jsm-core
Version:
Core library for JSM project
264 lines (263 loc) • 13.8 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.router = exports.registerRouteHandler = exports.JsmRequestHandlerMiddleware = exports.HttpMethods = void 0;
const typedi_1 = require("typedi");
const typedi_2 = require("typedi");
const express_1 = require("express");
const jsm_logger_1 = __importStar(require("jsm-logger"));
const context_1 = require("../../context");
const jsm_utilities_1 = require("jsm-utilities");
const logger = (0, jsm_logger_1.default)(jsm_logger_1.LoggerContext.MIDDLEWARE, 'JsmRequestHandler', jsm_logger_1.LogSeverity.Debug);
var HttpMethods;
(function (HttpMethods) {
HttpMethods["GET"] = "get";
HttpMethods["POST"] = "post";
HttpMethods["PUT"] = "put";
HttpMethods["DELETE"] = "delete";
HttpMethods["PATCH"] = "patch";
HttpMethods["OPTIONS"] = "options";
HttpMethods["HEAD"] = "head";
})(HttpMethods || (exports.HttpMethods = HttpMethods = {}));
let JsmRequestHandler = (() => {
let _classDecorators = [(0, typedi_2.Service)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var JsmRequestHandler = _classThis = class {
constructor() {
this.registeredPaths = [];
this.router = (0, express_1.Router)();
}
checkIfRegistered(id) {
const isRegistered = this.registeredPaths.some((route) => route.id === id);
return isRegistered;
}
/**
* Register a request handler for a specific HTTP method and path.
* @param {HttpMethods} method - The HTTP method to register the handler for.
* @param {string} path - The path to register the handler for.
* @param {RequestHandler | RequestHandler[]} handler - The request handler(s) to register.
* @param {string} [customId] - Used to check if it's already registered to prevent duplications.
*/
registerHandler(method, path, handler, opt) {
const { customId, addApiPrefix } = (0, jsm_utilities_1.defaults)(opt || {}, {
addApiPrefix: true
});
const apiPrefix = (0, context_1.getRegistry)().getConfig('http.api.prefix');
if (addApiPrefix && apiPrefix)
path = `${apiPrefix}${path}`.replaceAll('//', '/');
logger.event(`Registered`, {
customId,
addApiPrefix,
apiPrefix,
opt,
path
});
const id = customId ? `${method}-${path}-${customId}` : undefined;
if (id) {
if (this.checkIfRegistered(id)) {
logger.warn(`Handler for path '${path}' is already registered.`);
return;
}
this.registeredPaths.push({ id, method, path, customId });
}
if (Array.isArray(handler)) {
handler.forEach((h) => this.router[method](path, h));
}
else {
this.router[method](path, handler);
}
logger.success(`Registered customHandler: ${method.toUpperCase()} ${path} with id: ${customId}`);
}
};
__setFunctionName(_classThis, "JsmRequestHandler");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
JsmRequestHandler = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return JsmRequestHandler = _classThis;
})();
// Used on express.loader.ts
const JsmRequestHandlerMiddleware = (errorHandler) => {
const handler = typedi_1.Container.get(JsmRequestHandler);
return handler.router;
};
exports.JsmRequestHandlerMiddleware = JsmRequestHandlerMiddleware;
/**
* Register a request handler for a specific HTTP method and path.
* @param {HttpMethods} method - The HTTP method to register the handler for.
* @param {string} path - The path to register the handler for.
* @param {boolean} addApiPrefix - Whether to add the API prefix to the path. @default true
* @param {string} [customId] - Used to check if it's already registered to prevent duplications.
*
*/
const registerRouteHandler = (method, path, requestHandler, opt) => {
const handler = typedi_1.Container.get(JsmRequestHandler);
handler.registerHandler(method, path, requestHandler, opt);
};
exports.registerRouteHandler = registerRouteHandler;
exports.router = {
/**
* Registers a GET request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
get(path, ...args) {
parseAndRegisterRoute(HttpMethods.GET, path, args);
},
/**
* Registers a POST request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
post(path, ...args) {
parseAndRegisterRoute(HttpMethods.POST, path, args);
},
/**
* Registers a PUT request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
put(path, ...args) {
parseAndRegisterRoute(HttpMethods.PUT, path, args);
},
/**
* Registers a DELETE request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
delete(path, ...args) {
parseAndRegisterRoute(HttpMethods.DELETE, path, args);
},
/**
* Registers a PATCH request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
patch(path, ...args) {
parseAndRegisterRoute(HttpMethods.PATCH, path, args);
},
/**
* Registers an OPTIONS request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
options(path, ...args) {
parseAndRegisterRoute(HttpMethods.OPTIONS, path, args);
},
/**
* Registers a HEAD request handler for the specified path.
* @param {`/${string}`} path - The path to register the handler for.
* @param {...(RequestHandler | RequestHandler[] | TRegisterRouteHandlerOptions)} args - The request handlers or options for the route. Multiple handlers can be provided.
* @param {boolean} [addApiPrefix] - Whether to add the API prefix to the path. Defaults to true.
* @param {string} [customId] - A custom identifier for the route, used to prevent duplicate registrations.
*/
head(path, ...args) {
parseAndRegisterRoute(HttpMethods.HEAD, path, args);
},
};
function parseAndRegisterRoute(method, path, args) {
const handlers = [];
let options = {};
args.forEach((arg) => {
if (typeof arg === 'function' || Array.isArray(arg)) {
handlers.push(...(Array.isArray(arg) ? arg : [arg]));
}
else if (typeof arg === 'object') {
options = Object.assign(Object.assign({}, options), arg);
}
else if (typeof arg === 'string') {
options = Object.assign(Object.assign({}, options), { customId: arg });
}
else if (typeof arg === 'boolean') {
options = Object.assign(Object.assign({}, options), { addApiPrefix: arg });
}
});
(0, exports.registerRouteHandler)(method, path, handlers, options);
}