Jaime Ramírez
2020-06-11 523d18a86155840b6a89af8b7b9f8bb8b9ca2663
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
import Axios, { AxiosInstance } from "axios";
 
 
 
export abstract class RESTService {
 
    private readonly axiosInstance: AxiosInstance;
 
    constructor(
        baseURL: string,
        private readonly remoteServiceName: string,
        private readonly timeoutMs = 3000
    ) {
        this.axiosInstance = Axios.create({ baseURL });
    }
 
    protected async get<T>(url: string): Promise<T> {
        try {
            const r = await this.axiosInstance.get<T>(url, { timeout: this.timeoutMs });
            return r.data;
        } catch (e) {
            throw new RESTConnectionError(e, this.remoteServiceName, e.response?.status);
        }
    }
 
    protected async post<T, R>(url: string, body: T): Promise<R> {
        try {
            const r = await this.axiosInstance.post<R>(url, body, { timeout: this.timeoutMs });
            return r.data;
        } catch (e) {
            throw new RESTConnectionError(e, this.remoteServiceName, e.response?.status);
        }
    }
 
}
 
 
export class RESTConnectionError extends Error {
 
    public readonly statusCode: number = 500;
    public readonly description: string;
    public readonly remoteStatusCode: number;
 
    constructor(error: Error, serviceName: string, remoteStatusCode?: number) {
        super();
        this.message = `An error ocurred when calling the remote service "${serviceName}"`;
        this.description = (error && error.message) ? error.message : "No additional information";
        this.remoteStatusCode = remoteStatusCode || 500;
    }
 
}