Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.7 KB
Raw Blame
import { markdownTable } from 'markdown-table'
import Papa from 'papaparse'

type ResultRow = Record<string, unknown>

export function formatResults(
  results: readonly ResultRow[]
): Record<string, string | number | boolean | null | undefined>[] {
  return results.map((row) => {
    const formatted: Record<string, string | number | boolean> = {}
    for (const key of Object.keys(row)) {
      const value = row[key]
      formatted[key] =
        typeof value === 'object' ? JSON.stringify(value) : (value as string | number | boolean)
    }
    return formatted
  })
}

export function convertResultsToMarkdown(results: readonly ResultRow[]): string | undefined {
  const formatted = formatResults(results)
  if (formatted.length === 0) return undefined

  const columns = Object.keys(formatted[0])
  const escapeCell = (value: string) =>
    value
      .replace(/\\/g, '\\\\')
      .replace(/\|/g, '\\|')
      .replace(/\r\n|\r|\n/g, '<br>')
  const rows = formatted.map((row) => columns.map((col) => escapeCell(String(row[col] ?? ''))))
  const table = [columns.map(escapeCell), ...rows]
  return markdownTable(table)
}

export function convertResultsToJSON(results: readonly ResultRow[]): string | undefined {
  if (results.length === 0) return undefined
  return JSON.stringify(results, null, 2)
}

export function getResultsHeaders(results: readonly ResultRow[]): string[] | undefined {
  const firstRow = Array.from(results)[0]
  if (firstRow) return Object.keys(firstRow)
  return undefined
}

export function convertResultsToCSV(results: readonly ResultRow[]): string | undefined {
  if (results.length === 0) return undefined

  const headers = getResultsHeaders(results)
  const formatted = formatResults(results)

  return Papa.unparse(formatted, { columns: headers })
}