coap-fast-router
Version:
Fast CoAP Router
80 lines (79 loc) • 3.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRouter = createRouter;
const node_url_1 = __importDefault(require("node:url"));
const node_querystring_1 = __importDefault(require("node:querystring"));
const path_to_regexp_1 = require("path-to-regexp");
const lru_cache_1 = require("lru-cache");
const METHODS = ["all", "get", "observe", "post", "put", "delete"];
function createRouter(cacheOptions) {
const handlers = [];
const cache = new lru_cache_1.LRUCache(Object.assign({ max: 10000 }, cacheOptions));
const router = function (req, res) {
var _a;
const url = node_url_1.default.parse(req.url);
const path = url.pathname;
// Parse url query parameter and append to req
req.query = url.query ? node_querystring_1.default.parse(url.query) : {};
let method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
if (method === "get" &&
req.headers["Observe"] === 0) {
method = "observe";
}
let callback = null;
if (path) {
const cached = cache.get(path);
if (cached) {
req.params = Object.assign({}, cached.params);
callback = cached.callback;
}
else {
for (const handler of handlers) {
if (handler.method === "all" || handler.method === method) {
const matches = handler.regexp.exec(path);
if (matches) {
req.params = {};
if (matches.length > 1) {
handler.keys.forEach((key, idx) => {
req.params[key.name] = matches[idx + 1];
});
}
callback = handler.callback;
cache.set(path, {
callback,
params: Object.assign({}, req.params),
});
break;
}
}
}
}
}
if (callback) {
callback(req, res);
}
else {
res.code = 404;
res.end();
}
};
router.cache = cache;
router.method = function (method, path, callback) {
if (path !== "" && !path.startsWith("/")) {
throw new Error("Path must starts with '/'.");
}
const { regexp, keys } = (0, path_to_regexp_1.pathToRegexp)(path);
handlers.push({ method, path, regexp, keys, callback });
cache.clear();
return this;
};
METHODS.forEach((method) => {
router[method] = function (path, callback) {
return router.method(method, path, callback);
};
});
return router;
}