All files / apps / web/src / lib api.ts

100% Statements 39/39
100% Branches 28/28
100% Functions 12/12
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      29x 29x 29x 29x 29x             24x             28x         52x                                                     21x 21x 4x   21x   21x       23x 23x       23x     23x 18x   21x           3x     20x   3x   3x               17x                                 23x   23x     24x       5x   4x               24x                   14x         12x    
import {
  apiPath,
  ApiErrorSchema,
  AUTH_ERROR_CODE,
  ERROR_CODE,
  HTTP_STATUS,
  REQUEST_ID_HEADER,
  type Endpoint,
  type EndpointInput,
  type EndpointResponse,
} from '@chattra/shared'
 
// `status` 0 means the request got no answer (offline, DNS, blocked).
export class ApiRequestError extends Error {
  readonly status: number
  readonly code: string
  readonly requestId: string | null
 
  constructor(status: number, code: string, requestId: string | null, options?: ErrorOptions) {
    super(`${code} (${status})`, options)
    this.name = 'ApiRequestError'
    this.status = status
    this.code = code
    this.requestId = requestId
  }
}
 
/** The Firebase ID token for the next request, or null while nobody is signed in. */
export type TokenGetter = () => Promise<string | null>
 
let getToken: TokenGetter = () => Promise.resolve(null)
 
/**
 * Set by the auth feature once Firebase is ready, so this file never loads the Firebase SDK.
 * Firebase refreshes the short-lived token itself (design 4.2).
 */
export function setTokenGetter(getter: TokenGetter): void {
  getToken = getter
}
 
/** Test only: back to sending no token. */
export function resetTokenGetter(): void {
  getToken = () => Promise.resolve(null)
}
 
// A part is required when the contract has it, so a call cannot leave out a body or a path param.
type Needs<E extends Endpoint, K extends 'params' | 'body'> = E extends { [P in K]: object }
  ? { [P in K]: EndpointInput<E, K> }
  : unknown
 
// A query is always optional: the server defaults what the caller leaves out.
type Query<E extends Endpoint> = E extends { query: object }
  ? { query?: EndpointInput<E, 'query'> }
  : unknown
 
/** What a call to endpoint `E` takes: only the parts its contract declares. */
export type ApiCallOptions<E extends Endpoint> = { headers?: HeadersInit } & Needs<E, 'params'> &
  Needs<E, 'body'> &
  Query<E>
 
// What the options and the answer are at run time, once the contract's types are erased.
interface RuntimeOptions {
  headers?: HeadersInit
  params?: Record<string, string>
  query?: Record<string, string | number | boolean | undefined>
  body?: unknown
}
 
function buildUrl(endpoint: Endpoint, { params, query = {} }: RuntimeOptions): string {
  const search = new URLSearchParams()
  for (const [name, value] of Object.entries(query)) {
    if (value !== undefined) search.set(name, String(value))
  }
  const queryString = search.size > 0 ? `?${search}` : ''
 
  return `${apiPath(endpoint.path, params)}${queryString}`
}
 
async function request(endpoint: Endpoint, options: RuntimeOptions): Promise<unknown> {
  const headers = new Headers(options.headers)
  if (options.body !== undefined) headers.set('content-type', 'application/json')
 
  let res: Response
 
  try {
    // Bearer on every request (design 5.1), never a cookie; a caller that sets the header itself
    // (session bootstrap) keeps its own.
    const token = headers.has('authorization') ? null : await getToken()
    if (token) headers.set('authorization', `Bearer ${token}`)
 
    res = await fetch(buildUrl(endpoint, options), {
      method: endpoint.method,
      headers,
      body: options.body === undefined ? undefined : JSON.stringify(options.body),
    })
  } catch (cause) {
    throw new ApiRequestError(0, 'network', null, { cause })
  }
 
  if (!res.ok) {
    // The Worker answers { code, message, requestId } (design G19); anything else came from in front of it.
    const body = ApiErrorSchema.safeParse(await res.json().catch(() => null))
 
    throw new ApiRequestError(
      res.status,
      body.success ? body.data.code : `http_${res.status}`,
      body.success ? body.data.requestId : res.headers.get(REQUEST_ID_HEADER),
    )
  }
 
  // No response schema: the endpoint answers 204, so there is no body to read.
  return endpoint.response?.parse(await res.json())
}
 
// Options may be left out only when the contract needs no params and no body.
type CallArgs<E extends Endpoint> =
  Record<never, never> extends ApiCallOptions<E>
    ? [options?: ApiCallOptions<E>]
    : [options: ApiCallOptions<E>]
 
// The one place the SPA calls the API: the contract in `@chattra/shared` gives method, path and shapes.
export async function apiFetch<E extends Endpoint>(
  endpoint: E,
  ...args: CallArgs<E>
): Promise<EndpointResponse<E>> {
  // SAFETY: TypeScript cannot narrow ApiCallOptions<E> / EndpointResponse<E> inside the generic body;
  // the types guarantee the options hold what the contract declares, and the response is parsed by
  // the contract's own schema.
  const options = (args[0] ?? {}) as RuntimeOptions
 
  return (await request(endpoint, options)) as EndpointResponse<E>
}
 
const MAX_RETRIES = 3
 
// For TanStack Query's `retry`: only what a retry can fix (no answer, or a 5xx), never a 4xx or a bad body.
export function shouldRetry(failureCount: number, error: unknown): boolean {
  if (failureCount >= MAX_RETRIES) return false
 
  return (
    error instanceof ApiRequestError &&
    (error.status === 0 || error.status >= HTTP_STATUS.internalServerError)
  )
}
 
// Refusals that mean this browser is no longer signed in to Chattra: no or a bad token, an ended
// session, or a person Chattra does not know or has deactivated (design 4.2).
const SIGNED_OUT_CODES = new Set<string>([
  ERROR_CODE.unauthenticated,
  AUTH_ERROR_CODE.invalidToken,
  AUTH_ERROR_CODE.sessionEnded,
  AUTH_ERROR_CODE.notRegistered,
  AUTH_ERROR_CODE.accountDeactivated,
])
 
/** True for an error code that means the person must sign in again (also what ?reason= holds). */
export function isSignedOutCode(code: string): boolean {
  return SIGNED_OUT_CODES.has(code)
}
 
/** True when the API refused the token or the session, so the person must sign in again. */
export function isSignedOutError(error: unknown): error is ApiRequestError {
  return error instanceof ApiRequestError && isSignedOutCode(error.code)
}