-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
64 lines (55 loc) · 1.67 KB
/
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
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const User = require('./users')
mongoose.connect('mongodb://localhost/pagination', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.once('open', async () => {
if (await User.countDocuments().exec() > 0) return
Promise.all([
User.create({ name: 'User 1' }),
User.create({ name: 'User 2' }),
User.create({ name: 'User 3' }),
User.create({ name: 'User 4' }),
User.create({ name: 'User 5' }),
User.create({ name: 'User 6' }),
User.create({ name: 'User 7' }),
User.create({ name: 'User 8' }),
User.create({ name: 'User 9' }),
User.create({ name: 'User 10' }),
User.create({ name: 'User 11' }),
User.create({ name: 'User 12' })
]).then(() => console.log('Added Users'))
})
app.get('/users', paginatedResults(User), (req, res) => {
res.json(res.paginatedResults)
})
function paginatedResults(model) {
return async (req, res, next) => {
const page = parseInt(req.query.page)
const limit = parseInt(req.query.limit)
const startIndex = (page - 1) * limit
const endIndex = page * limit
const results = {}
if (endIndex < await model.countDocuments().exec()) {
results.next = {
page: page + 1,
limit: limit
}
}
if (startIndex > 0) {
results.previous = {
page: page - 1,
limit: limit
}
}
try {
results.results = await model.find().limit(limit).skip(startIndex).exec()
res.paginatedResults = results
next()
} catch (e) {
res.status(500).json({ message: e.message })
}
}
}
app.listen(3000)