-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (56 loc) · 1.64 KB
/
index.js
File metadata and controls
67 lines (56 loc) · 1.64 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
55
56
57
58
59
60
61
62
63
64
65
66
67
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const bodyParser = require('body-parser')
const app = express()
const host = process.env.RUNNABLE_CONTAINER_URL || 'localhost'
const port = 3000
const mongoHost = process.env.MONGODB_HOST || 'localhost:27017'
const appInfo = require('./package.json')
const launched = new Date()
let connectionAttempts = 0
mongoose.connect(`mongodb://${mongoHost}/todo`)
mongoose.connection.on('error', () => {
if (connectionAttempts > 10) {
console.log('Unable to connect to MongoDB, exiting.')
process.exit(1);
}
console.log('ERROR: Unable to connect to MongoDB... waiting 5 seconds')
setTimeout(function () {
console.log('Retrying connection to MongoDB')
mongoose.connect(`mongodb://${mongoHost}/todo`)
connectionAttempts += 1
}, 5000)
})
const todos = require('./todos')
function logErrors (err, req, res, next) {
console.error(err.stack)
next(err)
}
function errorHandler (err, req, res, next) {
res.status(500)
res.json({ error: err })
}
app.listen(port, () => {
var hostName = 'http://' + host + ':' + port
console.log('Application running at: ' + hostName)
})
app.use(bodyParser.json())
app.use(logErrors)
app.use(errorHandler)
app.use(cors())
// Routes
app.get('/', function (req, res) {
res.send({
name: appInfo.name,
version: appInfo.version,
author: appInfo.author,
deployed: launched.toLocaleString()
})
})
app.get('/todos', todos.all)
app.get('/todos/:id', todos.one)
app.post('/todos', todos.create)
app.put('/todos/:id', todos.update)
app.delete('/todos/:id', todos.delete)