Skip to content

Commit

Permalink
New update
Browse files Browse the repository at this point in the history
  • Loading branch information
datkat21 committed Nov 9, 2023
1 parent 78006ea commit 08fab9b
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 40 deletions.
74 changes: 46 additions & 28 deletions handlers/handling.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,27 @@
import { BunFile } from "bun";
import path from "path";
interface FileOnlyOptions {
enabled: boolean;
directory: string;
}

export interface ReqHandler {
interface ReqHandler {
urlPath: string;
handler: CallableFunction;
handler?: CallableFunction;
fomOptions?: FileOnlyOptions;
}

export type { ReqHandler, FileOnlyOptions };

export function returnNotFound() {
return new Response("404 Not Found", {
status: 404,
headers: { "Content-Type": "text/html" },
});
}

export interface Route {
/**
* The path of the route, e.g. `/` or `/chat`.
*/
urlPath: string;
handler: CallableFunction;
}

export function fileOnlyHandlers(url: URL) {
return new Response(Bun.file(url.pathname));
}

export interface RouteArguments {
req: Request;
url: URL;
route: Route;
route: ReqHandler;
params: URLSearchParams;
}

Expand All @@ -48,12 +41,19 @@ export function generateRequestHandler(
urlPath = "/index.html";
}

let route: Route | null;
let route: ReqHandler | null;
try {
route = handlers.find((r: Route) => {
if (r.urlPath.endsWith(url.pathname))
// if (r.path.exec(url.pathname) !== null && r.method === req.method)
return r;
route = handlers.find((r: ReqHandler) => {
if (r.fomOptions !== undefined && r.fomOptions.enabled === true) {
// console.log("fom found:", r);
if (url.pathname.startsWith(r.urlPath))
// if (r.path.exec(url.pathname) !== null && r.method === req.method)
return r;
} else {
if (r.urlPath.endsWith(url.pathname))
// if (r.path.exec(url.pathname) !== null && r.method === req.method)
return r;
}
});
} catch (e: any) {
return new Response(e, { status: 500 });
Expand All @@ -62,30 +62,37 @@ export function generateRequestHandler(
// If there's no such route, show a 404
if (!route) return fofHandler();

const params = new URLSearchParams(url.search)
const params = new URLSearchParams(url.search);

// Run the route's handler
return await route?.handler({ req, url, route, params } as RouteArguments);
if (route.handler !== undefined)
return await route.handler({ req, url, route, params } as RouteArguments);
else return fofHandler();
}

return requestHandler;
}

import { join } from "path";

export function fileOnlyReqHandler(staticFilePath: string = "public") {
export function fileOnlyReqHandler(
prefix: string = "/public",
staticFilePath: string = "public"
) {
async function requestHandler(req: Request) {
// Generate URL from request data
const url = new URL(req.url);

// Fall back to public directory
let urlPath = url.pathname;
let urlPath = url.pathname.substring(prefix.length);

// default handlers built into the program
if (urlPath.endsWith("/")) {
if (urlPath.endsWith("/") || urlPath === "") {
urlPath = "/index.html";
}

// console.log(prefix, staticFilePath, urlPath);

return new Response(Bun.file(join(staticFilePath, urlPath)));
}

Expand Down Expand Up @@ -117,6 +124,17 @@ export function editCookie(name: string, value: string) {
});
}

/// Delete a cookie
export function deleteCookie(name: string, value: string) {
return new Response("Cookie Edited", {
headers: {
"Set-Cookie": `${name}=${value}; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
},
status: 301,
statusText: "Moved",
});
}

/// Return any raw file you would like, headers will be filled out by Bun.file()
export function rawFile(path: string) {
// return rawFile = Bun.file -> Response;
Expand Down
23 changes: 15 additions & 8 deletions handlers/serverConstructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {

interface MiniDxServerOptions {
enableWs?: boolean;
fileOnlyMode?: boolean;
staticFilePath?: string;
}

Expand All @@ -23,7 +22,7 @@ interface MiniDxServerConfig {
export function miniServer(config: MiniDxServerConfig): Server {
// Assign default port
if (!config.port) config.port = 3000;

// Assign default FoF handler
if (!config.fofHandler) config.fofHandler = returnNotFound;
// Assign default error handler
if (!config.errorHandler)
Expand Down Expand Up @@ -54,23 +53,31 @@ export function miniServer(config: MiniDxServerConfig): Server {
if (!config.options)
config.options = {
enableWs: false,
fileOnlyMode: false,
staticFilePath: "public",
};

if (config.handlers === undefined && config.options.fileOnlyMode !== true) {
if (config.handlers === undefined) {
/**
* This text shows up somewhere
*/
throw new Error("No handlers assigned to your server");
} else {
config.handlers = config.handlers.map((h) => {
if (h.fomOptions?.enabled === true) {
h.handler = fileOnlyReqHandler(h.urlPath, h.fomOptions.directory);
return h;
} else {
return h;
}
});
}
if (!config.handlers) config.handlers = [];

// Generate request handler
const fetchHandler =
config.options.fileOnlyMode == false
? generateRequestHandler(config.handlers, config.fofHandler)
: fileOnlyReqHandler(config.options.staticFilePath);
const fetchHandler = generateRequestHandler(
config.handlers,
config.fofHandler
);

// Return final server
return Bun.serve({
Expand Down
21 changes: 17 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { miniServer } from "./handlers/serverConstructor";
// weird bun fix
import {
FileOnlyOptions,
RouteArguments,
ReqHandler,
} from "./handlers/handling";

export default {
miniServer
};
export type { FileOnlyOptions, RouteArguments, ReqHandler };

export {
createCookie,
deleteCookie,
editCookie,
pageBuilder,
rawFile,
} from "./handlers/handling";

export { miniServer } from "./handlers/serverConstructor";
37 changes: 37 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 08fab9b

Please sign in to comment.