-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
103 lines (86 loc) · 2.44 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var restify = require('restify'),
mongojs = require('mongojs')
var config = {
app: {
name: 'pokedex',
address: '127.0.0.1',
port: 8080
},
mongo: {
address: '127.0.0.1',
port: 27017,
base: 'pokedex'
}
}
var db = mongojs(config.mongo.address + ':' + config.mongo.port + '/' + config.mongo.base, [config.mongo.base])
var Pokemons = db.collection('pokemons')
var server = restify.createServer({
name: config.app.name
})
server.use(restify.queryParser()) // Parsed contend into req.query
server.use(restify.bodyParser()) // Request data into JavaScript object
server.use(restify.CORS()) // CORS support
// Routes
var pokemonsPath = '/pokemons'
server.get(pokemonsPath, findAllPokemons)
server.get(pokemonsPath + '/:pokemonId', findPokemon)
server.post(pokemonsPath, createPokemon)
server.put(pokemonsPath + '/:pokemonId', editPokemon)
server.del(pokemonsPath + '/:pokemonId', removePokemon)
server.listen(config.app.port, config.app.address, function() {
console.log('%s listening at %s', server.name, server.url)
})
// Callbacks
function findAllPokemons(req, res, next) {
Pokemons.find().sort({ 'postedOn': -1 }, function(err, pokemons) {
if(err) return next(err)
res.send(200, pokemons)
return next()
})
}
function findPokemon(req, res, next) {
Pokemons.findOne({ _id: mongojs.ObjectId(req.params.pokemonId) }, function(err, pokemon) {
if(err) return next(err)
res.send(200, pokemon)
return next()
})
}
function createPokemon(req, res, next) {
var params = req.params,
now = new Date()
var pokemon = {
name: params.name,
created_at: now,
updated_at: now
}
Pokemons.save(pokemon, function(err) {
if(err) return next(err)
res.send(201, pokemon)
return next()
})
}
function editPokemon(req, res, next) {
var params = req.params
var pokemon = { updated_at: new Date() }
if(typeof params.name !== 'undefined') {
pokemon.name = params.name
}
var objectId = mongojs.ObjectId(params.pokemonId)
Pokemons.update({ _id: objectId }, { $set: pokemon }, function(err) {
if(err) return next(err)
Pokemons.findOne({ _id: objectId }, function(err, pokemon) {
if(err) return next(err)
res.send(200, pokemon)
return next()
})
})
}
function removePokemon(req, res, next) {
Pokemons.remove({
_id: mongojs.ObjectId(req.params.pokemonId)
}, function(err) {
if(err) return next(err)
res.send(204)
return next()
})
}