From 54aad21d0c54f70312a131e713f1f9f33eb02317 Mon Sep 17 00:00:00 2001 From: Mehmet Date: Mon, 21 Nov 2022 13:13:32 +0100 Subject: [PATCH] add generic interface support for tableSchema function --- src/Schema/index.d.ts | 35 ++++++++++++++++++++++++++++++----- src/types.d.ts | 13 +++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/Schema/index.d.ts b/src/Schema/index.d.ts index 2bb45fc6f..5478dfa11 100644 --- a/src/Schema/index.d.ts +++ b/src/Schema/index.d.ts @@ -2,7 +2,7 @@ // NOTE: Only require files needed (critical path on web) import invariant from '../utils/common/invariant' -import type { $Exact, $RE } from '../types' +import type { $Exact, $RE, GetType, IsOptional, RequireKey } from '../types' import type Model from '../Model' @@ -10,18 +10,39 @@ export type TableName = string export type ColumnName = string export type ColumnType = 'string' | 'number' | 'boolean' -export type ColumnSchema = $RE<{ + +export type StandardColumn = $RE<{ name: ColumnName type: ColumnType isOptional?: boolean isIndexed?: boolean }> +export type MappedColumn = { + name: K + type: GetType + isOptional?: IsOptional + isIndexed?: boolean +} + +type MakeMappedColumn< + T extends object, + U = { + [K in keyof T]: IsOptional extends true + ? RequireKey, 'isOptional'> + : MappedColumn + }, +> = U[keyof U] + +export type ColumnSchema = T extends undefined + ? StandardColumn + : MakeMappedColumn + export type ColumnMap = { [name: ColumnName]: ColumnSchema } -export type TableSchemaSpec = $Exact<{ +export type TableSchemaSpec = $Exact<{ name: TableName - columns: ColumnSchema[] + columns: ColumnSchema[] unsafeSql?: (string) => string }> @@ -59,4 +80,8 @@ export function appSchema({ version, tables: tableList, unsafeSql }: AppSchemaSp export function validateColumnSchema(column: ColumnSchema): void -export function tableSchema({ name, columns: columnArray, unsafeSql }: TableSchemaSpec): TableSchema +export function tableSchema({ + name, + columns: columnArray, + unsafeSql, +}: TableSchemaSpec): TableSchema diff --git a/src/types.d.ts b/src/types.d.ts index 4cba60438..4940e855b 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -16,3 +16,16 @@ export type Array = Type[] export type $Call = any export type $ReadOnlyArray = T[] + +export type RequireKey = Omit & Required> + +export type IsOptional = Exclude extends never ? false : true + +// Assumes that arrays and objects will be stored as json strings +export type GetType = T extends string + ? 'string' + : T extends number + ? 'number' + : T extends boolean + ? 'boolean' + : 'string'