forked from CodeNow/api-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (47 loc) · 1.38 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
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()
mongoose.connect(`mongodb://${mongoHost}/todo`)
mongoose.connection.on('error', () => {
console.log('ERROR: Unable to connect to MongoDB... retrying')
mongoose.connect(`mongodb://${mongoHost}/todo`)
})
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)