@paroicms/server
Version:
The ParoiCMS server
33 lines • 1.52 kB
JavaScript
import { ApiError } from "@paroicms/public-server-lib";
import { createBackendPluginService } from "../plugin-services/make-backend-plugin-service.js";
import { serve404SimpleHtml } from "./http-helpers.js";
export async function pluginPublicApiReqHandler(siteContext, httpContext) {
const { req } = httpContext;
const path = req.path;
const prefix = "/api/plugin/";
if (!path.startsWith(prefix))
return false;
const sepIndex = path.indexOf("/", prefix.length);
const pluginPublicDirName = sepIndex === -1 ? path.substring(prefix.length) : path.substring(prefix.length, sepIndex);
const relativePath = sepIndex === -1 ? "" : path.substring(sepIndex);
const plugin = siteContext.pluginsBySlug.get(pluginPublicDirName);
if (!plugin || !plugin.publicApiHandler) {
serve404SimpleHtml(httpContext);
return true;
}
const service = createBackendPluginService(siteContext, plugin);
try {
await plugin.publicApiHandler(service, httpContext, relativePath);
}
catch (error) {
siteContext.logger.error(`[${plugin.slug}] API plugin error handling request to "${relativePath}":`, error);
if (error instanceof ApiError) {
httpContext.res.status(error.status).send({ success: false, error: error.message });
}
else {
httpContext.res.status(500).send({ success: false, error: "Internal server error" });
}
}
return true;
}
//# sourceMappingURL=public-api.req-handler.js.map