UNPKG

hotshot-mod-manager

Version:

93 lines (78 loc) 2.66 kB
import inquirer from "inquirer"; import fs from "node:fs"; import path from "node:path"; import { cleanupString, configPath, getConfig, nameFixer } from "../main.js"; export async function middlewareGenTrigger() { const { middlewareName } = await inquirer.prompt([ { type: "input", name: "middlewareName", message: "Enter the name of the middleware:", validate: (input) => input.trim() ? true : "Middleware name cannot be empty.", }, ]); if (middlewareName) { await generateMiddleware(cleanupString(middlewareName)); } } export async function generateMiddleware(middlewareName) { const config = await getConfig(); if ( config?.useGuards?.find((m) => m.name === middlewareName) ) { throw new Error( `Error: UseGuard '${middlewareName}' already exists in config.`, ); } const middlewareContent = middlewareContents(middlewareName); /* |----------------------------------------------------------------------- | File System IO |----------------------------------------------------------------------- */ const middlewareDirPath = path.join( process.cwd(), "src", "use_guards", ); fs.mkdirSync(middlewareDirPath, { recursive: true }); fs.writeFileSync( path.join(middlewareDirPath, `${middlewareName}_guard.ts`), middlewareContent, ); /* |----------------------------------------------------------------------- | Config Update |----------------------------------------------------------------------- */ config?.useGuards?.push({ name: middlewareName, path: `./src/use_guards/${middlewareName}_guard`, }); const updatedConfigContent = JSON.stringify(config, null, 2); fs.writeFileSync(configPath, updatedConfigContent); } /* |----------------------------------------------------------------------- | Middleware Contents |----------------------------------------------------------------------- */ function middlewareContents(middlewareName) { const middlewareClassName = `${nameFixer(middlewareName, true)}Guard`; return ` import { type UseGuard, HTTPStatus } from "@a4arpon/hotshot"; import type {Context, Next} from "hono"; import { HTTPException } from "hono/http-exception" export class ${middlewareClassName} implements UseGuard { async use(ctx: Context) { if (ctx.req.path === "/${middlewareName.toLowerCase()}-guard") { throw new HTTPException(HTTPStatus.BadRequest, { message: "You're hitting on a dummy route", }); } console.log("${middlewareClassName} Activated On", ctx.req.path); return true; } }`; }