This repository has been archived on 2023-06-09. You can view files and clone it, but cannot push or open issues or pull requests.
deno-http/mod.ts

373 lines
10 KiB
TypeScript
Raw Normal View History

2023-05-10 12:21:20 +00:00
import {
Status,
STATUS_TEXT,
} from "https://deno.land/std@0.186.0/http/http_status.ts";
2023-05-10 12:57:29 +00:00
import * as path from "https://deno.land/std@0.185.0/path/mod.ts";
import * as cookie from "https://deno.land/std@0.185.0/http/cookie.ts";
2023-05-10 12:21:20 +00:00
type ListenOptions = {
port: number;
host?: string;
2023-05-10 12:57:29 +00:00
staticLocalDir?: string;
staticServePath?: string;
2023-05-10 12:21:20 +00:00
};
type HTTPMethod = "GET" | "POST" | "PUSH" | "DELETE";
type RouteHandler = (
req: RouteRequest,
2023-05-10 12:21:20 +00:00
rep: RouteReply,
) =>
| Promise<unknown>
| unknown;
2023-05-11 04:46:41 +00:00
export type RouteParam = {
idx: number;
paramKey: string;
};
2023-05-10 12:21:20 +00:00
export class HTTPServer {
private server?: Deno.Listener;
private routes = new Map<string, Route>();
2023-05-10 12:57:29 +00:00
private staticLocalDir?: string;
private staticServePath?: string;
2023-05-11 07:32:18 +00:00
private notFoundHandler?: RouteHandler;
2023-05-10 12:21:20 +00:00
async listen(options: ListenOptions) {
this.server = Deno.listen({
port: options.port,
hostname: options.host,
});
2023-05-10 13:00:17 +00:00
console.log(
`Listening on ${
options.host ? options.host : "http://localhost"
}:${options.port} !`,
);
2023-05-10 12:57:29 +00:00
if (options.staticLocalDir && options.staticServePath) {
this.staticLocalDir = options.staticLocalDir;
this.staticServePath = options.staticServePath;
}
2023-05-10 12:21:20 +00:00
for await (const conn of this.server) {
2023-05-10 17:03:24 +00:00
this.handleHttp(conn);
}
}
2023-05-11 04:46:41 +00:00
private async handleHttp(conn: Deno.Conn) {
2023-05-10 17:03:24 +00:00
const httpConn = Deno.serveHttp(conn);
2023-05-11 04:46:41 +00:00
for await (const requestEvent of httpConn) {
const url = new URL(requestEvent.request.url);
const filepath = decodeURIComponent(url.pathname);
2023-05-11 07:32:18 +00:00
const routeRequest = new RouteRequest(requestEvent.request);
const routeReply: RouteReply = new RouteReply();
2023-05-11 04:46:41 +00:00
if (this.staticServePath && filepath.startsWith(this.staticServePath)) {
const fileDir = filepath.split("/").slice(2).join("/");
const pathLoc = path.join(
Deno.cwd(),
this.staticLocalDir as string,
fileDir,
);
let file;
try {
file = await Deno.open(pathLoc, { read: true });
} catch {
// If the file cannot be opened, return a "404 Not Found" response
2023-05-11 07:32:18 +00:00
if (this.notFoundHandler) {
routeReply.status(Status.NotFound);
routeReply.type("application/json");
const notNoundHandle = await this.notFoundHandler(
routeRequest,
routeReply,
);
await requestEvent.respondWith(
new Response(notNoundHandle as string, {
status: routeReply.statusCode,
headers: routeReply.headers,
statusText: STATUS_TEXT[routeReply.statusCode],
2023-05-10 12:21:20 +00:00
}),
2023-05-11 07:32:18 +00:00
);
continue;
} else {
await requestEvent.respondWith(
new Response(
JSON.stringify({
code: 404,
message: `File ${filepath} not found!`,
}),
{
status: Status.NotFound,
headers: {
"Content-Type": "application/json",
},
},
),
);
}
2023-05-11 04:46:41 +00:00
continue;
2023-05-10 12:21:20 +00:00
}
2023-05-11 04:46:41 +00:00
const readableStream = file.readable;
const response = new Response(readableStream);
await requestEvent.respondWith(response);
return;
}
const routeName = `${requestEvent.request.method}@${filepath}`;
let route = this.routes.has(routeName)
? this.routes.get(routeName)
: undefined;
if (route) {
const handler = await route.handler(
routeRequest,
routeReply,
);
await requestEvent.respondWith(
new Response(handler as string, {
status: routeReply.statusCode,
headers: routeReply.headers,
statusText: STATUS_TEXT[routeReply.statusCode],
}),
);
continue;
}
route = Array.from(this.routes.values()).find((route) =>
routeWithParamsRouteMatcher(routeRequest, route)
);
if (route) {
const routeParamsMap: RouteParam[] = extractRouteParams(route.path);
const routeSegments: string[] = filepath.split("/");
routeRequest.pathParams = routeParamsMap.reduce(
2023-05-11 05:12:51 +00:00
(accum: { [key: string]: string }, curr: RouteParam) => {
2023-05-11 04:46:41 +00:00
return {
...accum,
[curr.paramKey]: routeSegments[curr.idx],
};
},
{},
);
const handler = await route.handler(
routeRequest,
routeReply,
);
await requestEvent.respondWith(
new Response(handler as string, {
status: routeReply.statusCode,
headers: routeReply.headers,
statusText: STATUS_TEXT[routeReply.statusCode],
}),
);
continue;
2023-05-10 12:21:20 +00:00
}
2023-05-11 07:32:18 +00:00
if (this.notFoundHandler) {
routeReply.status(Status.NotFound);
routeReply.type("application/json");
const notNoundHandle = await this.notFoundHandler(
routeRequest,
routeReply,
);
await requestEvent.respondWith(
new Response(notNoundHandle as string, {
status: routeReply.statusCode,
headers: routeReply.headers,
statusText: STATUS_TEXT[routeReply.statusCode],
2023-05-11 04:46:41 +00:00
}),
2023-05-11 07:32:18 +00:00
);
} else {
await requestEvent.respondWith(
new Response(
JSON.stringify({
code: 404,
message: `Route ${routeName} not found!`,
}),
{
status: Status.NotFound,
headers: {
"Content-Type": "application/json",
},
},
),
);
}
2023-05-11 04:46:41 +00:00
}
2023-05-10 12:21:20 +00:00
}
2023-05-11 08:29:21 +00:00
close() {
if (this.server) {
this.server.close();
}
}
2023-05-11 07:32:18 +00:00
error(handler: RouteHandler) {
this.notFoundHandler = handler;
}
2023-05-10 12:21:20 +00:00
get(path: string, handler: RouteHandler) {
this.add("GET", path, handler);
}
post(path: string, handler: RouteHandler) {
this.add("POST", path, handler);
}
push(path: string, handler: RouteHandler) {
this.add("PUSH", path, handler);
}
delete(path: string, handler: RouteHandler) {
this.add("DELETE", path, handler);
}
add(method: HTTPMethod, path: string, handler: RouteHandler) {
const route = new Route(path, method, handler);
2023-05-10 13:28:00 +00:00
if (this.routes.has(route.routeName)) {
console.log(`${route.routeName} already registered!`);
return;
}
2023-05-10 12:21:20 +00:00
this.routes.set(route.routeName, route);
console.log(`${route.routeName} added`);
}
}
2023-05-11 04:46:41 +00:00
export const routeWithParamsRouteMatcher = (
req: RouteRequest,
route: Route,
): boolean => {
const routeMatcherRegEx = new RegExp(`^${routeParamPattern(route.path)}$`);
return (
2023-05-11 06:11:11 +00:00
req.method as HTTPMethod === route.method &&
2023-05-11 04:46:41 +00:00
route.path.includes("/:") &&
routeMatcherRegEx.test(req.path)
);
};
export const routeParamPattern: (route: string) => string = (route) =>
route.replace(/\/\:[^/]{1,}/gi, "/[^/]{1,}").replace(/\//g, "\\/");
export const extractRouteParams: (route: string) => RouteParam[] = (route) =>
route.split("/").reduce((accum: RouteParam[], curr: string, idx: number) => {
if (/:[A-Za-z1-9]{1,}/.test(curr)) {
const paramKey: string = curr.replace(":", "");
const param: RouteParam = { idx, paramKey };
return [...accum, param];
}
return accum;
}, []);
2023-05-10 12:21:20 +00:00
export class Route {
routeName: string;
path: string;
method: HTTPMethod;
handler: RouteHandler;
constructor(path: string, method: HTTPMethod, handler: RouteHandler) {
this.path = path;
this.method = method;
this.routeName = `${method}@${path}`;
this.handler = handler;
}
}
export class RouteRequest {
2023-05-11 04:46:41 +00:00
url: string;
path: string;
headers: Headers;
2023-05-11 06:11:11 +00:00
method: HTTPMethod;
2023-05-11 05:03:10 +00:00
queryParams: { [key: string]: string };
pathParams: { [key: string]: string };
constructor(request: Request) {
2023-05-11 04:46:41 +00:00
this.url = request.url;
const urlObj = new URL(request.url);
this.path = decodeURIComponent(urlObj.pathname);
this.headers = request.headers;
2023-05-11 06:11:11 +00:00
this.method = request.method as HTTPMethod;
2023-05-11 04:46:41 +00:00
this.pathParams = {};
2023-05-11 05:03:10 +00:00
this.queryParams = this.paramsToObject(urlObj.searchParams.entries());
}
2023-05-11 05:03:10 +00:00
private paramsToObject(entries: IterableIterator<[string, string]>) {
const result: { [key: string]: string } = {};
for (const [key, value] of entries) {
result[key] = value;
}
return result;
}
header(name: string): unknown {
const matchingHeader = Array.from(this.headers.keys()).find((headerName) =>
headerName === name
);
return matchingHeader ? this.headers.get(matchingHeader) : undefined;
}
2023-05-11 05:03:10 +00:00
cookie(name: string): unknown {
const allCookies = cookie.getCookies(this.headers);
const allCookieNames = Object.keys(allCookies);
return allCookieNames.includes(name) ? allCookies[name] : undefined;
}
2023-05-11 05:03:10 +00:00
pathParam(name: string): string {
return this.pathParams[name];
}
queryParam(name: string): string {
return this.queryParams[name];
}
}
2023-05-10 12:21:20 +00:00
export class RouteReply {
headers: Headers = new Headers();
statusCode: Status = Status.OK;
header(name: string, value: string): RouteReply {
this.headers.set(name, value);
return this;
2023-05-10 12:21:20 +00:00
}
status(code: Status): RouteReply {
this.statusCode = code;
return this;
}
type(type: string): RouteReply {
this.header("Content-Type", type);
return this;
}
cookie(name: string, value: string, attributes?: {
expires?: Date | number;
maxAge?: number;
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: "Strict" | "Lax" | "None";
unparsed?: string[];
2023-05-11 04:46:41 +00:00
}): RouteReply {
if (!value) {
cookie.deleteCookie(this.headers, name, {
domain: attributes?.domain,
path: attributes?.path,
});
} else {
cookie.setCookie(this.headers, {
name: name,
value: value,
expires: attributes?.expires,
maxAge: attributes?.maxAge,
domain: attributes?.domain,
path: attributes?.path,
secure: attributes?.secure,
httpOnly: attributes?.httpOnly,
sameSite: attributes?.sameSite,
unparsed: attributes?.unparsed,
});
}
2023-05-11 04:46:41 +00:00
return this;
}
2023-05-11 04:46:41 +00:00
}