import Router from './Router'; import BaseRouter from './BaseRouter'; import LayRequest from '../IO/LayRequest'; import LayResponse from '../IO/LayResponse'; import Logger from '../Utils/Logger'; export default class LayRouting extends BaseRouter { routers; namespace = null; server; constructor(server, namespace = null) { super(); this.server = server; this.routers = new Map([ ['$default', new Router(this.server)] ]); } getServer() { return this.server; } setNamespace(ns) { if (!ns || typeof ns != 'string') this.namespace = null; this.namespace = ns; } routes() { return this.routers.get('$default').routes; } addRouter(router) { let routerInstance; if(typeof router == 'undefined' || router === null) { routerInstance = new Router(this.server); } else { routerInstance = new router(this.server); } this.routers.set(router.domain || '$default', routerInstance); } route(config = {}) { if (typeof config != 'object') throw new Error('route config is not an object'); const { path, handle, method = 'get' } = config; if (typeof path != 'string') throw new Error('route path is not a string'); if (typeof handle != 'function') throw new Error('route handle is not a function'); this.add(path, handle, method); return this; } async handle(req) { const url = new URL(req.url); const reqContext = { request: null, response: null, }; try { reqContext.request = new LayRequest(req); reqContext.response = new LayResponse(this); } catch (err) { Logger.error(err); } let domain = url.hostname; if([...this.routers.keys()].indexOf(domain) < 0) domain = '$default'; return await this.routers.get(domain).handle(reqContext); } add(path, cb) { let options = arguments[2] ?? { method: 'get', domain: '$default' }; if(typeof options.domain != 'string') options.domain = '$default'; if (this.namespace) { if (!path.startsWith('/')) path = '/' + path; path = this.namespace + path; } Logger(path, options) if(options.domain === '$default') { let domains = this.routers.keys(); for(let domain of [...domains]) { this.routers.get(domain).add(path, cb, options); } } else { if(!this.routers.has(options.domain)) { const domainRouter = Router; domainRouter.domain = options.domain; this.addRouter(domainRouter); Logger('added new router for domain', options.domain) } this.routers.get(options.domain).add (path, cb, options); } } }