UNPKG

2.75 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var express = require("express");
5var url_1 = require("url");
6var libs_1 = require("../../libs");
7var cache = new libs_1.Cache();
8function staticRoutes(args) {
9 var _this = this;
10 var router = express.Router();
11 var baseUrl = clean(args.base);
12 var route = "/" + baseUrl + "/*";
13 var dir = args.dir;
14 var getInfo = function (pathname) {
15 if (pathname === void 0) { pathname = ''; }
16 return tslib_1.__awaiter(_this, void 0, void 0, function () {
17 var path, file, exists;
18 return tslib_1.__generator(this, function (_a) {
19 switch (_a.label) {
20 case 0:
21 path = clean(pathname.substr(baseUrl.length + 1));
22 file = libs_1.fsPath.join(dir, baseUrl, path);
23 return [4, libs_1.fs.pathExists(file)];
24 case 1:
25 exists = _a.sent();
26 return [2, { file: file, exists: exists }];
27 }
28 });
29 });
30 };
31 router.get(route, function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
32 var url, pathname, force, cacheKey, cached, info, _a, status, error;
33 return tslib_1.__generator(this, function (_b) {
34 switch (_b.label) {
35 case 0:
36 url = url_1.parse(req.url, false);
37 pathname = url.pathname;
38 force = libs_1.queryString.isFlag(['force', 'f'], req.query);
39 cacheKey = "STATIC/" + pathname;
40 if (force) {
41 cache.del(cacheKey);
42 }
43 cached = cache.get(cacheKey);
44 if (!cached) return [3, 1];
45 _a = cached;
46 return [3, 3];
47 case 1: return [4, getInfo(pathname)];
48 case 2:
49 _a = _b.sent();
50 _b.label = 3;
51 case 3:
52 info = _a;
53 cache.put(cacheKey, info);
54 status = info.exists ? 200 : 404;
55 error = info.exists ? undefined : "File not found.";
56 return [2, info.exists
57 ? res.sendFile(info.file)
58 : res.status(200).send({ status: status, error: error, path: pathname })];
59 }
60 });
61 }); });
62 return router;
63}
64exports.staticRoutes = staticRoutes;
65var clean = function (value) { return value.replace(/^\//, '').replace(/\/$/, ''); };
66//# sourceMappingURL=staticRoutes.js.map
\No newline at end of file