|
| 1 | +import { Metadata } from 'nice-grpc'; |
| 2 | +import { InternalApi } from '@/api/generated'; |
| 3 | +import { createClient } from '@/api/generated/client'; |
| 4 | +import { config } from '@/config'; |
| 5 | +import { grpcClient } from '@/grpc'; |
| 6 | +import type { UserTokens } from '@/types/juxt/tokens'; |
| 7 | + |
| 8 | +export class InternalApiError extends Error { |
| 9 | + status: number; |
| 10 | + response: any; |
| 11 | + |
| 12 | + constructor(res: Response, body: any) { |
| 13 | + super(`Interal API fetch call failed with status ${res.status}`); |
| 14 | + this.status = res.status; |
| 15 | + this.response = body; |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +export const customFetch: typeof globalThis.fetch = async (input, init) => { |
| 20 | + const req = new Request(input, init); |
| 21 | + const url = new URL(req.url); |
| 22 | + const metadata = Metadata({ |
| 23 | + 'X-API-Key': config.grpc.miiverse.apiKey |
| 24 | + }); |
| 25 | + const method = req.method.toUpperCase(); |
| 26 | + const grpcResponse = await grpcClient.sendPacket({ |
| 27 | + path: url.pathname + url.search, |
| 28 | + method, |
| 29 | + headers: JSON.stringify(Object.fromEntries(req.headers.entries())), |
| 30 | + payload: req.body ? await new Response(req.body).text() : undefined |
| 31 | + }, { |
| 32 | + metadata |
| 33 | + }); |
| 34 | + |
| 35 | + // Mask 404's as a succesfull `null` response |
| 36 | + if (grpcResponse.status === 404 && req.method === 'GET') { |
| 37 | + grpcResponse.status = 200; |
| 38 | + grpcResponse.payload = JSON.stringify(null); |
| 39 | + } |
| 40 | + |
| 41 | + const response = new Response(Buffer.from(grpcResponse.payload), { |
| 42 | + status: grpcResponse.status, |
| 43 | + headers: { |
| 44 | + 'content-type': 'application/json' |
| 45 | + } |
| 46 | + }); |
| 47 | + return response; |
| 48 | +}; |
| 49 | + |
| 50 | +export function createInternalApiClient(tokens: UserTokens): InternalApi { |
| 51 | + const client = createClient({ |
| 52 | + fetch: customFetch, |
| 53 | + baseUrl: 'https://example.com/api/v1', // Hostname is ignored by `customFetch` |
| 54 | + headers: { |
| 55 | + 'x-service-token': tokens.serviceToken, |
| 56 | + 'x-oauth-token': tokens.oauthToken |
| 57 | + }, |
| 58 | + throwOnError: true |
| 59 | + }); |
| 60 | + |
| 61 | + client.interceptors.error.use((err, response, _req, options) => { |
| 62 | + if (!options.throwOnError) { |
| 63 | + return err; |
| 64 | + } |
| 65 | + |
| 66 | + return new InternalApiError(response, err); |
| 67 | + }); |
| 68 | + |
| 69 | + return new InternalApi({ |
| 70 | + client |
| 71 | + }); |
| 72 | +} |
0 commit comments