|
1 | | -import request from 'request'; |
| 1 | +import fetch from 'node-fetch'; |
2 | 2 |
|
3 | | -export function put<T extends object>(url: string, payload: object): Promise<T> { |
4 | | - return new Promise<T>((resolve, reject): void => { |
5 | | - request({ |
6 | | - url: url, |
7 | | - method: 'PUT', |
8 | | - headers: {}, |
9 | | - body: payload, |
10 | | - json: true, |
11 | | - }) |
12 | | - .on('response', response => { |
13 | | - response.on('data', body => { |
14 | | - try { |
15 | | - const jsonObj = JSON.parse(body.toString('utf8')); |
16 | | - if (jsonObj as T) { |
17 | | - return resolve(jsonObj); |
18 | | - } else if (jsonObj.error !== undefined && typeof jsonObj.error === 'string') { |
19 | | - return reject(new Error(jsonObj.error)); |
20 | | - } else { |
21 | | - return reject( |
22 | | - new Error( |
23 | | - `Failed to read response. |
24 | | - Body: |
25 | | - ${body.toString('utf8')}`, |
26 | | - ), |
27 | | - ); |
28 | | - } |
29 | | - } catch (err) { |
30 | | - return reject(err); |
31 | | - } |
32 | | - }); |
33 | | - }) |
34 | | - .on('error', err => reject(err)); |
| 3 | +export function put(url: string, payload: object): Promise<unknown> { |
| 4 | + return fetch(url, { |
| 5 | + method: 'PUT', |
| 6 | + headers: { |
| 7 | + Accept: 'application/json', |
| 8 | + 'Content-Type': 'application/json', |
| 9 | + }, |
| 10 | + body: JSON.stringify(payload), |
| 11 | + }).then(async response => { |
| 12 | + const bodyText = await response.text(); |
| 13 | + try { |
| 14 | + return JSON.parse(bodyText); |
| 15 | + } catch (error) { |
| 16 | + if (error instanceof SyntaxError) { |
| 17 | + throw new Error(`Failed to parse response json.\nBody:\n\n${bodyText}`); |
| 18 | + } else { |
| 19 | + throw error; |
| 20 | + } |
| 21 | + } |
35 | 22 | }); |
36 | 23 | } |
0 commit comments