-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
355 lines (306 loc) · 11.3 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import Joi from 'joi';
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerJsDoc from 'swagger-jsdoc';
const app = express();
app.use(express.json());
const port = process.env.PORT || 1227;
//Set options for swaggerJsDoc (OpenAPI)
const openApiOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'Sample Students API for a university project',
contact: {
name: "86x on GitHub",
url: "https://github.com/86x/example-openapi-swagger-jsdoc"
},
version: '1.0.0',
servers: [`http://localhost:${port}`]
}
},
apis: ['index.js', 'additionalOpenApiDocs.js']
};
const openApiDocs = await swaggerJsDoc(openApiOptions);
//Make OpenAPI description file available as json file
app.get('/api/docs/openapi.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(openApiDocs);
});
//Serve Swagger UI (OpenAPI) Documentation
app.use ('/api/docs', swaggerUi.serve, swaggerUi.setup(openApiDocs));
let students = [
{ matrNum: 1230000033, firstName: "Jack", lastName: "Daniels", cantineCredit: 24.5 },
{ matrNum: 1230000026, firstName: "Jim", lastName: "Beam", cantineCredit: 1.0 },
{ matrNum: 1230000039, firstName: "Charlie", lastName: "Harper", cantineCredit: 122000.4 }
];
app.get('/', (req, res) => {
res.send("<h1>It works!</h1>");
});
/**
* @openapi
* /api/v1/students:
* parameters:
* - $ref: "#/components/parameters/sortBy"
* get:
* summary: Gets all students
* description: Returns all students
* tags:
* - Students
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/students"
* example:
* - matrNum: 1230000001
* firstName: "John"
* lastName: "Doe"
* cantineCredit: 12.5
* - matrNum: 1230000003
* firstName: "Simeon"
* lastName: "Yetarian"
* cantineCredit: 123000.4
* - matrNum: 1230000010
* firstName: "Michael without a last name"
* lastName: null
* cantineCredit: 999999.99
*/
app.get('/api/v1/students', (req, res) => {
//If sortBy query-parameter is set, sort by firstName, lastName or default to matrNum if unknown
if(req.query && req.query.sortBy){
let studentsClone = [...students];
switch(req.query.sortBy){
case "firstName":
//Sort by Name: Thx https://stackoverflow.com/a/6712058
return res.send(studentsClone.sort((a, b) => a.firstName.localeCompare(b.firstName)));
case "lastName":
return res.send(studentsClone.sort((a, b) => a.lastName.localeCompare(b.lastName)));
default:
return res.send(studentsClone.sort((a, b) => a.matrNum - b.matrNum));
}
}
//Return all students to user
res.send(students);
});
/**
* @openapi
* /api/v1/student/{matrNum}:
* parameters:
* - $ref: "#/components/parameters/matrNum"
* get:
* summary: Gets a single student
* description: Gets a student with the specified matrNum or return an error message if no student with this matrNum exists.
* tags:
* - Students
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/student"
* 404:
* description: No student with the specified matrNum exists
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/errorResponse"
* example:
* error:
* "This student was not found"
*/
app.get('/api/v1/student/:matrNum', (req, res) => {
const student = findStudent(req.params.matrNum);
//If student does not exist, send 404 Not Found error
if(!student){
return res.status(404).send({error: "This student was not found"});
}
//Return student object to user
res.send(student);
});
/**
* @openapi
* /api/v1/students/add:
* post:
* summary: Add a single student
* description: Adds a student with the specified firstName and lastName. The matrNum is automatically generated and cantineCredit will be zero.
* tags:
* - Students
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* firstName:
* $ref: "#/components/schemas/firstName"
* lastName:
* $ref: "#/components/schemas/lastName"
* responses:
* 201:
* description: Created
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/student"
* 400:
* description: Invalid input
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/errorResponse"
* example:
* error:
* "\"firstName\" is required"
*/
app.post('/api/v1/students/add', (req, res) => {
//Validate POST user input
const { error } = validateStudent(req.body, true);
//If POST user input is invalid, send 400 Bad Request error
if(error !== undefined){
return res.status(400).send({ error: error.details[0].message });
}
//Generate a new matrNum by adding 1 to the currently highest matrNum
const newMatrNum = Math.max.apply(Math, students.map(function(o) { return o.matrNum + 1; }));
//Build new student object
const newStudent = {
matrNum: newMatrNum,
firstName: req.body.firstName || null,
lastName: req.body.lastName || null,
cantineCredit: 0.0
};
//Add new student object to students
students.push(newStudent);
console.log(`Added new student ${newStudent.firstName + " " + newStudent.lastName} with matrNum ${newMatrNum}`);
//Return created student
res.status(201).send(newStudent);
});
/**
* @openapi
* /api/v1/student/{matrNum}:
* parameters:
* - $ref: "#/components/parameters/matrNum"
* put:
* summary: Updates a student's info
* description: Updates firstName, lastName or both at the same time of the student with the specified matrNum, if one exists.
* tags:
* - Students
* requestBody:
* content:
* application/json:
* schema:
* type: object
* properties:
* firstName:
* $ref: "#/components/schemas/firstName"
* lastName:
* $ref: "#/components/schemas/lastName"
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/student"
* 404:
* description: No student with the specified matrNum exists
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/errorResponse"
* example:
* error:
* "This student was not found"
*/
app.put('/api/v1/student/:matrNum', (req, res) => {
const student = findStudent(req.params.matrNum);
//If student does not exist, send 404 Not Found error
if(!student){
return res.status(404).send({ error: "This student was not found" });
}
//Validate PUT user input
const { error } = validateStudent(req.body, false);
//If PUT user input is invalid, send 400 Bad Request error
if(error !== undefined){
return res.status(400).send(error.details[0].message);
}
//Update student's information
if(req.body.firstName){ student.firstName = req.body.firstName; }
if(req.body.lastName){ student.lastName = req.body.lastName; }
//Return updated student to user
res.send(student);
});
/**
* @openapi
* /api/v1/student/{matrNum}:
* parameters:
* - $ref: "#/components/parameters/matrNum"
* delete:
* summary: Deletes a student
* description: Immediately deletes the student with the specified matrNum, if one exists.
* tags:
* - Students
* responses:
* 200:
* description: Deleted student successfully
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/student"
* 404:
* description: No student with the specified matrNum exists
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/errorResponse"
* example:
* error:
* "This student was not found"
*/
app.delete('/api/v1/student/:matrNum', (req, res) => {
const student = findStudent(req.params.matrNum);
//If student does not exist, send 404 Not Found error
if(!student){
return res.status(404).send({ error: "This student was not found" });
}
//Delete student
const studentIndex = students.indexOf(student);
students.splice(studentIndex, 1);
//Return deleted student to user
res.send(student);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
/**
* Checks that the specified student object contains a firstName of type string which consists
* of at least 1 character and a lastName of type string which consists of at least 1 character
* @param student object with a firstName and lastName attribute
* @param requireAll If true, firstName and lastName are required. If false, only what is sent is being validated.
* @returns
*/
function validateStudent(student, requireAll){
if(requireAll){
var inputSchema = Joi.object({
firstName: Joi.string().min(1).required(),
lastName: Joi.string().min(1).required()
});
return inputSchema.validate(student);
} else{
var inputSchema = Joi.object({
firstName: Joi.string().min(1),
lastName: Joi.string().min(1)
});
return inputSchema.validate(student);
}
}
/**
* Finds a student in the students array and returns it, if one is found.
* @param matrNum matrNum of student object in students
* @returns student object
*/
function findStudent(matrNum){
return students.find(s => s.matrNum === parseInt(matrNum));
}