-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
121 lines (112 loc) · 3.09 KB
/
app.ts
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import * as express from "express";
import * as bodyParser from "body-parser";
import Datastore from "./async-nedb";
let port = 3000;
let root = `http://localhost:${ port }`;
let app = express();
app.use(bodyParser.json());
let db = {
movies: new Datastore<{
title: string;
rating?: number;
}>({
filename: "db/movies",
autoload: true
})
};
app.get("/", (request, response) => {
response.send("API is working.");
});
app.get("/movies", (request, response) => {
db.movies.findAsync({})
.then((results) => {
response.json(200, results);
})
.catch((error) => {
response.json(500, { error: error });
});
});
app.post("/movies", (request, response) => {
if (!request.body.title) {
response.json(400, {
error: {
message: "A title is required to create a new movie."
}
});
return;
}
db.movies.insertAsync({
title: request.body.title
}).then((document) => {
response.set("location", `${ root }/movies/${ document._id }`);
response.json(201, document);
}).catch((error) => {
response.json(500, { error: error });
});
});
app.get("/movies/:id", (request, response) => {
db.movies.findOneAsync({
_id: request.params.id
}).then((document) => {
if (!document) {
response.json(404, {
error: {
message: `We did not find a movie with id: ${
request.params.id
}`
}
});
return;
}
response.json(200, document);
}).catch((error) => {
response.json(500, { error: error });
});
});
app.put("/movies/:id", (request, response) => {
db.movies.updateAsync(
{ title: request.params.id },
{ $set: { rating: request.body.rating } }
).then((result) => {
if (result.numberOfUpdated === 0) {
response.json(400, {
error: {
message: "No records were updated"
}
})
return;
}
response.json(204, {
success: {
message: `Successfully updated movie with ID ${
request.params.id
}`
}
});
}).catch((error) => {
response.json(500, { error: error });
});
});
app.delete("/movies/:id", (request, response) => {
db.movies.removeAsync(
{ _id: request.params.id }
).then((numberOfDeleted) => {
if (numberOfDeleted === 0) {
response.json(404, {
error: {
message: `We did not find a movie with id: ${
request.params.id
}`
}
});
return;
}
response.set("link", `${ root }/movies; rel="collection"`);
response.send(204);
}).catch((error) => {
response.json(500, { error: error });
});
});
app.listen(3000, () => {
console.log("Server started on 3000");
});