next-rest-framework
Version:
Next REST Framework - write type-safe, self-documenting REST APIs in Next.js
76 lines (75 loc) • 3.54 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineCatchAllRoute = void 0;
const server_1 = require("next/server");
const constants_1 = require("./constants");
const utils_1 = require("./utils");
const js_yaml_1 = __importDefault(require("js-yaml"));
const define_route_1 = require("./define-route");
const headers_1 = require("next/headers");
const defineCatchAllRoute = ({ config }) => {
return (methodHandlers = {}) => {
return async (req, context) => {
try {
const { method, headers, nextUrl } = req;
const { pathname } = nextUrl;
const proto = headers.get('proto') ?? headers.get('x-forwarded-proto') ?? 'http';
const host = headers.get('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 === swaggerUiPath) {
const cookieStore = (0, headers_1.cookies)();
const theme = cookieStore.get('theme')?.value;
const html = (0, utils_1.getHTMLForSwaggerUI)({ config, baseUrl, theme });
return new server_1.NextResponse(html, {
headers: {
'Content-Type': 'text/html'
},
status: 200
});
}
if (pathname === openApiJsonPath) {
return server_1.NextResponse.json(spec, { status: 200 });
}
if (pathname === openApiYamlPath) {
return new server_1.NextResponse(js_yaml_1.default.dump(spec), {
headers: {
'Content-Type': 'text/plain'
},
status: 200
});
}
}
if (!methodHandlers[method]) {
return server_1.NextResponse.json({ message: constants_1.DEFAULT_ERRORS.notFound }, { status: 404 });
}
return await (0, define_route_1.defineRoute)({
config
})(methodHandlers)(req, context);
}
catch (error) {
const res = await config.errorHandler?.({ req, error });
if (res) {
return res;
}
else {
return server_1.NextResponse.json({ message: constants_1.DEFAULT_ERRORS.unexpectedError }, { status: 500 });
}
}
};
};
};
exports.defineCatchAllRoute = defineCatchAllRoute;