Skip to content

Commit

Permalink
chore: Itty-router v5 migration
Browse files Browse the repository at this point in the history
  • Loading branch information
pigri committed Apr 12, 2024
1 parent 7119a57 commit e9763b8
Showing 1 changed file with 29 additions and 21 deletions.
50 changes: 29 additions & 21 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { createCors, error, Router } from 'itty-router';
import { cors, error, AutoRouter } from 'itty-router';
import { xxhash64 } from 'cf-workers-hash';

const { preflight, corsify } = createCors({
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],
const { preflight } = cors();
const router = AutoRouter({
});
const router = Router();

async function deduplication(request: Request, env: Env) {
if (!env.DEDUPLICATION) return false;
Expand Down Expand Up @@ -41,17 +40,22 @@ async function proxy (request: Request, env: Env) {
case 'PUT':
case 'PATCH':
case 'DELETE':
if (await deduplication(request, env)) {
return new Response(null, {
status: 202,
statusText: 'Accepted',
try {
if (await deduplication(request, env)) {
return new Response(null, {
status: 202,
statusText: 'Accepted',
});
}
return await fetch(proxyUrl, {
method: request.method,
body: request.body,
headers: request.headers,
});
} catch (e) {
console.error(JSON.stringify(e));
return error(500);
}
return await fetch(proxyUrl, {
method: request.method,
body: request.body,
headers: request.headers,
});
case 'OPTIONS':
return new Response(null, {
status: 204,
Expand All @@ -78,12 +82,16 @@ async function proxy (request: Request, env: Env) {
}

async function createNewRequest(request: Request): Promise<Request> {
const { url, method, headers } = request;
if (method === 'GET' || method === 'HEAD') {
return new Request(url, { method, headers });
} else {
const body = await request.text();
return new Request(url, { method, headers, body });
try {
const { url, method, headers } = request;
if (method === 'GET' || method === 'HEAD') {
return new Request(url, { method, headers });
} else {
const body = await request.text();
return new Request(url, { method, headers, body });
}
} catch (e) {
throw e;
}
}

Expand All @@ -102,7 +110,7 @@ type MessageBatch = {
router
.all('*', preflight)
.all('/webhook/:id', async (request: Request, env: Env, _: ExecutionContext) => {
try {
try {
const newRequest = await createNewRequest(request);
const response = await proxy(newRequest, env);
const responseClone = response.clone();
Expand Down Expand Up @@ -138,7 +146,7 @@ router

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return router.handle(request, env, ctx).then(corsify);
return router.fetch(request, env, ctx);
},
async queue(batch: MessageBatch, env: Env): Promise<void> {
for (const message of batch.messages) {
Expand Down

0 comments on commit e9763b8

Please sign in to comment.