next-rest-framework
Version:
Next REST Framework - write type-safe, self-documenting REST APIs in Next.js
66 lines (65 loc) • 3.03 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineCatchAllApiRoute = void 0;
const constants_1 = require("./constants");
const utils_1 = require("./utils");
const js_yaml_1 = __importDefault(require("js-yaml"));
const define_api_route_1 = require("./define-api-route");
const defineCatchAllApiRoute = ({ config }) => {
return (methodHandlers = {}) => {
return async (req, res) => {
try {
const { method, headers, url: pathname, cookies } = req;
const proto = headers['x-forwarded-proto'] ?? 'http';
const host = headers.host;
const baseUrl = `${proto}://${host}`;
const { openApiJsonPath, openApiYamlPath, swaggerUiPath, exposeOpenApiSpec, suppressInfo } = config;
if (!suppressInfo) {
(0, utils_1.logInitInfo)({ config });
if (!global.reservedPathsLogged) {
(0, utils_1.logReservedPaths)({ config, baseUrl });
}
}
if ([openApiJsonPath, openApiYamlPath, swaggerUiPath].includes(pathname) &&
exposeOpenApiSpec &&
method === constants_1.ValidMethod.GET) {
const spec = await (0, utils_1.getOrCreateOpenApiSpec)({ config, baseUrl });
if (pathname === openApiJsonPath) {
res.status(200).json(spec);
return;
}
if (pathname === openApiYamlPath) {
res.setHeader('Content-Type', 'text/plain');
res.status(200).send(js_yaml_1.default.dump(spec));
return;
}
if (pathname === swaggerUiPath) {
const html = (0, utils_1.getHTMLForSwaggerUI)({
config,
baseUrl,
theme: cookies.theme
});
res.setHeader('Content-Type', 'text/html');
res.status(200).send(html);
return;
}
}
if (!methodHandlers[method]) {
res.status(404).json({ message: constants_1.DEFAULT_ERRORS.notFound });
return;
}
await (0, define_api_route_1.defineApiRoute)({ config })(methodHandlers)(req, res);
}
catch (error) {
await config.errorHandler?.({ req, error });
if (!res.writableEnded) {
res.status(500).json({ message: constants_1.DEFAULT_ERRORS.unexpectedError });
}
}
};
};
};
exports.defineCatchAllApiRoute = defineCatchAllApiRoute;