Debugging fetch in a consumer

Yes, I'm awaiting the fetch and I also put inside a try/catch, but no error is logged. The last log I see is the API URL log, and then the code skips everything below the log
try {
console.log('API URL :', `${env.STRAPI_API_URL}/c-orders`);
const connection = await fetch(`${env.STRAPI_API_URL}/c-orders`, {
headers: {
Authorization: `Bearer ${env.STRAPI_API_KEY}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
data: {
planId,
date: new Date(),
deliveryDate: new Date(deliveryDate * 1000),
status: 1,
details,
grossPrice: totalPrice,
finalPrice: totalPrice,
subscriptionId: subscription ? strapiSubscriptionId : null,
userId,
paymentId: paymentIntent,
paymentStatus: subscription ? 'processing' : 'success',
orderInfo: [],
stripeInvoiceId: invoice,
},
}),
});

console.log('connection :', connection);
const data = await connection.json();
console.log('data :', JSON.stringify(data, null, 2));

if (connection.status !== 200) wasOrderCreated = false;

wasOrderCreated = true;
} catch (err) {
console.log('err :', err);
return false;
}
try {
console.log('API URL :', `${env.STRAPI_API_URL}/c-orders`);
const connection = await fetch(`${env.STRAPI_API_URL}/c-orders`, {
headers: {
Authorization: `Bearer ${env.STRAPI_API_KEY}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
data: {
planId,
date: new Date(),
deliveryDate: new Date(deliveryDate * 1000),
status: 1,
details,
grossPrice: totalPrice,
finalPrice: totalPrice,
subscriptionId: subscription ? strapiSubscriptionId : null,
userId,
paymentId: paymentIntent,
paymentStatus: subscription ? 'processing' : 'success',
orderInfo: [],
stripeInvoiceId: invoice,
},
}),
});

console.log('connection :', connection);
const data = await connection.json();
console.log('data :', JSON.stringify(data, null, 2));

if (connection.status !== 200) wasOrderCreated = false;

wasOrderCreated = true;
} catch (err) {
console.log('err :', err);
return false;
}
19 Replies
elithrar
elithrar16mo ago
Can you show the entire consumer code, just to make sure nothing is missed? And is this running locally or is it deployed? cc @Charlie B | KV, Queues, PubSub
nuno
nunoOP16mo ago
async queue(batch: MessageBatch<Stripe.Event>, env: Env): Promise<void> {
console.log('batch :', JSON.stringify(batch, null, 2));

batch.messages.forEach(async (m) => {
if (isStripeEvent(m.body))
(await handleStripeEvents(m.body, env)) ? m.ack() : m.retry();
});
},
async queue(batch: MessageBatch<Stripe.Event>, env: Env): Promise<void> {
console.log('batch :', JSON.stringify(batch, null, 2));

batch.messages.forEach(async (m) => {
if (isStripeEvent(m.body))
(await handleStripeEvents(m.body, env)) ? m.ack() : m.retry();
});
},
export async function handleStripeEvents(
event: Stripe.Event,
env: Env,
): Promise<boolean> {
switch (event.type) {
case 'checkout.session.completed':
return await checkoutCompleted(event, env);
case 'invoice.payment_succeeded':
case 'invoice.payment_failed':
return true;
}

return true;
}
export async function handleStripeEvents(
event: Stripe.Event,
env: Env,
): Promise<boolean> {
switch (event.type) {
case 'checkout.session.completed':
return await checkoutCompleted(event, env);
case 'invoice.payment_succeeded':
case 'invoice.payment_failed':
return true;
}

return true;
}
nuno
nunoOP16mo ago
I tried both, same behavior
John Spurlock
John Spurlock16mo ago
did you try a normal for of loop instead of batch.messages.forEach ? what you have now will just create a bunch of unresolved promises - forEach is not really ideal for async
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
John Spurlock
John Spurlock16mo ago
us meaning cloudflare? Hopefully you are not using batch.messages.forEach in any public samples!
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
John Spurlock
John Spurlock16mo ago
ideally cf would show the logs even from work that occurs after the queue handler returns
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
John Spurlock
John Spurlock16mo ago
i wonder what the guidance/semantics is around work intended to be deferred until after the queue handler returns (ie not really like this case) - same as with fetch handlers: waitUntil? Or do you wait for all pending promises up to a certain limit like DO
nuno
nunoOP16mo ago
Not sure if this is the case here. I'm just triggering one event at a time, but if this code isn't ideal I'll change and test
John Spurlock
John Spurlock16mo ago
that foreach is sync and will fire off your code async, and not wait for it yea just change to for (const m of batch.messages) { that way you can wait for the results or await Promise.all(batch.messages.map(work)) if you want to be fancy and run them all in parallel (prob overkill in your case)
nuno
nunoOP16mo ago
Got it thank, will do It works, thanks @John Spurlock <a:wumpus_party:393564669765353483>
John Spurlock
John Spurlock16mo ago
nice! that'll be better for errors too, if your external fetch call throws, the error will now be raised up and out of the queue handler - triggering the infrastructure to retry that message later, which is probably what you want never mind, you have a giant try catch around it! : )
nuno
nunoOP16mo ago
Got it, thanks for your explanation and help
elithrar
elithrar16mo ago
waitUntil. Anything else is undefined (and should, as of now, be cancelled immediately when the handler returns)
John Spurlock
John Spurlock16mo ago
thanks - wouldn't expect deferred logic to be nearly as desired for queue where no clients are potentially waiting vs fetch where they potentially are - and most failures I'd imagine you'd want to wait for, before ack or not. only use case for deferred/waitUntil I could see for queue logic is analytics pings, where you might not want them in the critical path for processing, and don't care if some never make it
elithrar
elithrar16mo ago
Yep, that's exactly right - metrics/logging after the fact. We should probably document this a little more clearly and although forEach and the interaction with promises isn't our problem, also document that cc @Charlie B | KV, Queues, PubSub ^
Want results from more Discord servers?
Add your server