File size: 897 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { inject } from 'vitest';

export interface SharedServerContext {
  readonly base: string;
  readonly token: string;
}

declare module 'vitest' {
  interface ProvidedContext {
    readonly sharedServer: SharedServerContext;
  }
}

export function sharedServer(): SharedServerContext {
  return inject('sharedServer');
}

export function sharedAuthHeaders(extra: Record<string, string> = {}): Record<string, string> {
  return { ...extra, authorization: `Bearer ${sharedServer().token}` };
}

interface SharedFetchOptions {
  readonly method?: string;
  readonly headers?: Record<string, string>;
  readonly body?: string;
  readonly signal?: AbortSignal;
}

export async function sharedAuthedFetch(path: string, init: SharedFetchOptions = {}): Promise<Response> {
  return fetch(`${sharedServer().base}${path}`, {
    ...init,
    headers: sharedAuthHeaders(init.headers),
  } as never);
}