-
Notifications
You must be signed in to change notification settings - Fork 13
/
rest-server.js
83 lines (70 loc) · 2.51 KB
/
rest-server.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
'use strict'
const express = require('express')
const server = express()
// Get the Mongoose models used for querying the database
const { User } = require('./models.js')
// A list of the fields that are allowed to be accessed
const defaultFields = ['_id', 'username', 'group']
// Filter a user object based on the requested fields
const filterFields = async function(req, user) {
// We assume the fields are a comma-separated list of field
// names. If none are specified, we return all fields.
const fieldKeys = req.query.fields
? req.query.fields.split(',')
: defaultFields
// Generate a new object that contains only those fields.
const filteredUser = {}
for (const field of fieldKeys) {
// If the field is a function then we expect it to return
// a Promise which we will immediately resolve.
if (typeof user[field] === 'function') {
filteredUser[field] = await user[field]()
} else {
filteredUser[field] = user[field]
}
}
return filteredUser
}
// Listen for all GET requests to /users/:id URL (where the
// ID is the ID of the user account)
server.get('/users/:id', (req, res) => {
// Try to find the user by their id (_id field), using the ID
// parameter from the URL.
User.findById(req.params.id, async (err, user) => {
if (err) {
// The DB returned an error so we return a 500 error
return res.status(500).end()
}
if (!user) {
// No user was found so we return a 404 error
return res.status(404).end()
}
// Return the user to the client (automatically serialized
// as a JSON string). We need to wait for all of the fields
// to load before we can return the results.
res.send(await filterFields(req, user))
})
})
// Listen for all GET requests to /users
server.get('/users', (req, res) => {
// Find all of the users in the database collection (we pass in
// an empty collection as we aren't filtering the results)
User.find({}, async (err, users) => {
if (err) {
// The DB returned an error so we return a 500 error
return res.status(500).end()
}
// Return the array of users to the client (automatically
// serialized as a JSON string) We need to wait for all
// of the Promises to resolve for all of the users.
res.send(await Promise.all(users.map(user => filterFields(req, user))))
})
})
// Start the application, listening on port 3000
server.listen(3000, () =>
console.log(`Listening on port 3000. Try:
http://localhost:3000/users/123
or
http://localhost:3000/users
`)
)