All files / apps / api/src / server / system service.ts

100% Statements 11/11
100% Branches 8/8
100% Functions 4/4
100% Lines 10/10

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              15x                               15x 15x 15x   2x         30x   30x         5x 4x   4x    
import { PublicConfigSchema, type Health, type PublicConfig } from '@chattra/shared'
import { mainDb, searchDb } from '../../db/client'
import { pingDb } from './repository'
 
// Parsed, not trusted: a variable can be missing on a deployed Worker (set in the dashboard, or a
// new env block that forgot one), and the types only describe wrangler.jsonc.
export function getPublicConfig(env: Env): PublicConfig {
  return PublicConfigSchema.parse({
    environment: env.ENVIRONMENT,
    firebase: {
      projectId: env.FIREBASE_PROJECT_ID,
      apiKey: env.FIREBASE_API_KEY,
      authDomain: env.FIREBASE_AUTH_DOMAIN,
      messagingSenderId: env.FIREBASE_MESSAGING_SENDER_ID,
      appId: env.FIREBASE_APP_ID,
      vapidKey: env.FIREBASE_VAPID_KEY,
    },
    signIn: getSignInBroker(env),
  })
}
 
// Only dev and its previews set these; anywhere else the config has no `signIn` at all.
function getSignInBroker(env: Env): PublicConfig['signIn'] {
  const brokerUrl = readVar(env, 'SIGN_IN_BROKER_URL')
  const brokerReturnPattern = readVar(env, 'SIGN_IN_BROKER_RETURN_PATTERN')
  if (!brokerUrl && !brokerReturnPattern) return undefined
 
  return { brokerUrl, brokerReturnPattern }
}
 
// Not in the local config, so the generated Env type may not list them at all.
function readVar(env: Env, name: string): string | undefined {
  const value: unknown = Reflect.get(env, name)
 
  return typeof value === 'string' && value !== '' ? value : undefined
}
 
// Also fails on a bad variable, so the check after a deploy catches a misconfigured Worker.
export async function checkHealth(env: Env): Promise<Health> {
  getPublicConfig(env)
  await Promise.all([pingDb(mainDb(env)), pingDb(searchDb(env))])
 
  return { status: 'ok' }
}