-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhooks.server.ts
73 lines (62 loc) · 1.64 KB
/
hooks.server.ts
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
import type { Handle } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
import { client } from '$lib/client/services.gen';
import { getServerConfig } from '$lib/serverConfig';
const configureClientMiddleware: Handle = async ({ event, resolve }) => {
const config = await getServerConfig();
if (config) {
event.locals.backendUrl = config.backendUrl;
event.locals.apiKey = config.apiKey;
client.setConfig({
baseUrl: config.backendUrl,
headers: {
'x-api-key': config.apiKey
}
});
}
if (
!event.url.pathname.startsWith('/connect') &&
!event.url.pathname.startsWith('/api/configure-client') &&
event.request.method === 'GET'
) {
if (!event.locals.backendUrl || !event.locals.apiKey) {
throw redirect(307, '/connect');
}
let hasConnection;
try {
await fetch(event.locals.backendUrl + '/api/v1/health')
.then(() => {
hasConnection = true;
})
.catch(() => {
hasConnection = false;
});
} catch {
hasConnection = false;
}
if (!hasConnection) {
throw redirect(307, '/connect');
}
}
return resolve(event);
};
const errorInterceptor: Handle = async ({ event, resolve }) => {
const response = await resolve(event);
client.interceptors.error.use((error: unknown) => {
if (
error &&
typeof error === 'object' &&
'detail' in error &&
typeof error.detail === 'string'
) {
if (error.detail === 'Missing or invalid API key') {
throw redirect(307, '/connect');
}
return error.detail;
}
return undefined;
});
return response;
};
export const handle = sequence(configureClientMiddleware, errorInterceptor);