In the last section, we built a basic todo list servier with get functions and set all the things right.
Now, we should add create, update and delete abilities to it.
Here We Go
As we have already setup properly, now all have to do is to add methods to the controller.
POST Item
Now we are implementing a method for creating todo items (remember to import neccesary components from @t2ee/vader).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Consumes('application/json')
@POST
@Path('/:id?')
async postItem(@Body body, @PathParam('id') id) {
if (!id) {
id = LIST.length;
} else {
id = parseInt(id);
}
const item = {
id,
name: body.name,
};
LIST.push(item);
const response = new Response();
response.body = item;
return response;
}
@Consumes('application/json') tells vader to consume request body as json.
@Body binds the requested body. At this moment, we haven’t done any type checking yet, so it’s an any variable.
@Path('/:id?'), the parameter in @Path() is slightly different from what we used in getItem(). In this format, we can make parameter id optional. Thus, we can get id from either body or path.
PUT and DELETE item
Like how we implmeneted the postItem method, put and delete should be almost the same.
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
@Consumes('application/json')
@PUT
@Path('/:id?')
async putItem(@Body body, @PathParam('id') id) {
if (!id) {
id = body.id;
} else {
id = parseInt(id);
}
const item = LIST.find(todo => todo.id === id);
if (item) {
item.name = body.name;
const response = new Response();
response.body = item;
return response;
}
}
@DELETE
@Path('/:id')
async deleteItem(@PathParam('id') id) {
id = parseInt(id);
const index = LIST.findIndex(todo => todo.id === id);
if (index >= 0) {
LIST.splice(index, 1);
const response = new Response();
response.body = 'OK';
return response;
}
}
Conclusion
Now we have a full functional todo item api service. In the next section, we will be discussing some other advantage usages with @t2ee components.