UNPKG

counterfact

Version:

a library for building a fake REST API for testing

48 lines (47 loc) 1.65 kB
import { pathToFileURL } from "node:url"; import createDebug from "debug"; import Koa from "koa"; import bodyParser from "koa-bodyparser"; import { koaSwagger } from "koa2-swagger-ui"; import { openapiMiddleware } from "./openapi-middleware.js"; import { pageMiddleware } from "./page-middleware.js"; const debug = createDebug("counterfact:server:create-koa-app"); export function createKoaApp(registry, koaMiddleware, config) { const app = new Koa(); app.use(openapiMiddleware(config.openApiPath, `//localhost:${config.port}${config.routePrefix}`)); app.use(koaSwagger({ routePrefix: "/counterfact/swagger", swaggerOptions: { url: "/counterfact/openapi", }, })); debug("basePath: %s", config.basePath); debug("routes", registry.routes); app.use(pageMiddleware("/counterfact/", "index", { basePath: config.basePath, methods: ["get", "post", "put", "delete", "patch"], openApiHref: config.openApiPath.includes("://") ? config.openApiPath : pathToFileURL(config.openApiPath).href, openApiPath: config.openApiPath, get routes() { return registry.routes; }, })); app.use(async (ctx, next) => { if (ctx.URL.pathname === "/counterfact") { ctx.redirect("/counterfact/"); return; } await next(); }); app.use(pageMiddleware("/counterfact/rapidoc", "rapi-doc", { basePath: config.basePath, get routes() { return registry.routes; }, })); app.use(bodyParser()); app.use(koaMiddleware); return app; }