forked from bananaoomarang/isomorphic-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redux-tutorial-backend.js
73 lines (60 loc) · 1.58 KB
/
redux-tutorial-backend.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
'use latest';
const express = require('express');
const webtask = require('webtask-tools');
const Bluebird = require('bluebird');
const { MongoClient } = require('mongodb');
const app = express();
Bluebird.promisifyAll(MongoClient);
app.post('/', function (req, res) {
const MONGO_URL = req.webtaskContext.data.MONGO_URL;
const text = req.webtaskContext.data.text;
MongoClient.connectAsync(MONGO_URL)
.then(db => {
db
.collection('todos')
.find()
.toArray((e, a) => {
if(e) throw e;
if(a.length >= 50)
db
.collection('todos')
.deleteMany({}, e => {
if(e) throw e;
})
});
return db;
})
.then(db => {
db
.collection('todos')
.insertOne({ text }, e => {
if(e) throw e;
res.json({
text: req.webtaskContext.data.text
});
});
})
.catch(e => {
console.error(e);
res.status(500).end('Error saving to DB');
})
});
app.get('/', function (req, res) {
const MONGO_URL = req.webtaskContext.data.MONGO_URL;
MongoClient.connectAsync(MONGO_URL)
.then(db => {
db
.collection('todos')
.find()
.toArray((e, a) => {
if(e) throw e;
res.json(a.map(obj => obj.text));
});
})
.catch(e => {
console.error(e);
res.status(500).end('Error loading from DB');
})
});
// expose this express app as a webtask-compatible function
module.exports = webtask.fromExpress(app);