@sapphire/plugin-api
Version:
Plugin for @sapphire/framework to expose a REST API
65 lines (62 loc) • 3 kB
JavaScript
;
var utilities = require('@sapphire/utilities');
var Middleware_cjs = require('../lib/structures/Middleware.cjs');
var HttpCodes_cjs = require('../lib/structures/http/HttpCodes.cjs');
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var _PluginMiddleware = class _PluginMiddleware extends Middleware_cjs.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 (utilities.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_cjs.HttpCodes.NotFound).end();
} else if (route === null) {
response.status(HttpCodes_cjs.HttpCodes.MethodNotAllowed).end();
}
}
};
__name(_PluginMiddleware, "PluginMiddleware");
var PluginMiddleware = _PluginMiddleware;
exports.PluginMiddleware = PluginMiddleware;
//# sourceMappingURL=headers.cjs.map
//# sourceMappingURL=headers.cjs.map