UNPKG

6.92 kBJavaScriptView Raw
1const SriClient = require('../sri-client.js');
2const commonUtils = require('../common-utils');
3const SriClientError = require('../sri-client-error');
4const nodeFetch = require('node-fetch');
5
6class NodeFetchClient 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 if(config.username && config.password) {
17 this.defaultHeaders['Authorization'] = 'Basic ' + Buffer.from(config.username + ':' + config.password).toString('base64');
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 nodeFetch(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 timeout: options.timeout || 0,
44 headers: Object.assign(this.defaultHeaders, options.headers ? options.headers : {})
45 });
46 if(response.ok) {
47 const resp = await this.readResponse(response);
48 return options.fullResponse ? resp : resp.body;
49 } else {
50 if(logging && typeof logging === 'string' && /get/.test(logging.toLowerCase())) {
51 console.log('[sri-client] response is not ok!', response);
52 }
53 throw await this.handleError('GET ' + baseUrl + commonUtils.parametersToString(href, params), response, options, stack);
54 }
55 } catch(error) {
56 if(error instanceof SriClientError) {
57 throw error;
58 }
59 if(logging && typeof logging === 'string' && /get/.test(logging.toLowerCase())) {
60 console.log('[sri-client] an error occured when doing fetch', error);
61 }
62 throw await this.handleError('GET ' + baseUrl + commonUtils.parametersToString(href, params), error, options, stack);
63 }
64 }
65
66 async sendPayload(href, payload, options = {}, method) {
67 const baseUrl = this.getBaseUrl(options);
68 const logging = options.logging || this.configuration.logging;
69 if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
70 console.log('[sri-client] ' + method + ' ' + baseUrl + href + ':\n' + JSON.stringify(payload));
71 }
72 const stack = new Error().stack;
73 if(!options.raw && options.strip$$Properties !== false) {
74 if(payload instanceof Array) {
75 payload = commonUtils.strip$$PropertiesFromBatch(payload);
76 } else {
77 payload = commonUtils.strip$$Properties(payload);
78 }
79 }
80 try {
81 const response = await nodeFetch(baseUrl + href, {
82 method: method,
83 cache: 'no-cache',
84 credentials: options.credentials || 'omit',
85 redirect: options.redirect || 'follow',
86 signal: options.cancel,
87 headers: Object.assign({}, this.defaultHeaders, {'Content-Type': 'application/json;charset=UTF-8'}, options.headers ? options.headers : {}),
88 body: options.raw ? payload : JSON.stringify(payload)
89 });
90
91 if(response.ok) {
92 const resp = await this.readResponse(response);
93 return options.fullResponse ? resp : resp.body;
94 } else {
95 if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
96 console.log('[sri-client] response is not ok!', response);
97 }
98 throw await this.handleError(method + baseUrl + href, response, options, stack);
99 }
100 } catch (error) {
101 if(error instanceof SriClientError) {
102 throw error;
103 }
104 if(logging && typeof logging === 'string' && (new RegExp(method.toLowerCase)).test(logging.toLowerCase())) {
105 console.log('[sri-client] an error occured when doing fetch', error);
106 }
107 throw await this.handleError(method + baseUrl + href, error, options, stack);
108 }
109 }
110
111 async delete(href, options = {}) {
112 const baseUrl = this.getBaseUrl(options);
113 const stack = new Error().stack;
114 try {
115 const response = await nodeFetch(baseUrl + href, {
116 method: 'DELETE',
117 cache: 'no-cache',
118 credentials: 'omit',
119 signal: options.cancel,
120 headers: Object.assign(this.defaultHeaders, options.headers ? options.headers : {})
121 });
122 if(response.ok) {
123 const resp = await this.readResponse(response);
124 return options.fullResponse ? resp : resp.body;
125 } else {
126 throw await this.handleError('DELETE' + baseUrl + href, response, options, stack);
127 }
128 } catch (error) {
129 if(error instanceof SriClientError) {
130 throw error;
131 }
132 throw await this.handleError('DELETE' + baseUrl + href, error, options, stack);
133 }
134 }
135
136 async readResponse(response) {
137 let headers = null;
138 try {
139 headers = [...response.headers].reduce( (acc, cur) => Object.assign({}, acc, {[cur[0]]: cur[1]}), {} );
140 const contentType = headers['content-type'];
141
142 let body = null;
143 body = await response.text();
144 if(body && contentType.match(/application\/json/g)) {
145 try {
146 body = JSON.parse(body);
147 } catch(err) {
148 console.error('[sri-client] Json parse is mislukt!', response);
149 }
150 }
151
152 return {
153 headers: headers,
154 body: body,
155 redirected: response.redirected
156 };
157 } catch(err) {
158 console.warn('[sri-client] Het response kon niet worden uitgelezen.', response);
159 return new SriClientError({
160 status: response.status,
161 body: null,
162 headers: headers,
163 originalResponse: response,
164 error: err
165 });
166 }
167 }
168
169 async handleError(httpRequest, response, options, stack) {
170 if (response.code === 'ENOTFOUND') {
171 return new SriClientError({
172 status: null,
173 body: null,
174 originalResponse: null,
175 headers: null,
176 error: response,
177 stack: stack
178 });
179 }
180
181 const resp = await this.readResponse(response);
182
183 return new SriClientError({
184 status: response.status || null,
185 body: resp.body,
186 originalResponse: response,
187 headers: resp.headers,
188 stack: stack
189 });
190 };
191
192};
193
194
195
196module.exports = function(configuration) {
197 return new NodeFetchClient(configuration);
198};
\No newline at end of file