-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
api.controller.ts
62 lines (51 loc) 路 1.82 KB
/
api.controller.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
import {
Context, Delete, Get, HttpResponseCreated, HttpResponseNoContent,
HttpResponseNotFound, HttpResponseOK, Post,
ValidateBody, ValidatePathParam
} from '@foal/core';
import { Todo } from '../models';
export class ApiController {
@Get('/todos')
async getTodos() {
const todos = await Todo.find();
return new HttpResponseOK(todos);
}
@Post('/todos')
@ValidateBody({
// The body request should be an object once parsed by the framework.
// Every additional properties that are not defined in the "properties"
// object should be removed.
additionalProperties: false,
properties: {
// The "text" property of ctx.request.body should be a string if it exists.
text: { type: 'string' }
},
// The property "text" is required.
required: [ 'text' ],
type: 'object',
})
async postTodo(ctx: Context) {
// Create a new todo with the body of the HTTP request.
const todo = new Todo();
todo.text = ctx.request.body.text;
// Save the todo in the database.
await todo.save();
// Return the new todo with the id generated by the database. The status is 201.
return new HttpResponseCreated(todo);
}
@Delete('/todos/:id')
// The id should be a string. If it is not, the hook returns a "400 - Bad Request" error.
@ValidatePathParam('id', { type: 'string' })
async deleteTodo(ctx: Context) {
// Get the todo with the id given in the URL if it exists.
const todo = await Todo.findById(ctx.request.params.id);
// Return a 404 Not Found response if no such todo exists.
if (!todo) {
return new HttpResponseNotFound();
}
// Remove the todo from the database.
await Todo.findByIdAndRemove(ctx.request.params.id);
// Returns an successful empty response. The status is 204.
return new HttpResponseNoContent();
}
}