2019-01-22 14:18:58 +01:00
|
|
|
import fetch, { BodyInit, RequestInit, Response } from "node-fetch"
|
2019-03-19 14:27:28 +01:00
|
|
|
import LoggerInstance from "./Logger"
|
2018-10-26 11:57:26 +02:00
|
|
|
|
2019-01-09 16:15:32 +01:00
|
|
|
/**
|
|
|
|
* Provides a common interface to web services.
|
|
|
|
*/
|
2018-11-19 12:16:11 +01:00
|
|
|
export default class WebServiceConnector {
|
2018-10-26 11:57:26 +02:00
|
|
|
|
2019-01-23 12:29:13 +01:00
|
|
|
public post(url: string, payload: BodyInit): Promise<Response> {
|
2018-11-01 12:47:48 +01:00
|
|
|
return this.fetch(url, {
|
2018-10-26 11:57:26 +02:00
|
|
|
method: "POST",
|
|
|
|
body: payload,
|
2018-11-16 10:03:16 +01:00
|
|
|
headers: {
|
|
|
|
"Content-type": "application/json",
|
|
|
|
},
|
2018-10-26 11:57:26 +02:00
|
|
|
})
|
|
|
|
}
|
2018-10-29 16:38:23 +01:00
|
|
|
|
2019-01-23 12:29:13 +01:00
|
|
|
public get(url: string): Promise<Response> {
|
2018-11-01 12:47:48 +01:00
|
|
|
return this.fetch(url, {
|
2018-10-29 16:38:23 +01:00
|
|
|
method: "GET",
|
2018-11-16 10:03:16 +01:00
|
|
|
headers: {
|
|
|
|
"Content-type": "application/json",
|
|
|
|
},
|
2018-10-29 16:38:23 +01:00
|
|
|
})
|
|
|
|
}
|
2018-11-01 12:47:48 +01:00
|
|
|
|
2019-01-23 12:29:13 +01:00
|
|
|
public put(url: string, payload: BodyInit): Promise<Response> {
|
2018-11-01 12:47:48 +01:00
|
|
|
return this.fetch(url, {
|
|
|
|
method: "PUT",
|
|
|
|
body: payload,
|
2018-11-16 10:03:16 +01:00
|
|
|
headers: {
|
|
|
|
"Content-type": "application/json",
|
|
|
|
},
|
2018-11-01 12:47:48 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-01-09 16:15:32 +01:00
|
|
|
private async fetch(url: string, opts: RequestInit): Promise<Response> {
|
2019-01-24 10:58:05 +01:00
|
|
|
const result = await fetch(url, opts)
|
2019-01-23 12:29:13 +01:00
|
|
|
if (!result.ok) {
|
2019-03-19 14:27:28 +01:00
|
|
|
LoggerInstance.error(`Error requesting [${opts.method}] ${url}`)
|
|
|
|
LoggerInstance.error(`Response message: \n${await result.text()}`)
|
2019-01-23 12:29:13 +01:00
|
|
|
throw result
|
|
|
|
}
|
|
|
|
return result
|
2018-11-01 12:47:48 +01:00
|
|
|
}
|
2018-10-26 11:57:26 +02:00
|
|
|
}
|