All files file-router.ts

92.45% Statements 98/106
82.75% Branches 24/29
100% Functions 4/4
92.45% Lines 98/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 1251x 1x 1x 1x               1x 16x 16x 14x 14x 14x 14x 14x 14x 30x 2x 2x 30x 5x 5x 23x 14x 14x 14x 14x 14x   1x     2x 2x   2x   2x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 3x 2x 2x 2x 2x 2x 2x 2x     3x 3x 9x 2x 2x   9x 9x 9x 9x     1x       1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 2x 1x 7x         7x 5x 5x 5x 7x 2x 2x 2x 7x 2x 2x 2x 2x 2x 7x 7x 1x 1x 1x  
import express, { type Router } from "express";
import { loadModulesfromDir } from "./file-module";
import { type Handler, handleResponse, isHandler } from "./handler";
import { getLogger } from "./log";
 
export type FileRoute = {
  filePath: string;
  GET?: Handler;
  POST?: Handler;
};
 
export function getExpressRoutePath(relativePath: string): string {
  const log = getLogger("express-router");
  if (relativePath === "index.tsx") return "/";
  const expressPath = relativePath
    .replace(/\/index.tsx$/, "")
    .replace(/index.tsx$/, "")
    .replace(/\.tsx$/, "")
    .split("/")
    .map((part) => {
      if (part.startsWith("[...") && part.endsWith("]")) {
        return `:${part.slice(4, -1)}(*)`;
      }
      if (part.startsWith("[") && part.endsWith("]")) {
        return `:${part.slice(1, -1)}`;
      }
      return part;
    })
    .join("/");
  log.debug(`${relativePath} -> ${expressPath}`);
  return `/${expressPath}`;
}
 
export function expressRouter(fileRoutes: FileRoute[]): {
  paths: string[];
  router: Router;
} {
  const router = express.Router();
 
  const paths: string[] = [];
 
  for (const route of fileRoutes) {
    const routePath = getExpressRoutePath(route.filePath);
    paths.push(routePath);
    if (route.GET) {
      router.get(routePath, async (req, res, next) => {
        try {
          const userResponse = await (route as { GET: Handler }).GET({
            req,
            res,
          });
          await handleResponse(res, userResponse);
        } catch (e) {
          next(e);
        }
      });
    }
    if (route.POST) {
      router.post(routePath, async (req, res, next) => {
        try {
          const userResponse = await (route as { POST: Handler }).POST({
            req,
            res,
          });
          await handleResponse(res, userResponse);
        } catch (e) {
          next(e);
        }
      });
    }
  }
  return { paths, router };
}
 
async function load(m: unknown): Promise<Handler> {
  if (!isHandler(m)) throw new Error("invalid file route module");
  return m as Handler;
}
 
/** Return an express router that serves files as routes form the given directory. */
export async function fileRouter(opts?: { cwd?: string }): Promise<{
  paths: string[];
  router: express.RequestHandler;
  fileRoutes: FileRoute[];
}> {
  const log = getLogger("file-router");
  const cwd = opts?.cwd ?? process.cwd();
  const modules = await loadModulesfromDir(cwd, load, [".tsx"]);
  log.debug(`found ${modules.length} file routes in ${cwd}`);
  const fileRoutes: FileRoute[] = [];
  for (const module of modules) {
    const fileRoute: FileRoute = {
      filePath: module.relativePath,
      GET: undefined,
      POST: undefined,
    };
    if (
      !module.namedExports?.GET &&
      !module.namedExports?.POST &&
      !module.defaultExport
    ) {
      throw new Error(
        `invalid file route module at ${module.absolutePath}, no GET or POST export found`,
      );
    }
    if (module.namedExports?.GET) {
      log.debug(`found GET export in ${module.absolutePath}`);
      fileRoute.GET = module.namedExports.GET;
    }
    if (module.namedExports?.POST) {
      log.debug(`found POST export in ${module.absolutePath}`);
      fileRoute.POST = module.namedExports.POST;
    }
    if (module.defaultExport && !fileRoute.GET) {
      log.debug(
        `found default export in ${module.absolutePath}, assuming GET export`,
      );
      fileRoute.GET = module.defaultExport;
    }
    fileRoutes.push(fileRoute);
  }
  const { paths, router } = expressRouter(fileRoutes);
  return { paths, router, fileRoutes };
}