-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (39 loc) · 1.18 KB
/
Copy pathserver.js
File metadata and controls
43 lines (39 loc) · 1.18 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
"use latest";
import bodyParser from "body-parser";
import express from "express";
import Webtask from "webtask-tools";
import { MongoClient } from "mongodb";
import { ObjectID } from "mongodb";
const database = "tecel";
const collection = "lights";
const server = express();
server.use(bodyParser.json());
server.get("/", (req, res, next) => {
const { MONGO_URL } = req.webtaskContext.secrets;
MongoClient.connect(MONGO_URL, (err, client) => {
if (err) return next(err);
const db = client.db(database);
db.collection(collection)
.find()
.toArray((qerr, items) => {
client.close();
if (err) return next(err);
res.status(200).send(items);
});
});
});
server.post("/", (req, res, next) => {
const { MONGO_URL } = req.webtaskContext.secrets;
const model = req.body;
model.date = new Date().getTime();
MongoClient.connect(MONGO_URL, (err, client) => {
if (err) return next(err);
const db = client.db(database);
db.collection(collection).insertOne(model, (qerr, result) => {
client.close();
if (qerr) return next(qerr);
res.status(201).send(result);
});
});
});
module.exports = Webtask.fromExpress(server);