-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest.ts
More file actions
148 lines (136 loc) · 3.79 KB
/
request.ts
File metadata and controls
148 lines (136 loc) · 3.79 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import type { LRUCache } from 'lru-cache';
import type {
Params,
AnyObject,
AnyResource,
Resource,
} from 'pinejs-client-core';
import {
PinejsClientCore,
StatusError as CoreStatusError,
} from 'pinejs-client-core';
import request from 'request';
const requestAsync = (
opts:
| (request.UriOptions & request.CoreOptions)
| (request.UrlOptions & request.CoreOptions),
): Promise<request.Response> =>
new Promise((resolve, reject) => {
request(opts, (err: Error, response) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
const headersOfInterest = ['retry-after'] as const;
export class StatusError extends CoreStatusError {
public headers: Pick<
request.Response['headers'],
(typeof headersOfInterest)[number]
> = {};
constructor(
message: string,
statusCode: number,
headers: request.Response['headers'],
) {
super(message, statusCode);
if (headers != null) {
for (const header of headersOfInterest) {
this.headers[header] = headers[header];
}
}
}
}
interface CachedResponse {
etag: string;
body: any;
}
export interface BackendParams {
cache?: LRUCache.Options<string, CachedResponse, unknown>;
}
const validParams: Array<keyof BackendParams> = ['cache'];
export class PinejsClientRequest<
Model extends {
[key in keyof Model]: Resource;
} = {
[key in string]: AnyResource;
},
> extends PinejsClientCore<Model> {
public backendParams: BackendParams = {};
private cache?: LRUCache<string, CachedResponse>;
constructor(params: Params, backendParams?: BackendParams) {
if (params?.retry && params.retry.getRetryAfterHeader == null) {
params = {
...params,
retry: {
...params.retry,
getRetryAfterHeader(err) {
if (err instanceof StatusError) {
return err.headers['retry-after'];
}
},
},
};
}
super(params);
if (backendParams != null && typeof backendParams === 'object') {
for (const validParam of validParams) {
if (Object.prototype.hasOwnProperty.call(backendParams, validParam)) {
this.backendParams[validParam] = backendParams[validParam];
}
}
}
if (this.backendParams.cache != null) {
const { LRUCache: LRU } =
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('lru-cache') as typeof import('lru-cache');
this.cache = new LRU(this.backendParams.cache);
}
}
public async _request(
params: {
method: string;
url: string;
body?: AnyObject;
} & AnyObject,
): Promise<NonNullable<unknown>> {
// We default to gzip on for efficiency.
params.gzip ??= true;
// We default to a 59s timeout, rather than hanging indefinitely.
params.timeout ??= 59000;
// We default to enforcing valid ssl certificates, after all there's a reason we're using them!
params.strictSSL ??= true;
// The request is always a json request.
params.json = true;
if (this.cache != null && params.method === 'GET') {
// If the cache is enabled and we are doing a GET then try to use a cached
// version, and store whatever the (successful) result is.
let cached = this.cache.get(params.url);
if (cached != null) {
params.headers ??= {};
params.headers['If-None-Match'] = cached.etag;
}
const { statusCode, body, headers } = await requestAsync(params);
if (statusCode === 304 && cached != null) {
// The currently cached version is still valid
} else if (200 <= statusCode && statusCode < 300) {
cached = {
etag: headers.etag!,
body,
};
} else {
throw new StatusError(body, statusCode, headers);
}
this.cache.set(params.url, cached);
return structuredClone(cached.body);
} else {
const { statusCode, body, headers } = await requestAsync(params);
if (200 <= statusCode && statusCode < 300) {
return body;
}
throw new StatusError(body, statusCode, headers);
}
}
}