This repository was archived by the owner on Jul 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (48 loc) · 1.65 KB
/
Copy pathindex.js
File metadata and controls
54 lines (48 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const rg = require("./rg");
const express = require("express");
const fs = require("fs");
const _ = require("lodash");
const app = express();
const port = 3000;
const basePath = process.env.SEARCH_DIRECTORY;
if (!basePath) {
process.stderr.write(
"Please provide SEARCH_DIRECTORY environment variable\n"
);
process.exit(1);
}
app.get("/search/:query", async (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
const searchTerm = req.params.query.split("&")[0];
const page = req.params.query.split("&")[1];
const pageNum = _.defaultTo(
page ? page.replace("page=","") * 100 : 100,
100
);
if (!searchTerm.match(/^[0-9a-zA-Z,-,+,\s]+$/)) {
res.status(400).send("search query does not match alphanum");
return;
}
if (searchTerm.length < 3) {
res.status(400).send("");
return;
}
const rgResults = await rg(basePath, '"' + searchTerm + '"');
const sortedRgResults = _.sortBy(rgResults, "file");
const searchResult = sortedRgResults.slice(pageNum - 100, pageNum);
searchResult.forEach((v) => delete v.column);
res.send({ hits: sortedRgResults.length, results: searchResult });
});
app.get("/file/:year/:month/:name", async (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
const { year, month, name } = req.params;
try {
const fileName = basePath + year + "/" + month + "/" + name;
fs.createReadStream(fileName).pipe(res);
} catch (e) {
console.log("Error:", e.stack);
}
});
app.listen(port, () => {});