diff --git a/examples/static_assets_server.ts b/examples/static_assets_server.ts index 35a078b..c32dc07 100644 --- a/examples/static_assets_server.ts +++ b/examples/static_assets_server.ts @@ -1,29 +1,12 @@ // Copyright 2021 Deno Land Inc. All rights reserved. MIT license. -import { createWorker } from "../mod.ts"; -import { - contentType, - lookup, -} from "https://deno.land/x/media_types@v2.9.0/mod.ts"; +import { createWorker, handlers } from "../mod.ts"; const staticAssets = await createWorker( "./examples/deploy_scripts/static_assets.ts", { name: "staticAssets", - async fetchHandler(evt) { - const url = new URL(evt.request.url); - if (url.protocol === "file:") { - const ct = contentType(lookup(evt.request.url) ?? "") ?? - "text/plain"; - const body = await Deno.readFile(url); - const response = new Response(body, { - headers: { - "content-type": ct, - }, - }); - evt.respondWith(response); - } - }, + fetchHandler: handlers.fileFetchHandler, }, ); diff --git a/lib/handlers.ts b/lib/handlers.ts new file mode 100644 index 0000000..e37c449 --- /dev/null +++ b/lib/handlers.ts @@ -0,0 +1,35 @@ +import { + contentType, + lookup, +} from "https://deno.land/x/media_types@v2.9.0/mod.ts"; + +import type { RequestEvent } from "../types.d.ts"; + +/** + * A fetch handler that returns local files that are requested by the worker. + * + * This is useful when the worker is attempting to access static assets from + * its repo using `import.meta.url` as the base for a fetch request. + */ +export async function fileFetchHandler(evt: RequestEvent) { + const url = new URL(evt.request.url); + if (url.protocol === "file:") { + const stat = await Deno.stat(url); + let response: Response; + if (stat.isFile) { + const ct = contentType(lookup(evt.request.url) ?? "") ?? "text/plain"; + const body = await Deno.readFile(url); + response = new Response(body, { + headers: { + "content-type": ct, + }, + }); + } else { + response = new Response(null, { + status: 404, + statusText: "Not Found", + }); + } + evt.respondWith(response); + } +} diff --git a/mod.ts b/mod.ts index 30bdf69..dc71bf4 100644 --- a/mod.ts +++ b/mod.ts @@ -2,6 +2,7 @@ export { createWorker } from "./lib/deploy_worker.ts"; export type { DeployWorker } from "./lib/deploy_worker.ts"; +export * as handlers from "./lib/handlers.ts"; export { LogLevel, setLevel as setLogLevel } from "./lib/logger.ts"; export * as testing from "./lib/testing.ts"; export type { DeployOptions, DeployWorkerInfo } from "./types.d.ts";