1 |
|
2 | const SriClient = require('../sri-client.js');
|
3 | const commonUtils = require('../common-utils');
|
4 | const SriClientError = require('../sri-client-error');
|
5 |
|
6 | class FetchClient extends SriClient {
|
7 |
|
8 | constructor(config = {}) {
|
9 | super(config);
|
10 | this.setDefaultHeaders(config);
|
11 | this.cache.initialise();
|
12 | }
|
13 |
|
14 | setDefaultHeaders(config) {
|
15 | this.defaultHeaders = config.headers || {};
|
16 | |
17 |
|
18 |
|
19 | if(config.accessToken) {
|
20 | this.defaultHeaders[config.accessToken.name] = config.accessToken.value;
|
21 | }
|
22 | }
|
23 |
|
24 | setConfiguration(config) {
|
25 | super.setConfiguration(config);
|
26 | this.setDefaultHeaders(config);
|
27 | }
|
28 |
|
29 | async getRaw(href, params, options = {}) {
|
30 | var baseUrl = this.getBaseUrl(options);
|
31 | const logging = options.logging || this.configuration.logging;
|
32 | if(logging && typeof logging === 'string' && /get/.test(logging.toLowerCase())) {
|
33 | console.log('[sri-client] GET ' + baseUrl + commonUtils.parametersToString(href, params));
|
34 | }
|
35 | const stack = new Error().stack;
|
36 | try {
|
37 | const response = await fetch(baseUrl + commonUtils.parametersToString(href, params), {
|
38 | method: 'GET',
|
39 | cache: 'no-cache',
|
40 | credentials: options.credentials || 'omit',
|
41 | redirect: options.redirect || "follow",
|
42 | signal: options.cancel,
|
43 | headers: Object.assign(this.defaultHeaders, options.headers ? options.headers : {})
|
44 | });
|
45 | if(response.ok) {
|
46 | const resp = await this.readResponse(response);
|
47 | return options.fullResponse ? resp : resp.body;
|
48 | } else {
|
49 | if(logging && typeof logging === 'string' && /get/.test(logging.toLowerCase())) {
|
50 | console.log('[sri-client] response is not ok!', response);
|
51 | }
|
52 | throw await this.handleError('GET ' + baseUrl + commonUtils.parametersToString(href, params), response, options, stack);
|
53 | }
|
54 | } catch(error) {
|
55 | if(error instanceof SriClientError) {
|
56 | throw error;
|
57 | }
|
58 | if(logging && typeof logging === 'string' && /get/.test(logging.toLowerCase())) {
|
59 | console.log('[sri-client] an error occured when doing fetch', error);
|
60 | }
|
61 | throw await this.handleError('GET ' + baseUrl + commonUtils.parametersToString(href, params), error, options, stack);
|
62 | }
|
63 | }
|
64 |
|
65 | async sendPayload(href, payload, options = {}, method) {
|
66 | const baseUrl = this.getBaseUrl(options);
|
67 | const logging = options.logging || this.configuration.logging;
|
68 | if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
|
69 | console.log('[sri-client] ' + method + ' ' + baseUrl + href + ':\n' + JSON.stringify(payload));
|
70 | }
|
71 | const stack = new Error().stack;
|
72 | if(!options.raw && options.strip$$Properties !== false) {
|
73 | if(payload instanceof Array) {
|
74 | payload = commonUtils.strip$$PropertiesFromBatch(payload);
|
75 | } else {
|
76 | payload = commonUtils.strip$$Properties(payload);
|
77 | }
|
78 | }
|
79 | try {
|
80 | const response = await fetch(baseUrl + href, {
|
81 | method: method,
|
82 | cache: 'no-cache',
|
83 | credentials: options.credentials || 'omit',
|
84 | redirect: options.redirect || 'follow',
|
85 | signal: options.cancel,
|
86 | headers: Object.assign(this.defaultHeaders, {'Content-Type': 'application/json;charset=UTF-8'}, options.headers ? options.headers : {}),
|
87 | body: options.raw ? payload : JSON.stringify(payload)
|
88 | });
|
89 |
|
90 | if(response.ok) {
|
91 | const resp = await this.readResponse(response);
|
92 | return options.fullResponse ? resp : resp.body;
|
93 | } else {
|
94 | if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
|
95 | console.log('[sri-client] response is not ok!', response);
|
96 | }
|
97 | throw await this.handleError(method + baseUrl + href, response, options, stack);
|
98 | }
|
99 | } catch (error) {
|
100 | if(error instanceof SriClientError) {
|
101 | throw error;
|
102 | }
|
103 | if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
|
104 | console.log('[sri-client] an error occured when doing fetch', error);
|
105 | }
|
106 | throw await this.handleError(method + baseUrl + href, error, options, stack);
|
107 | }
|
108 | }
|
109 |
|
110 | async delete(href, options = {}) {
|
111 | const baseUrl = this.getBaseUrl(options);
|
112 | const stack = new Error().stack;
|
113 | try {
|
114 | const response = await fetch(baseUrl + href, {
|
115 | method: 'DELETE',
|
116 | cache: 'no-cache',
|
117 | credentials: 'omit',
|
118 | signal: options.cancel,
|
119 | headers: Object.assign(this.defaultHeaders, options.headers ? options.headers : {})
|
120 | });
|
121 | if(response.ok) {
|
122 | const resp = await this.readResponse(response);
|
123 | return options.fullResponse ? resp : resp.body;
|
124 | } else {
|
125 | throw await this.handleError('DELETE' + baseUrl + href, response, options, stack);
|
126 | }
|
127 | } catch (error) {
|
128 | if(error instanceof SriClientError) {
|
129 | throw error;
|
130 | }
|
131 | throw await this.handleError('DELETE' + baseUrl + href, error, options, stack);
|
132 | }
|
133 | }
|
134 |
|
135 | async readResponse(response) {
|
136 | try {
|
137 | const headers = [...response.headers].reduce( (acc, cur) => Object.assign({}, acc, {[cur[0]]: cur[1]}), {} );
|
138 | const contentType = headers['content-type'];
|
139 |
|
140 | let body = null;
|
141 | body = await response.text();
|
142 | if(body && contentType.match(/application\/json/g)) {
|
143 | try {
|
144 | body = JSON.parse(body);
|
145 | } catch(err) {
|
146 | console.error('[sri-client] Json parse is mislukt!', response);
|
147 | }
|
148 | }
|
149 |
|
150 | return {
|
151 | headers: headers,
|
152 | body: body,
|
153 | redirected: response.redirected
|
154 | };
|
155 | } catch(err) {
|
156 | console.warn('[sri-client] Het response kon niet worden uitgelezen.', response);
|
157 | }
|
158 | }
|
159 |
|
160 | async handleError(httpRequest, response, options, stack) {
|
161 | if(!response || !(response instanceof Response)) {
|
162 | return response;
|
163 | }
|
164 |
|
165 | const resp = await this.readResponse(response);
|
166 |
|
167 | return new SriClientError({
|
168 | status: response.status || null,
|
169 | body: resp.body,
|
170 | originalResponse: response,
|
171 | headers: resp.headers
|
172 |
|
173 | });
|
174 | };
|
175 |
|
176 | };
|
177 |
|
178 |
|
179 |
|
180 | module.exports = function(configuration) {
|
181 | return new FetchClient(configuration);
|
182 | }; |
\ | No newline at end of file |