-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathservice.ts
More file actions
58 lines (51 loc) · 1.77 KB
/
service.ts
File metadata and controls
58 lines (51 loc) · 1.77 KB
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
52
53
54
55
56
57
58
import { defaults, FetchOptions } from "make-fetch-happen";
import { ConfigService } from "src/config/service";
import { LoggerService } from "src/logger/service";
import { Service } from "typedi";
import { FetchConfig } from "./types";
@Service()
export class FetchService {
constructor(
private readonly configService: ConfigService,
private readonly loggerService: LoggerService,
) {
const { FETCH_CACHE_PATH } = this.configService.env();
this.makeFetchHappenInstance = defaults({
cachePath: FETCH_CACHE_PATH,
});
}
public post = async <T>(
url: string,
{ headers = {}, body }: FetchConfig = {},
): Promise<Awaited<T>> => {
const response = await this.fetch<T>(url, {
headers: {
"Content-Type": "application/json",
...headers,
},
method: "POST",
body: body ? JSON.stringify(body) : undefined,
});
return response;
};
public get = async <T>(
url: string,
{ params = {}, headers = {} }: FetchConfig = {},
): Promise<Awaited<T>> => {
const _url = new URL(url);
Object.keys(params).forEach((key) => _url.searchParams.append(key, String(params[key])));
const response = await this.fetch<T>(_url.toString(), { headers, method: "GET" });
return response;
};
private makeFetchHappenInstance;
private async fetch<T>(url: string, options: FetchOptions) {
this.loggerService.logger.info("Fetching URL", "url", url);
const response = await this.makeFetchHappenInstance(url, options);
if (!response.ok) {
this.loggerService.logger.error("Failed to fetch URL", "url", url, "status", response.status);
throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
}
const jsonResponse = (await response.json()) as T;
return jsonResponse;
}
}