-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
93 lines (77 loc) · 2.59 KB
/
index.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const express = require("express");
const cors = require("cors");
const fs = require("fs");
const app = express();
const port = 3000;
const DATA_DIR = "data/";
const METADATA_DIR = "metadata/";
const LOCAL_SEPARATOR = "_";
const FILE_EXT = ".json";
const METADATA_EXT = ".txt";
const ID_LEN = 5;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Set up reading of the JSON body. You can access the body with req.body
app.use(express.json({limit: '50mb'}));
// Set up CORS handling. Here you could specify only some specific domains to accept requests from
app.use(cors());
app.post("/:id?", (req, res) => {
let id = req.params.id;
let version;
if (!id) {
// Generate "random" 5 character string
const genRndChar = () => {
const idx = Math.floor(Math.random() * chars.length);
return chars[idx];
};
id = "";
for (let i = 0; i < ID_LEN; i++) {
id += genRndChar();
}
}
const metadataPath = METADATA_DIR + id + METADATA_EXT;
// Look for the latest version in the metadata directory. If there is no metadata file, then it is the first version.
if (fs.existsSync(metadataPath)) {
version = fs.readFileSync(metadataPath, {encoding: 'utf-8'});
// Increment the version and convert back to string
version = Number.parseInt(version) + 1;
version = version + "";
} else {
version = "1";
}
const newLocalToken = id + LOCAL_SEPARATOR + version;
fs.writeFileSync(metadataPath, version);
const filePath = DATA_DIR + newLocalToken + FILE_EXT;
const stringBody = JSON.stringify(req.body);
fs.writeFileSync(filePath, stringBody);
res.status(200).json({
id,
version
});
});
app.get("/:id/:version?", (req, res) => {
const id = req.params.id;
const version = req.params.version || "1";
const localToken = id + LOCAL_SEPARATOR + version;
const path = DATA_DIR + localToken + FILE_EXT;
if (fs.existsSync(path)) {
const rawData = fs.readFileSync(path);
const parsedData = JSON.parse(rawData);
res.status(200).json({
name: parsedData.name,
description: parsedData.description,
tags: parsedData.tags,
jsonPayload: parsedData.payload
});
} else {
res.status(404).send();
}
});
app.listen(port, () => {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR);
}
if (!fs.existsSync(METADATA_DIR)) {
fs.mkdirSync(METADATA_DIR);
}
console.log(`Example app listening on port ${port}`);
});