forked from freiksenet/graphql-finland-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonPlaceholderResource.js
38 lines (33 loc) · 934 Bytes
/
JsonPlaceholderResource.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
const fetch = require("node-fetch");
class JsonPlaceholderResource {
constructor(apiUrl) {
this.apiUrl = apiUrl;
}
async query(resource) {
console.log(resource);
const result = await fetch(`${this.apiUrl}${resource}`);
if (result.status === 200) {
return result.json();
} else {
throw new Error(`Error querying REST API, url: ${resource}`);
}
}
async post(resource, payload) {
const result = await fetch(`${this.apiUrl}${resource}`, {
method: "PUT",
body: JSON.stringify(payload),
headers: {
"Content-Type": "application/json"
}
});
if (result.status === 200) {
const resultJson = await result.json();
console.log(resultJson);
return resultJson;
} else {
console.log(await result.text());
throw new Error(`Error querying REST API, url: ${resource}`);
}
}
}
module.exports = JsonPlaceholderResource;