UNPKG

@sapphire/plugin-api

Version:

Plugin for @sapphire/framework to expose a REST API

60 lines (58 loc) 2.58 kB
import { __name, __publicField } from '../chunk-S573YWRP.mjs'; import { isNullish } from '@sapphire/utilities'; import { Middleware } from '../lib/structures/Middleware.mjs'; import { HttpCodes } from '../lib/structures/http/HttpCodes.mjs'; var _PluginMiddleware = class _PluginMiddleware extends Middleware { constructor(context) { super(context, { position: 10 }); __publicField(this, "origin"); __publicField(this, "routes"); this.origin = this.container.server.options.origin ?? "*"; this.routes = this.container.stores.get("routes"); } run(request, response) { response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString()); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Origin", this.origin); response.setHeader("Access-Control-Allow-Headers", "Authorization, User-Agent, Content-Type"); response.setHeader("Access-Control-Allow-Methods", this.getMethods(request.routerNode)); this.ensurePotentialEarlyExit(request, response); } getMethods(routerNode) { if (isNullish(routerNode)) { return this.routes.router.supportedMethods.join(", "); } return [...routerNode.methods()].join(", "); } /** * **RFC 7231 4.3.7.** * > This method allows a client to determine the options and/or requirements associated with a * > resource, or the capabilities of a server, without implying a resource action. * * This method ensures that the request is exited early in case required * The conditions in which an early exit is required are: * 1. If the request method is 'OPTIONS'. In this case the request is returned with status code 200 * 2. If the requested route isn't matched with any existing route in the RouteStore. * In this case the request is returned with a status code 404. * * @param request The API Request coming in * @param response The API response that will go out * @param route The route being requested by the request */ ensurePotentialEarlyExit({ method, route, routerNode }, response) { if (method === "OPTIONS") { if (!route?.methods.has("OPTIONS")) { response.end(); } } else if (routerNode === null) { response.status(HttpCodes.NotFound).end(); } else if (route === null) { response.status(HttpCodes.MethodNotAllowed).end(); } } }; __name(_PluginMiddleware, "PluginMiddleware"); var PluginMiddleware = _PluginMiddleware; export { PluginMiddleware }; //# sourceMappingURL=headers.mjs.map //# sourceMappingURL=headers.mjs.map