UNPKG

@backstage/backend-defaults

Version:

Backend defaults used by Backstage backend apps

78 lines (72 loc) 2.24 kB
'use strict'; var express = require('express'); var trimEnd = require('lodash/trimEnd'); function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } var trimEnd__default = /*#__PURE__*/_interopDefaultCompat(trimEnd); function normalizePath(path) { return `${trimEnd__default.default(path, "/")}/`; } class DefaultRootHttpRouter { #indexPath; #router = express.Router(); #namedRoutes = express.Router(); #indexRouter = express.Router(); #existingPaths = new Array(); static create(options) { let indexPath; if (options?.indexPath === false) { indexPath = void 0; } else if (options?.indexPath === void 0) { indexPath = "/api/app"; } else if (options?.indexPath === "") { throw new Error("indexPath option may not be an empty string"); } else { indexPath = options.indexPath; } return new DefaultRootHttpRouter(indexPath); } constructor(indexPath) { this.#indexPath = indexPath; this.#router.use(this.#namedRoutes); this.#router.use("/api/", (_req, _res, next) => { next("router"); }); if (this.#indexPath) { this.#router.use(this.#indexRouter); } } use(path, handler) { if (path.match(/^[/\s]*$/)) { throw new Error(`Root router path may not be empty`); } const conflictingPath = this.#findConflictingPath(path); if (conflictingPath) { throw new Error( `Path ${path} conflicts with the existing path ${conflictingPath}` ); } this.#existingPaths.push(path); this.#namedRoutes.use(path, handler); if (this.#indexPath === path) { this.#indexRouter.use(handler); } } handler() { return this.#router; } #findConflictingPath(newPath) { const normalizedNewPath = normalizePath(newPath); for (const path of this.#existingPaths) { const normalizedPath = normalizePath(path); if (normalizedPath.startsWith(normalizedNewPath)) { return path; } if (normalizedNewPath.startsWith(normalizedPath)) { return path; } } return void 0; } } exports.DefaultRootHttpRouter = DefaultRootHttpRouter; //# sourceMappingURL=DefaultRootHttpRouter.cjs.js.map