import { existsSync, promises as fs } from "fs"; import _locreq from "locreq"; import { resolve } from "path"; import { generateRoutes } from "./generate-routes.js"; import { escape_url_params } from "./utils/escape-url-params.js"; import prompts from "prompts"; import { Templates } from "./templates/templates.js"; import { toKebabCase, toPascalCase } from "js-convert-case"; export async function addRoute( params: Partial<{ [key in "action" | "url" | "mode"]: string }>, app_directory: string = process.cwd() ): Promise { const target_locreq = _locreq(app_directory); prompts.override(params); const response = await prompts([ { type: "text", name: "action", message: 'What\'s the name of the action (e.g. "AddUser"): ', validate: (s: string) => s.length > 3 ? true : "Should be at least 3 characters long", format: function (action: string) { return toPascalCase(action); }, }, { type: "text", name: "url", message: "Enter a full absolute path for the new route (for example: /admin/users/:id/edit): ", validate: (s: string) => s.trim()[0] == "/" ? true : "Should start with a '/'", initial: function (_, { action }: { action: string }) { return "/" + toKebabCase(action); }, }, { type: "select", name: "mode", message: "What kind of route is it?", choices: [ { title: "page", value: "page" }, { title: "stateful page", value: "sreact" }, { title: "form", value: "form" }, { title: "list", value: "list" }, { title: "multiform", value: "multiform" }, { title: "redirect", value: "redirect" }, { title: "raw POST", value: "post" }, { title: "Long Running Process status page", value: "lpr" }, { title: "JDD content editor", value: "jdd-editor" }, ], }, ]); const { action, url, mode } = response as Record; const extension = ["list", "lpr", "page", "sreact", "jdd-editor"].includes( mode ) ? "tsx" : "ts"; const base_file_name = escape_url_params(url) || "index"; const file_path = target_locreq.resolve( `src/back/routes/${base_file_name}.${mode}.${extension}` ); const test_file_path = target_locreq.resolve( `src/back/routes/${base_file_name}.test.ts` ); const template = Templates[mode]; if (!template) { throw new Error(`Could not get template ${mode}`); } if (existsSync(file_path)) { console.error(`ERROR: File ${file_path} already exists.`); return; } await fs.mkdir(resolve(file_path, "../"), { recursive: true }); await fs.writeFile(file_path, await template(action, file_path)); console.info(`${file_path} created`); console.info(`${test_file_path} created`); await generateRoutes(); }