-
Notifications
You must be signed in to change notification settings - Fork 3
/
model.js
66 lines (61 loc) · 1.74 KB
/
model.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
import { GrampsError } from '@gramps/errors';
import { GraphQLModel } from '@gramps/rest-helpers';
export default class XKCDModel extends GraphQLModel {
/**
* Loads the latest xkcd comic.
* @return {Promise} resolves with the loaded comic data
*/
getLatestComic() {
return this.connector.get(`/info.0.json`).catch(res =>
this.throwError(res.error, {
description: 'Could not load the latest xkcd comic',
}),
);
}
/**
* Loads an xkcd comic by its ID.
* @param {String} id the ID of the comic to load
* @return {Promise} resolves with the loaded comic data
*/
getComicById(id) {
return this.connector.get(`/${id}/info.0.json`).catch(res => {
const description =
res.statusCode >= 400 && res.statusCode < 500
? 'Comic not found'
: 'Could not load the given xkcd comic';
return this.throwError(false, {
statusCode: res.statusCode,
targetEndpoint: `${this.connector.apiBaseUri}/${id}/info.0.json`,
data: { id },
description,
});
});
}
/**
* Throws a custom GrAMPS error.
* @param {Object} error the API error
* @param {Object?} customErrorData additional error data to display
* @return {void}
*/
throwError(
{
statusCode = 500,
message = 'Something went wrong.',
targetEndpoint = null,
} = {},
customErrorData = {},
) {
const defaults = {
statusCode,
targetEndpoint,
errorCode: `${this.constructor.name}_Error`,
description: message,
graphqlModel: this.constructor.name,
docsLink: 'https://ibm.biz/gramps-data-source-tutorial',
};
throw GrampsError({
...defaults,
...customErrorData,
});
}
}