(request: Request, env: Env)
| 8 | |
| 9 | /** Adds the event to an AWS SQS queue, so it can be consumed from the main Trigger.dev API */ |
| 10 | export async function queueEvents(request: Request, env: Env): Promise<Response> { |
| 11 | //check there's a private API key |
| 12 | const apiKeyResult = getApiKeyFromRequest(request); |
| 13 | if (!apiKeyResult || apiKeyResult.type !== "PRIVATE") { |
| 14 | return json( |
| 15 | { error: "Invalid or Missing API key" }, |
| 16 | { |
| 17 | status: 401, |
| 18 | } |
| 19 | ); |
| 20 | } |
| 21 | |
| 22 | //parse the request body |
| 23 | try { |
| 24 | const anyBody = await request.json(); |
| 25 | const body = SendBulkEventsBodySchema.safeParse(anyBody); |
| 26 | if (!body.success) { |
| 27 | return json( |
| 28 | { error: generateErrorMessage(body.error.issues) }, |
| 29 | { |
| 30 | status: 422, |
| 31 | } |
| 32 | ); |
| 33 | } |
| 34 | |
| 35 | // The AWS SDK tries to use crypto from off of the window, |
| 36 | // so we need to trick it into finding it where it expects it |
| 37 | globalThis.global = globalThis; |
| 38 | |
| 39 | const client = new SQSClient({ |
| 40 | region: env.AWS_SQS_REGION, |
| 41 | credentials: { |
| 42 | accessKeyId: env.AWS_SQS_ACCESS_KEY_ID, |
| 43 | secretAccessKey: env.AWS_SQS_SECRET_ACCESS_KEY, |
| 44 | }, |
| 45 | }); |
| 46 | |
| 47 | const updatedEvents: ApiEventLog[] = body.data.events.map((event) => { |
| 48 | const timestamp = event.timestamp ?? new Date(); |
| 49 | return { |
| 50 | ...event, |
| 51 | payload: event.payload, |
| 52 | timestamp, |
| 53 | }; |
| 54 | }); |
| 55 | |
| 56 | //divide updatedEvents into multiple batches of 10 (max size SQS accepts) |
| 57 | const batches: ApiEventLog[][] = []; |
| 58 | let currentBatch: ApiEventLog[] = []; |
| 59 | for (let i = 0; i < updatedEvents.length; i++) { |
| 60 | currentBatch.push(updatedEvents[i]); |
| 61 | if (currentBatch.length === 10) { |
| 62 | batches.push(currentBatch); |
| 63 | currentBatch = []; |
| 64 | } |
| 65 | } |
| 66 | if (currentBatch.length > 0) { |
| 67 | batches.push(currentBatch); |
no test coverage detected
searching dependent graphs…