-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
64 lines (54 loc) · 1.7 KB
/
app.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
const express = require("express");
const crypto = require("crypto");
const cors = require("cors");
const bodyParser = require("body-parser");
const Firestore = require("@google-cloud/firestore");
const PROJECTID = "winter-runway-279100";
const COLLECTION_NAME = "codesnippets";
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
keyFilename: "./winter-runway-279100-3998bbcc8fa0.json",
});
const app = express();
app.use(cors());
app.use(bodyParser());
app.get("/code/:hash", async function (req, res) {
let collectionReference = await firestore
.collection(COLLECTION_NAME)
.where("hash", "==", req.params.hash)
.get();
res.status(200).json(collectionReference.docs.map((doc) => doc.data()));
});
app.get("/code", async function (_, res) {
let collectionReference = await firestore.collection(COLLECTION_NAME).get();
res.status(200).json(collectionReference.docs.map((doc) => doc.data()));
});
app.post("/code", async function (req, res) {
const { content, language, name } = req.body;
const current_date = new Date().valueOf().toString();
const random = Math.random().toString();
const newHash = crypto
.createHash("sha1")
.update(current_date + random)
.digest("hex");
const payload = {
content,
language,
name,
hash: newHash,
};
try {
const document = firestore.doc(`${COLLECTION_NAME}/${newHash}`);
await document.set(payload);
res.status(200).json({
...payload,
message: "successful upload",
});
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Application running on ${PORT}`));