Skip to content
This repository has been archived by the owner on Nov 8, 2022. It is now read-only.

Commit

Permalink
feat: add fileFetchHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
kitsonk committed Jun 28, 2021
1 parent a741887 commit c9c32c9
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 19 deletions.
21 changes: 2 additions & 19 deletions examples/static_assets_server.ts
Original file line number Diff line number Diff line change
@@ -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,
},
);

Expand Down
35 changes: 35 additions & 0 deletions lib/handlers.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

0 comments on commit c9c32c9

Please sign in to comment.