|
| 1 | +export function createAstroRoute(client) { |
| 2 | + return async function astroRoute(ctx) { |
| 3 | + if (ctx.request.method === "HEAD") { |
| 4 | + return new Response(null, { status: 200 }); |
| 5 | + } |
| 6 | + |
| 7 | + try { |
| 8 | + // Prepare the request to be a fetch-compatible Request object: |
| 9 | + const requestHeaders = ctx.request.headers; |
| 10 | + const requestMethod = ctx.request.method; |
| 11 | + const responseHeaders = Object.create(null); |
| 12 | + |
| 13 | + for (const [headerName, headerValue] of requestHeaders.entries()) { |
| 14 | + responseHeaders[headerName] = headerValue; |
| 15 | + } |
| 16 | + |
| 17 | + // Create a new Request object to be passed to the TriggerClient |
| 18 | + // where we pass the clone the incoming request metadata such as |
| 19 | + // headers, method, body. |
| 20 | + const request = new Request("https://express.js/api/trigger", { |
| 21 | + headers: responseHeaders, |
| 22 | + method: requestMethod, |
| 23 | + body: ctx.request.body ? ctx.request.body : ctx.request, |
| 24 | + duplex: "half", |
| 25 | + }); |
| 26 | + |
| 27 | + // This handshake handler knows how to authenticate requests, |
| 28 | + // call the run() function of the job, and so on |
| 29 | + const response = await client.handleRequest(request); |
| 30 | + |
| 31 | + if (!response) { |
| 32 | + return new Response(JSON.stringify({ error: "Not found" }), { |
| 33 | + status: 404, |
| 34 | + }); |
| 35 | + } |
| 36 | + |
| 37 | + // Optionally can do something with the job's finished |
| 38 | + // execution's response body |
| 39 | + return new Response(JSON.stringify(response.body), { |
| 40 | + status: response.status, |
| 41 | + }); |
| 42 | + } catch (err) { |
| 43 | + return new Response(JSON.stringify({ error: "Internal server error" }), { |
| 44 | + status: 500, |
| 45 | + }); |
| 46 | + } |
| 47 | + }; |
| 48 | +} |
0 commit comments