-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.ts
76 lines (68 loc) · 2.23 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import CaseItem from './CaseItem.ts'
import db from './db.ts'
let caseItems = db;
/**
* @description Get all cases
* @route GET /cases
*/
const getCaseItems = ({ response }: { response: any }) => {
response.status = 200;
response.body = caseItems;
};
/**
* @description Get a case by Id
* @route GET /cases/:id
*/
const getCaseItem = ({ params, response }: { params: { id: string }; response: any }) => {
const caseItem: CaseItem | undefined = searchCaseItemById(params.id);
if (caseItem) {
response.status = 200;
response.body = caseItem;
} else {
response.status = 404;
response.body = { message: 'Case not found.' };
}
}
/**
* @description Add a new case
* @route POST /cases
*/
const addCaseItem = async ({ request, response }: { request: any; response: any }) => {
const body = await request.body();
const caseItem: CaseItem = await body.value;
caseItems.push(caseItem);
response.body = { message: 'OK' };
response.status = 200;
}
/**
* @description Update a case by Id
* @route PUT /cases/:id
*/
const updateCaseItem = async ({ params, request, response }: { params: { id: string }; request: any; response: any }) => {
let caseItem: CaseItem | undefined = searchCaseItemById(params.id);
if (caseItem) {
const body = await request.body();
const updateInfos: { customer?: string; product?: string; notes?: string } = await body.value;
caseItem = { ...caseItem, ...updateInfos};
caseItems = [...caseItems.filter(caseItem => caseItem.id !== params.id), caseItem];
response.status = 200;
response.body = { message: 'OK' };
} else {
response.status = 404;
response.body = { message: `Case not found` };
}
}
/**
* @description Delete a case by id
* @route DELETE /cases/:id
*/
const deleteCaseItem = ({ params, response }: { params: { id: string }; response: any }) => {
caseItems = caseItems.filter(caseItem => caseItem.id !== params.id);
response.body = { message: 'OK' };
response.status = 200;
};
/**
* @description return the case if found and undefined if not
*/
const searchCaseItemById = (id: string): ( CaseItem | undefined ) => caseItems.filter(caseItem => caseItem.id === id )[0];
export { getCaseItems, addCaseItem, getCaseItem, updateCaseItem, deleteCaseItem }