UNPKG

rjweb-server

Version:

Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS

114 lines (113 loc) 2.93 kB
import SafeServerEventEmitter from "../safeEventEmitter"; import RoutePath from "./path"; import RouteContentTypes from "./contentTypes"; import RouteDefaultHeaders from "./defaultHeaders"; class RouteIndex extends SafeServerEventEmitter { /** * List of Routes */ constructor() { super(); this.externals = []; this.middlewares = []; } /** * Add a new Block of Routes with a Prefix * @example * ``` * const controller = new Server({ }) * * controller.path('/', (path) => path * .http('GET', '/cool', (http) => http * .onRequest((ctr) => { * ctr.print('cool!') * }) * ) * .path('/api', (path) => path * .http('GET', '/', (http) => http * .onRequest((ctr) => { * ctr.print('Welcome to the API!') * }) * ) * ) * ) * ``` * @since 5.0.0 */ path(prefix, router) { if ("getData" in router) { this.externals.push({ object: router, addPrefix: prefix }); } else { const routePath = new RoutePath(prefix); this.externals.push({ object: routePath }); router(routePath); } return this; } /** * Add Content Type Mapping * @example * ``` * controller.contentTypes((cT) => cT * .add('.jayson', 'application/json') * ) * ``` * @since 5.3.0 */ contentTypes(code) { const routeContentTypes = new RouteContentTypes(); this.externals.push({ object: routeContentTypes }); code(routeContentTypes); return this; } /** * Add Default Headers * @example * ``` * controller.defaultHeaders((dH) => dH * .add('X-Api-Version', '1.0.0') * ) * ``` * @since 5.3.0 */ defaultHeaders(code) { const routeDefaultHeaders = new RouteDefaultHeaders(); this.externals.push({ object: routeDefaultHeaders }); code(routeDefaultHeaders); return this; } /** * Internal Method for Generating Routes Object * @since 6.0.0 */ async getData() { const routes = [], webSockets = [], statics = [], loadPaths = []; let contentTypes = {}, defaultHeaders = {}; for (const external of this.externals) { const result = await external.object.getData(external.addPrefix ?? "/"); if ("routes" in result) routes.push(...result.routes); if ("webSockets" in result) webSockets.push(...result.webSockets); if ("statics" in result) statics.push(...result.statics); if ("loadPaths" in result) loadPaths.push(...result.loadPaths); if ("contentTypes" in result) contentTypes = Object.assign(contentTypes, result.contentTypes); if ("defaultHeaders" in result) defaultHeaders = Object.assign(defaultHeaders, result.defaultHeaders); } return { routes, webSockets, statics, loadPaths, contentTypes, defaultHeaders }; } } export { RouteIndex as default };