All files / src/utils createErrorResponse.ts

100% Statements 23/23
100% Branches 6/6
100% Functions 6/6
100% Lines 22/22

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                                      17x 17x   1x         12x 12x 12x 72x   12x       12x       12x 12x 12x     12x 12x 12x       12x           12x 12x         12x     12x 5x 5x    
export interface FPJSResponse {
  v: '2'
  notifications?: Notification[]
  requestId: string
  error?: ErrorData
  products: {}
}
 
export interface Notification {
  level: 'info' | 'warning' | 'error'
  message: string
}
 
export interface ErrorData {
  code?: 'IntegrationFailed'
  message: string
}
 
function errorToString(error: string | Error | unknown): string {
  try {
    return typeof error === 'string' ? error : error instanceof Error ? error.message : String(error)
  } catch (e) {
    return 'unknown'
  }
}
 
function generateRandomString(length: number): string {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  return result
}
 
function generateRequestUniqueId(): string {
  return generateRandomString(6)
}
 
function generateRequestId(): string {
  const uniqueId = generateRequestUniqueId()
  const now = new Date().getTime()
  return `${now}.${uniqueId}`
}
 
export function createErrorResponseForIngress(request: Request, error: string | Error | unknown): Response {
  const reason = errorToString(error)
  const errorBody: ErrorData = {
    code: 'IntegrationFailed',
    message: `An error occurred with Cloudflare worker. Reason: ${reason}`,
  }
  const responseBody: FPJSResponse = {
    v: '2',
    error: errorBody,
    requestId: generateRequestId(),
    products: {},
  }
  const requestOrigin = request.headers.get('origin') || ''
  const responseHeaders: HeadersInit = {
    'Access-Control-Allow-Origin': requestOrigin,
    'Access-Control-Allow-Credentials': 'true',
    'content-type': 'application/json',
  }
  return new Response(JSON.stringify(responseBody), { status: 500, headers: responseHeaders })
}
 
export function createFallbackErrorResponse(error: string | Error | unknown): Response {
  const responseBody = { error: errorToString(error) }
  return new Response(JSON.stringify(responseBody), { status: 500, headers: { 'content-type': 'application/json' } })
}