Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

schema.ts

100 lines2.6 KB

1import { ColumnType } from '@powersync/common'
2import type { Table } from '@powersync/common'
3import type { StandardSchemaV1 } from '@standard-schema/spec'
4import type { ExtractedTable } from './helpers'
5​
6/**
7 * Converts a PowerSync Table instance to a StandardSchemaV1 schema.
8 * Creates a schema that validates the structure and types of table records
9 * according to the PowerSync table definition.
10 *
11 * @template TTable - The PowerSync schema-typed Table definition
12 * @param table - The PowerSync Table instance to convert
13 * @returns A StandardSchemaV1-compatible schema with proper type validation
14 *
15 * @example
16 * ```typescript
17 * const usersTable = new Table({
18 * name: column.text,
19 * age: column.integer
20 * })
21 * ```
22 */
23export function convertTableToSchema<TTable extends Table>(
24 table: TTable,
25): StandardSchemaV1<ExtractedTable<TTable>> {
26 type TExtracted = ExtractedTable<TTable>
27 // Create validate function that checks types according to column definitions
28 const validate = (
29 value: unknown,
30 ):
31 | StandardSchemaV1.SuccessResult<TExtracted>
32 | StandardSchemaV1.FailureResult => {
33 if (typeof value != `object` || value == null) {
34 return {
35 issues: [
36 {
37 message: `Value must be an object`,
38 },
39 ],
40 }
41 }
42​
43 const issues: Array<StandardSchemaV1.Issue> = []
44​
45 // Check id field
46 if (!(`id` in value) || typeof (value as any).id != `string`) {
47 issues.push({
48 message: `id field must be a string`,
49 path: [`id`],
50 })
51 }
52​
53 // Check each column
54 for (const column of table.columns) {
55 const val = (value as TExtracted)[column.name as keyof TExtracted]
56​
57 if (val == null) {
58 continue
59 }
60​
61 switch (column.type) {
62 case ColumnType.TEXT:
63 if (typeof val != `string`) {
64 issues.push({
65 message: `${column.name} must be a string or null`,
66 path: [column.name],
67 })
68 }
69 break
70 case ColumnType.INTEGER:
71 case ColumnType.REAL:
72 if (typeof val != `number`) {
73 issues.push({
74 message: `${column.name} must be a number or null`,
75 path: [column.name],
76 })
77 }
78 break
79 }
80 }
81​
82 if (issues.length > 0) {
83 return { issues }
84 }
85​
86 return { value: { ...value } as TExtracted }
87 }
88​
89 return {
90 '~standard': {
91 version: 1,
92 vendor: `powersync`,
93 validate,
94 types: {
95 input: {} as TExtracted,
96 output: {} as TExtracted,
97 },
98 },
99 }