#Returning multiple API responses in Action

50 messages · Page 1 of 1 (latest)

naive steeple
#

I have an action where I fetch data from 2 API endpoints. But I can't seem to return both of them and I don't understand why.

if (product.ok && stock.ok) {
    const stockData = await stock.json();
    const productData = await product.json();

    return {
        statusCode: 200,
        body: JSON.stringify({
            stock: stockData,
            product: productData,
        }),
    };
} else {
    throw new Error(`HTTP error! status: ${product.status}`);
}

This doesn't work for example. But if I do simply:

body: await stock.json()

or

body: await product.json()

Then it does work.

Anyone know why I can't return both at the same time?

#

To clarify further, the console log, when the 2 responses are merged is simply empty. Not null or undefined. Just empty.

wheat vine
#
if (product.ok && stock.ok) {
    const [stockData, productData] = await Promise.all([stock.json(), product.json()]);

    return {
        statusCode: 200,
        body: JSON.stringify({
            stock: stockData,
            product: productData,
        }),
    };
} else {
    throw new Error(`HTTP error! status: ${product.status}`);
}
#

Try this

naive steeple
#

Unfortunately that doesn't work either

#

This is the code that should log it:

const productStock = Astro.getActionResult(actions.getStock);
console.log(productStock);
#

The terminal only shows this:

18:01:42 [200] POST / 90ms
#

no console log

wheat vine
#

If you return just stockData it works though?

naive steeple
#

Yes.

return {
  statusCode: 200,
  body: await stock.json()
};
18:07:19 [200] POST / 85ms
{
  data: { statusCode: 200, body: { Result: [Array] } },
  error: undefined
}
#

This is the complete code:

getStock: defineAction({
    accept: "form",
    input: z.object({
        "article-number": z.string(),
    }),
    handler: async (input) => {
        const URL = import.meta.env.TEST_URL;
        const articleNumber = input["article-number"];
        const stock = await fetch(`${URL}/json/endpoint1`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: articleNumber,
        });

        const product = await fetch(`${URL}/json/endpoint2`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify([articleNumber]),
        });

        if (product.ok && stock.ok) {
            // const stockData = await stock.json();
            // const productData = await product.json();

            return {
                statusCode: 200,
                body: await stock.json()
            };
        } else {
            throw new Error(`HTTP error! status: ${product.status}`);
        }
    },
}),
wheat vine
#
if (product.ok && stock.ok) {
    const stockData = await stock.json();
    // const productData = await product.json();

    return {
        statusCode: 200,
        body: stockData
    };
} else {
    throw new Error(`HTTP error! status: ${product.status}`);
}

Does this work?

naive steeple
#

yes

wheat vine
#
getStock: defineAction({
    accept: "form",
    input: z.object({
        "article-number": z.string(),
    }),
    handler: async (input) => {
        const URL = import.meta.env.TEST_URL;
        const articleNumber = input["article-number"];

        
        const [stockResponse, productResponse] = await Promise.all([
            fetch(`${URL}/json/endpoint1`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ articleNumber }),
            }),
            fetch(`${URL}/json/endpoint2`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify([articleNumber]),
            })
        ]);


        if (stockResponse.ok && productResponse.ok) {
        const [stockData, productData] = await Promise.all([
                stockResponse.json(),
                productResponse.json(),
            ]);

            return {
                statusCode: 200,
                body: JSON.string({
                  stock: stockData,
                  product: productData,
    }),
            };
        } else {
            throw new Error(`HTTP error! stock: ${stockResponse.status}, product: ${productResponse.status}`);
        }
    },
}),

naive steeple
#

empty again

#

I changed JSON.string to JSON.stringify too

wheat vine
#

My bad. Mistyped it lol

naive steeple
#

no worries, I appreciate the help

wheat vine
#

Wrap it in Backticks

naive steeple
#

also empty

#

if one of the responses is not 'ok' I do get a console log

opaque arch
naive steeple
#

beyond my skill level unfortunately

slender sable
#

Darn ChatGPT. I thought it had the code right. Lol

wheat vine
#

Is your repo public?

opaque arch
naive steeple
#

The 2 arrays combined are less than 250 lines long. Dunno if that exceeds some kind of limit

wheat vine
#

Yeah. If you can send a mock array. I can play around
With it and see

slender sable
#

I added two console.logs and it should hopefully give you some feedback in your terminal when you try to use the code.

naive steeple
wheat vine
#

Okay. ONe sec

#

Let me see

naive steeple
#

individually they're working just fine. I just can't combine them into one and return them

wheat vine
#

Can we get on a call to take a look? Would be a bit easier

naive steeple
#

I'm not set up for that unfortunately

naive steeple
#

@wheat vine did you get anywhere with this?

#

curious if you were able to make it work

wheat vine
#

I got busy and havent had

#

a chance to lok more into it

naive steeple
#

ah gotcha

#

no worries

naive steeple
#

I think it has something to do with the length

#

If I return 3867 zero's, it works. If I send 3868 zero's it doesn't.

#

@wheat vine should I report this somewhere? (sorry for the ping)

#

what's weird though, it that my array is 2068 characters long.

#

But if I trim it to 1550, it works again

naive steeple
#

I think because the data is returned in a cookie there's a 4kb limit I may be hitting