UNPKG

@teclone/r-server

Version:

A lightweight, extensible web-server with inbuilt routing-engine, static file server, file upload handler, request body parser, middleware support and lots more

319 lines (292 loc) 10.9 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _classCallCheck = require('@babel/runtime/helpers/classCallCheck'); var _createClass = require('@babel/runtime/helpers/createClass'); var _defineProperty = require('@babel/runtime/helpers/defineProperty'); var utils = require('@teclone/utils'); var Wrapper = require('./Wrapper'); var Constants = require('./Constants'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass); var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var Router = /*#__PURE__*/function () { /** * * @param inheritMiddlewares - boolean indicating if parent middlewares should be inherited, defaults to true. */ function Router(opts) { var _opts$inheritMiddlewa; _classCallCheck__default["default"](this, Router); _defineProperty__default["default"](this, "basePath", ''); _defineProperty__default["default"](this, "routes", { options: [], head: [], get: [], post: [], put: [], "delete": [] }); _defineProperty__default["default"](this, "middlewares", []); _defineProperty__default["default"](this, "inheritMiddlewares", void 0); this.inheritMiddlewares = (_opts$inheritMiddlewa = opts === null || opts === void 0 ? void 0 : opts.inheritMiddlewares) !== null && _opts$inheritMiddlewa !== void 0 ? _opts$inheritMiddlewa : true; this.setBasePath((opts === null || opts === void 0 ? void 0 : opts.basePath) || ''); } /** * resolves the url route by joining it to the base path */ _createClass__default["default"](Router, [{ key: "resolvePath", value: function resolvePath(path) { return utils.stripSlashes([this.basePath, utils.stripSlashes(path)].join('/')); } /** * resolves a route callback options */ }, { key: "resolveMiddlewares", value: function resolveMiddlewares(use) { return use ? utils.makeArray(use) : []; } /** * resolves a use middleware options */ }, { key: "resolveMethods", value: function resolveMethods(method) { var methods = method ? utils.makeArray(method) : ['*']; if (methods.includes('*')) { return Constants.ALL_METHODS; } else { return methods; } } /** * sets the route rule for a given http method * * @param method - the http method * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "set", value: function set(method, path, callback, use) { var routeId = Constants.assignRouteId(); var resolvedPath = this.resolvePath(path); var methods = this.resolveMethods(method); var _iterator = _createForOfIteratorHelper(methods), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _method = _step.value; this.routes[_method].push([routeId, resolvedPath, callback, this.resolveMiddlewares(use)]); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return routeId; } /** * returns the routes. */ }, { key: "getRoutes", value: function getRoutes() { return this.routes; } /** * returns the middlewares */ }, { key: "getMiddlewares", value: function getMiddlewares() { return this.middlewares; } /** * returns routing base path that gets prepended to all route and middleware urls */ }, { key: "getBasePath", value: function getBasePath() { return this.basePath; } /** * sets routing base path that gets prepended to all route and middleware urls */ }, { key: "setBasePath", value: function setBasePath(basePath) { this.basePath = utils.stripSlashes(basePath); return this; } /** * stores route rules for http OPTIONS method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "options", value: function options(path, callback, use) { return this.set('options', path, callback, use); } /** * stores route rules for http HEAD method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "head", value: function head(path, callback, use) { return this.set('head', path, callback, use); } /** * stores route rules for http GET method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "get", value: function get(path, callback, use) { return this.set('get', path, callback, use); } /** * stores route rules for http POST method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "post", value: function post(path, callback, use) { return this.set('post', path, callback, use); } /** * stores route rules for http PUT method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "put", value: function put(path, callback, use) { return this.set('put', path, callback, use); } /** * stores route rules for http DELETE method * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "delete", value: function _delete(path, callback, use) { return this.set('delete', path, callback, use); } /** * stores route rules for all http methods * * @param url - route url * @param callback - route callback handler * @param options - route configuration object or middleware or array of middlewares */ }, { key: "any", value: function any(path, callback, use) { return this.set('*', path, callback, use); } /** * creates and returns a route wrapper for the given url */ }, { key: "route", value: function route(url) { return new Wrapper.Wrapper(this, url); } /** * registers a middleware to be called whenever the given url is visited * * @param url - url to apply middleware to. use * to appy to all urls * @param middleware - the middleware or array of middlewares * @param options - middleware configuration option. here, you can specify the http method * that the middleware will run against *@returns {MiddlewareId} returns the middleware id, can be used to delete the middleware. */ }, { key: "use", value: function use(path, middleware, operation) { var middlewareId = Constants.assignMiddlewareId(); this.middlewares.push([middlewareId, this.resolvePath(path), this.resolveMiddlewares(middleware), new Set(this.resolveMethods(operation))]); return middlewareId; } /** * sets or gets the inherit parent's middlewares flag. * @param status - if given, it sets this value */ }, { key: "shouldInheritMiddlewares", value: function shouldInheritMiddlewares(status) { if (utils.isBoolean(status)) { this.inheritMiddlewares = status; } return this.inheritMiddlewares; } /** * removes a given route * @param id route id */ }, { key: "removeRoute", value: function removeRoute(id) { var _this = this; var findIndex = function findIndex(routeInstance) { return routeInstance[0] === id; }; var found = false; Constants.ALL_METHODS.forEach(function (key) { var route = _this.routes[key]; var index = route.findIndex(findIndex); if (index !== -1) { route.splice(index, 1); found = true; } }); return found; } /** * removes a given middleware. returns true if it succeeds, otherwise, it returns false * @param id middleware id */ }, { key: "removeMiddleware", value: function removeMiddleware(id) { var findIndex = function findIndex(instance) { return instance[0] === id; }; var middlewares = this.middlewares; var index = middlewares.findIndex(findIndex); if (index !== -1) { middlewares.splice(index, 1); return true; } return false; } }]); return Router; }(); exports.Router = Router; //# sourceMappingURL=Router.js.map