forked from onetalksoft/fastify-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (92 loc) · 2.44 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
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
const fastify = require('fastify')
// Import "mongoose"
const mongoose = require("mongoose")// Import our "User" model
const User = require("./User")
const app = fastify()
const mongoUrl = process.env.MONGODB_URI || "mongodb://localhost:27017/"/** connect to MongoDB datastore */
try {
mongoose.connect(mongoUrl)
} catch (error) {
console.error(error)
}
app.get("/api/users", (request, reply) => {
User.find({}, (err, users) => {
if (!err) {
reply.send(users)
} else {
reply.send({ error: err })
}
})
})
app.get("/new", (request, reply) => {
User.find({}, (err, users) => {
if (!err) {
reply.send(users)
} else {
reply.send({ error: err })
}
})
})
app.get("/api/users/:userId", (request, reply) => {
var userId = request.params.userId
User.findById(userId, (err, user) => {
if (!err) {
reply.send(user)
} else {
reply.send({ error: err })
}
})
})
app.post("/api/users", (request, reply) => {
var user = request.body
User.create(user, (err, user) => {
if (!err) {
reply.send(user)
} else {
reply.send({ error: err })
}
})
})
app.put("/api/users/:userId", (request, reply) => {
var userId = request.params.userId
var newUserEdit = request.body
User.findById(userId, (err, user) => {
if (!err) {
user.age = newUserEdit.age
user.name = newUserEdit.name
user.email = newUserEdit.email
user.save((er, savedUser) => {
if (!er) {
reply.send(savedUser)
} else {
reply.send(er)
}
})
} else {
reply.send({ error: err })
}
})
})
app.put("/api/users/:userId", (request, reply) => {
var userId = request.params.userId
User.findById(userId, (err, user) => {
if (!err) {
user.remove((er) => {
if (!er) {
reply.send("USER DELETED")
} else {
reply.send({ error: er })
}
})
} else {
reply.send({ error: err })
}
})
})// Start the server
app.listen(3000, function (err, address) {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening on ${address}`)
})