-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfetchAPI.js
99 lines (77 loc) · 2.19 KB
/
fetchAPI.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
/*You are given the following API -
GET /api/comments
This will return a list of all comments. A comment object contains the following information
userId - ID of the user who commented
data - comment data
Given a userId, return an Array of comment data of all the comments by the given user.
Apart from .json(), don’t use any other methods on the response object returned from fetch() call. This can cause your tests to fail.
Input -
userId - the user id whose comment is to be returned.
Output -
A list of comments by the given user id
Sample input 1 -
userId = 1
Sample API response
comments = [
{
'userId': '1',
"data": 'This looks slick!'
},
{
'userId': '2',
"data": 'I think this can be improved.'
},
{
'userId': '1',
"data": 'What kind of improvement?'
}]
Sample output 1 -
['This looks slick!', 'What kind of improvement?']
*/
// TODO - Implement getCommentsByUserId() function
async function getCommentsByUserId(userId) {
return fetch("/api/comments")
.then(response => response.json())
.then(comments => {
let filteredComments =
comments.filter(comments => comments.userId === userId)
let result = [];
for(let i=0; i< filteredComments.length; i++){
result[i] = filteredComments[i].data;
}
return result;
})
}
// ----------- Don't modify -----------
const mockFetch = (url, responseData) => {
const mockJsonPromise = Promise.resolve(responseData);
const mockFetchPromise = (callUrl) => {
if (url === callUrl) {
return Promise.resolve({
json: () => mockJsonPromise
});
} else {
return Promise.reject('404: No such url')
}
}
global.fetch = mockFetchPromise;
}
const successResponse = [
{
'userId': '1',
"data": 'This looks slick!'
},
{
'userId': '2',
"data": 'I think this can be improved.'
},
{
'userId': '1',
"data": 'What kind of improvement?'
}];
mockFetch('/api/comments', successResponse);
module.exports = getCommentsByUserId;
// ----------- Don't modify -----------
getCommentsByUserId("1").then((res) => {
console.log(res);
});