Skip to content

Commit

Permalink
chore: dispatchFetch implemented on eval
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Apr 15, 2024
1 parent 065afa8 commit c11d262
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
37 changes: 36 additions & 1 deletion packages/workerd/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,45 @@ export function vitePluginWorkerd(pluginOptions: WorkerdPluginOptions): Plugin {
return;
}
const devEnv = server.environments["workerd"] as WorkerdDevEnvironment;

// implement dispatchFetch based on eval
const dispatchFetch = async (request: Request): Promise<Response> => {
const result = await devEnv.api.eval({
entry,
args: [
{
url: request.url,
method: request.method,
headers: [...request.headers.entries()],
body: ["HEAD", "GET"].includes(request.method)
? null
: await request.text(),
},
],
fn: async ({ mod, args: [{ url, method, headers, body }], env }) => {
const request = new Request(url, { method, headers, body });
const response: Response = await mod.default.fetch(request, env);
return {
headers: [...response.headers.entries()],
status: response.status,
body: await response.text(),
};
},
});
return new Response(result.body, {
status: result.status,
headers: result.headers,
});
};

const nodeMiddleware = createMiddleware(
(ctx) => devEnv.api.dispatchFetch(entry, ctx.request),
(ctx) => dispatchFetch(ctx.request),
{ alwaysCallNext: false },
);
// const nodeMiddleware = createMiddleware(
// (ctx) => devEnv.api.dispatchFetch(entry, ctx.request),
// { alwaysCallNext: false },
// );
return () => {
server.middlewares.use(nodeMiddleware);
};
Expand Down
3 changes: 2 additions & 1 deletion packages/workerd/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@ export function getRunnerFetchOptions(headers: Headers): RunnerFetchOptions {
return JSON.parse(decodeURIComponent(raw));
}

// TODO: infer Args and Return
export type EvalFn = (ctx: { mod: any; args: any[]; env: any }) => any;

export type EvalApi = (request: {
entry: string;
fn: EvalFn;
args: any[];
args: any[]; // data?
serializerEntry?: string;
serializer?: EvalSerializer;
}) => Promise<any>;
Expand Down

0 comments on commit c11d262

Please sign in to comment.