-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackendService.ts
More file actions
259 lines (223 loc) · 8.89 KB
/
Copy pathbackendService.ts
File metadata and controls
259 lines (223 loc) · 8.89 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { z, type ZodSchema } from 'zod';
import { UserFacingError } from '../components/ErrorReportInstruction.tsx';
import { apiKeyMetadataSchema, generatedApiKeySchema } from '../types/ApiKey.ts';
import {
collectionSchema,
collectionSummarySchema,
type CollectionRequest,
type CollectionUpdate,
} from '../types/Collection.ts';
import { type ProblemDetail, problemDetailSchema } from '../types/ProblemDetail.ts';
import { publicUserSchema } from '../types/PublicUser.ts';
import {
type SubscriptionPutRequest,
type SubscriptionRequest,
subscriptionResponseSchema,
triggerEvaluationResponseSchema,
} from '../types/Subscription.ts';
const X_REQUEST_ID_HEADER = 'x-request-id';
type EndpointParameters<Response> = {
url: string;
requestParams?: Record<string, string | boolean | undefined>;
schema: ZodSchema<Response>;
};
type EndpointParametersWithBody<Request, Response> = EndpointParameters<Response> & { data: Request };
class ApiService {
private readonly axiosInstance: AxiosInstance;
constructor(baseURL: string) {
this.axiosInstance = axios.create({ baseURL });
}
public async get<Response>({ url, requestParams, schema }: EndpointParameters<Response>): Promise<Response> {
return this.handleRequest({ url, method: 'get', params: requestParams }, schema);
}
public async post<Request, Response>({
url,
data,
requestParams,
schema,
}: EndpointParametersWithBody<Request, Response>): Promise<Response> {
return this.handleRequest({ url, method: 'post', params: requestParams, data }, schema);
}
public async put<Request, Response>({
url,
data,
requestParams,
schema,
}: EndpointParametersWithBody<Request, Response>): Promise<Response> {
return this.handleRequest({ url, method: 'put', params: requestParams, data }, schema);
}
public async delete<Response>({ url, requestParams, schema }: EndpointParameters<Response>): Promise<Response> {
return this.handleRequest({ url, method: 'delete', params: requestParams }, schema);
}
private async handleRequest<Request, Response>(request: AxiosRequestConfig<Request>, schema: ZodSchema<Response>) {
try {
const response = await this.axiosInstance.request(request);
return schema.parse(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response) {
this.handleErrors(error.response);
}
if (error.code === axiosNotFoundError) {
throw new BackendNotAvailable(error.config?.baseURL ?? '');
}
}
throw error;
}
}
private handleErrors(response: AxiosResponse) {
if (response.status >= 300 || response.status < 200) {
const backendError = problemDetailSchema.safeParse(response.data);
if (backendError.success) {
throw new BackendError(
backendError.data.detail ?? '(no detail)',
response.status,
backendError.data,
response.config.url ?? '',
response.headers[X_REQUEST_ID_HEADER],
);
}
throw new UnknownBackendError(response.statusText, response.status, response.config.url ?? '');
}
}
}
const axiosNotFoundError = 'ENOTFOUND';
export class BackendError extends UserFacingError {
constructor(
message: string,
public readonly status: number,
public readonly problemDetail: ProblemDetail,
public readonly requestedData: string,
public readonly requestId: string | undefined,
) {
super(message);
this.name = 'BackendError';
}
}
export class UnknownBackendError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly requestedData: string,
) {
super(message);
this.name = 'UnknownBackendError';
}
}
export class BackendNotAvailable extends UserFacingError {
constructor(url: string) {
super(`Backend not available under ${url}`);
this.name = 'BackendNotAvailable';
}
}
export class BackendService extends ApiService {
public async getSubscriptions() {
const url = `/subscriptions`;
return this.get({ url, schema: z.array(subscriptionResponseSchema) });
}
public async getEvaluateTrigger({ subscriptionId }: { subscriptionId: string }) {
const url = `/subscriptions/evaluateTrigger`;
return this.get({
url,
requestParams: { id: subscriptionId },
schema: triggerEvaluationResponseSchema,
});
}
public async postSubscription({ subscription }: { subscription: SubscriptionRequest }) {
const url = `/subscriptions`;
return this.post({ url, data: subscription, schema: subscriptionResponseSchema });
}
public async putSubscription({
subscription,
subscriptionId,
}: {
subscription: SubscriptionPutRequest;
subscriptionId: string;
}) {
const url = `/subscriptions/${subscriptionId}`;
return this.put({
url,
data: subscription,
schema: subscriptionResponseSchema,
});
}
public async deleteSubscription({ subscriptionId }: { subscriptionId: string }) {
const url = `/subscriptions/${subscriptionId}`;
return this.delete({
url,
schema: z.literal('').refine((_input): _input is never => true),
});
}
public async getMe() {
return this.get({ url: '/users/me', schema: publicUserSchema });
}
public async getUser({ id }: { id: number }) {
return this.get({ url: `/users/${id}`, schema: publicUserSchema });
}
public async getCollectionSummaries({
organism,
userId,
excludeSystemCollections,
}: { organism?: string; userId?: number; excludeSystemCollections?: boolean } = {}) {
const requestParams: Record<string, string> = {};
if (organism !== undefined) requestParams.organism = organism;
if (userId !== undefined) requestParams.userId = String(userId);
if (excludeSystemCollections !== undefined)
requestParams.excludeSystemCollections = String(excludeSystemCollections);
return this.get({
url: '/collections',
requestParams: Object.keys(requestParams).length > 0 ? requestParams : undefined,
schema: z.array(collectionSummarySchema),
});
}
public async getCollections({ organism }: { organism?: string } = {}) {
const requestParams: Record<string, string> = { includeVariants: 'true' };
if (organism !== undefined) requestParams.organism = organism;
return this.get({ url: '/collections', requestParams, schema: z.array(collectionSchema) });
}
public async getCollection({ id }: { id: string }) {
return this.get({ url: `/collections/${id}`, schema: collectionSchema });
}
public async postCollection({ collection }: { collection: CollectionRequest }) {
return this.post({
url: '/collections',
data: collection,
schema: collectionSchema,
});
}
public async putCollection({ id, collection }: { id: string; collection: CollectionUpdate }) {
return this.put({
url: `/collections/${id}`,
data: collection,
schema: collectionSchema,
});
}
public async deleteCollection({ id }: { id: string }) {
return this.delete({
url: `/collections/${id}`,
schema: z.literal('').refine((_input): _input is never => true),
});
}
/** Returns metadata for the current API key, or throws a 404 BackendError if none exists. */
public async getApiKey() {
return this.get({ url: '/api-keys', schema: apiKeyMetadataSchema });
}
/** Generates a new API key and returns it. The raw key is shown once and cannot be retrieved again. Throws 409 if a key already exists. */
public async generateApiKey() {
return this.post({ url: '/api-keys', data: undefined, schema: generatedApiKeySchema });
}
/** Revokes the current API key. Throws 404 if no key exists. */
public async revokeApiKey() {
return this.delete({
url: '/api-keys',
schema: z.literal('').refine((_input): _input is never => true),
});
}
}
let backendServiceForClientside: BackendService | null = null;
export function getBackendServiceForClientside(): BackendService {
backendServiceForClientside =
backendServiceForClientside ?? new BackendService(`${new URL(window.location.href).origin}/api`);
return backendServiceForClientside;
}