How to send custom json response from server action?

I have three table product, seller, slots. Each table contain a field called seller_id which connects the data between them. Here is the server action I want to perform.
I want to fetch all the products from the products table, then using the seller_id field value of the product I want to fetch the seller. Here the seller_id is unique in seller table, which means the response will be a single row. And the using the same technique I want to fetch the slots based on the seller_id value. Now, here the slots result can be multiple rows, because seller_id here is not unique. And I want all those data as an array in a single product items.

Simply speaking, this is how I want my result

{
  query:[
    {
      product:product_details,
      seller: seller_details,
      slots:[
           {
              slots:slot_details
          },
..........
         ]
    },
.
.
.
.
.
  ]
}

How can I develop a server action which takes less time interval ?

Hi.
Not sure how familiar you are with SQL, but you need to make sure to select correct join type & put in correct conditions to get correct data from product & seller tables.
Then you can run a repeat on this query’s result, which has all the products.
Inside the repeat, run another query which will fetch data from slot table.
Make sure to set output fields of the repeat & enable output of both repeat & inner query step.

Its all quite easy actually.
Also, the reponse of a Server Action is (almost) always a JSON. The response of queries & repeat will also be returned as JSON.

My old approach was same as you explained, I repeat the product tables response to get the seller_id and then inside the repeat make use of multiple query to fetch the slots. But this approach is very time consuming, and I want less time consuming method

This is my old approach

Ok.
I can suggest two approaches here:

  1. Write a query that returns all the data in rows. Then use Wappler’s group by formatters to group that information and return that in response via set value.
  2. Write a custom query that can generate the json string in the way you want as response of query itself, then parse the string as JSON and return that.

We are using both in different project/places and are definitely faster than repeat.

1 Like

Thank you for your solutions.

I used your first solution which worked, small edit to your first solution. In order to get custom response, one must use the server content editor in set value.

1 Like

What is that? Can you share a screenshot?
Maybe you are talking about schema.

This is the server content editor where you can customise your data response in server.

Ah. I never read the header in 2+ years. Its all just popups. :sweat_smile:

You can actually write the same thing directly in the input, without opening the editor. But you have to type manually. Editor gives picker options.