(
value: TOutput,
tableSchema: TTable,
customSerializer: Partial<
CustomSQLiteSerializer<TOutput, ExtractedTableColumns<TTable>>
> = {},
)
| 38 | * - Throws if a value cannot be converted to the required SQLite type. |
| 39 | */ |
| 40 | export function serializeForSQLite< |
| 41 | TOutput extends Record<string, unknown>, |
| 42 | // The keys should match |
| 43 | TTable extends Table<MapBaseColumnType<TOutput>> = Table< |
| 44 | MapBaseColumnType<TOutput> |
| 45 | >, |
| 46 | >( |
| 47 | value: TOutput, |
| 48 | tableSchema: TTable, |
| 49 | customSerializer: Partial< |
| 50 | CustomSQLiteSerializer<TOutput, ExtractedTableColumns<TTable>> |
| 51 | > = {}, |
| 52 | ): ExtractedTable<TTable> { |
| 53 | return Object.fromEntries( |
| 54 | // eslint-disable-next-line no-shadow |
| 55 | Object.entries(value).map(([key, value]) => { |
| 56 | // First get the output schema type |
| 57 | const outputType = |
| 58 | key == `id` |
| 59 | ? ColumnType.TEXT |
| 60 | : tableSchema.columns.find((column) => column.name == key)?.type |
| 61 | if (!outputType) { |
| 62 | throw new Error(`Could not find schema for ${key} column.`) |
| 63 | } |
| 64 | |
| 65 | if (value == null) { |
| 66 | return [key, value] |
| 67 | } |
| 68 | |
| 69 | const customTransform = customSerializer[key] |
| 70 | if (customTransform) { |
| 71 | return [key, customTransform(value as TOutput[string])] |
| 72 | } |
| 73 | |
| 74 | // Map to the output |
| 75 | switch (outputType) { |
| 76 | case ColumnType.TEXT: |
| 77 | if (typeof value == `string`) { |
| 78 | return [key, value] |
| 79 | } else if (value instanceof Date) { |
| 80 | return [key, value.toISOString()] |
| 81 | } else { |
| 82 | return [key, JSON.stringify(value)] |
| 83 | } |
| 84 | case ColumnType.INTEGER: |
| 85 | case ColumnType.REAL: |
| 86 | if (typeof value == `number`) { |
| 87 | return [key, value] |
| 88 | } else if (typeof value == `boolean`) { |
| 89 | return [key, value ? 1 : 0] |
| 90 | } else { |
| 91 | const numberValue = Number(value) |
| 92 | if (isNaN(numberValue)) { |
| 93 | throw new Error( |
| 94 | `Could not convert ${key}=${value} to a number for SQLite`, |
| 95 | ) |
| 96 | } |
| 97 | return [key, numberValue] |
no test coverage detected
searching dependent graphs…