-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrud.js
121 lines (106 loc) · 2.38 KB
/
crud.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
/// <reference path="../scripts/bundles/global.d.ts" />
let id = 3;
/** @type {(url: string, options?: RequestInit) => Promise<any>} */
const mockFetch = window.mockFetch;
/**
* @typedef {{ id: number; name: string; surname: string; }} Person
* @param {Person} person
* @returns {Person}
*/
function copyPerson(person) {
return {
id: person.id,
name: person.name,
surname: person.surname
};
}
export function getInitialState() {
return [
{ id: 0, name: "Hans", surname: "Emil" },
{ id: 1, name: "Max", surname: "Mustermann" },
{ id: 2, name: "Roman", surname: "Tisch" }
];
}
export function createApi() {
/**
* @type {Person[]}}
*/
const store = getInitialState();
function getPersonById(id) {
for (let person of store) {
if (person.id == id) {
return person;
}
}
return null;
}
return {
/**
* @param {string} name
* @param {string} surname
* @returns {Promise<Person>}
*/
create(name, surname) {
/** @type {Person} */
const person = {
id: id++,
name,
surname
};
return mockFetch("/persons", {
method: "PUT",
body: JSON.stringify(person)
}).then(() => {
store.push(person);
return copyPerson(person);
});
},
/**
* @returns {Promise<Person[]>}
*/
listAll() {
return mockFetch("/persons").then(() => store.map(copyPerson));
},
/**
* @param {number} id
* @returns {Promise<Person>}
*/
read(id) {
return mockFetch(`/persons/${id}`).then(() =>
copyPerson(getPersonById(id))
);
},
/**
* @param {number} id
* @param {string} name
* @param {string} surname
* @returns {Promise<Person>}
*/
update(id, name, surname) {
const body = JSON.stringify({ name, surname });
return mockFetch(`/persons/${id}`, { method: "POST", body }).then(() => {
const person = getPersonById(id);
if (person == null) {
throw new Error(`Could not find person with id "${id}".`);
}
person.name = name;
person.surname = surname;
return copyPerson(person);
});
},
/**
* @param {number} id
* @returns {Promise<Person>}
*/
remove(id) {
return mockFetch(`/persons/${id}`, { method: "DELETE" }).then(() => {
const person = getPersonById(id);
if (person == null) {
throw new Error(`Could not find person with id "${id}".`);
}
store.splice(store.indexOf(person), 1);
return copyPerson(person);
});
}
};
}