Skip to content

Commit

Permalink
update itty-router, use built-in cors support
Browse files Browse the repository at this point in the history
  • Loading branch information
mdtanrikulu committed Dec 4, 2023
1 parent 9a849fc commit 9e44ba3
Show file tree
Hide file tree
Showing 4 changed files with 412 additions and 86 deletions.
4 changes: 2 additions & 2 deletions packages/worker/package.json
Expand Up @@ -61,7 +61,7 @@
"typescript": "^4.7.4"
},
"dependencies": {
"ethers": "^5.3.1",
"itty-router": "^2.6.1"
"ethers": "^5.7.2",
"itty-router": "^4.0.3"
}
}
37 changes: 23 additions & 14 deletions packages/worker/src/index.ts
@@ -1,9 +1,19 @@
import { ethers, BytesLike } from 'ethers';
import { Fragment, FunctionFragment, Interface, JsonFragment } from '@ethersproject/abi';
import { hexlify } from '@ethersproject/bytes';
import { Router } from 'itty-router';
import { Router, createCors } from 'itty-router';
import { isAddress, isBytesLike } from 'ethers/lib/utils';
import { IRequest, handleCors } from './utils/cors';

const { corsify, preflight } = createCors();

type MethodType = 'GET' | 'POST';

export interface IRequest extends Request {
params: any;
method: MethodType;
url: string;
optional?: string;
}

export interface RPCCall {
to: BytesLike;
Expand Down Expand Up @@ -115,18 +125,15 @@ export class Server {
* in a smart contract would be "https://example.com/{sender}/{callData}.json".
* @returns An `itty-router.Router` object configured to serve as a CCIP read gateway.
*/
makeApp(prefix: string, corsEnabled?: false): Router {
makeApp(prefix: string) {
const app = Router();
app.get(prefix, () => new Response('hey ho!', { status: 200 }));
/*
* uncomment app.options for cors
* also wrap responses with cors wrapper
* e.g. return wrapCorsHeader(new Response('Invalid request format', { status: 400 }));
*/
if (corsEnabled) {
app.options(`${prefix}:sender/:callData.json`, handleCors({ methods: 'GET', maxAge: 86400 }));
app.options(prefix, handleCors({ methods: 'POST', maxAge: 86400 }));
}
app.all('*', preflight);
app.get(`${prefix}:sender/:callData.json`, this.handleRequest.bind(this));
app.post(prefix, this.handleRequest.bind(this));
return app;
Expand All @@ -151,14 +158,16 @@ export class Server {

try {
const response = await this.call({ to: sender, data: callData });
return new Response(JSON.stringify(response.body), {
status: response.status,
headers: {
'Content-Type': 'application/json',
},
});
return corsify(
new Response(JSON.stringify(response.body), {
status: response.status,
headers: {
'Content-Type': 'application/json',
},
})
);
} catch (e) {
return new Response(`Internal server error: ${(e as any).toString()}`, { status: 500 });
return corsify(new Response(`Internal server error: ${(e as any).toString()}`, { status: 500 }));
}
}

Expand Down
66 changes: 0 additions & 66 deletions packages/worker/src/utils/cors.ts

This file was deleted.

0 comments on commit 9e44ba3

Please sign in to comment.