From aeb2ce9f1bdca64d0a0d12812c777b0e76df24ae Mon Sep 17 00:00:00 2001 From: Ryuya Date: Wed, 14 Jun 2023 12:28:19 +0900 Subject: [PATCH] fix: return SelectQueryError when referencing missing columns (#436) * Returns 'never' if a column that does not exist in the schema * fix: return SelectQueryError when referencing missing columns --------- Co-authored-by: Bobbie Soedirgo --- src/select-query-parser.ts | 37 ++++++++++++++++++++++--------------- test/index.test-d.ts | 9 ++++++++- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/select-query-parser.ts b/src/select-query-parser.ts index 2179d280..f7580e83 100644 --- a/src/select-query-parser.ts +++ b/src/select-query-parser.ts @@ -55,6 +55,7 @@ type Json = string | number | boolean | null | { [key: string]: Json } | Json[] */ type ParserError = { error: true } & Message type GenericStringError = ParserError<'Received a generic string'> +export type SelectQueryError = { error: true } & Message /** * Trims whitespace from the left of the input. @@ -136,7 +137,9 @@ type ConstructFieldDefinition< : never } : Field extends { name: string; original: string } - ? { [K in Field['name']]: Row[Field['original']] } + ? Field['original'] extends keyof Row + ? { [K in Field['name']]: Row[Field['original']] } + : SelectQueryError<`Referencing missing column \`${Field['original']}\``> : Field extends { name: string; type: infer T } ? { [K in Field['name']]: T } : Record @@ -415,21 +418,25 @@ type GetResultHelper< Fields extends unknown[], Acc > = Fields extends [infer R] - ? GetResultHelper< - Schema, - Row, - Relationships, - [], - ConstructFieldDefinition & Acc - > + ? ConstructFieldDefinition extends SelectQueryError + ? SelectQueryError + : GetResultHelper< + Schema, + Row, + Relationships, + [], + ConstructFieldDefinition & Acc + > : Fields extends [infer R, ...infer Rest] - ? GetResultHelper< - Schema, - Row, - Relationships, - Rest, - ConstructFieldDefinition & Acc - > + ? ConstructFieldDefinition extends SelectQueryError + ? SelectQueryError + : GetResultHelper< + Schema, + Row, + Relationships, + Rest, + ConstructFieldDefinition & Acc + > : Prettify /** diff --git a/test/index.test-d.ts b/test/index.test-d.ts index 2bf27671..d2407856 100644 --- a/test/index.test-d.ts +++ b/test/index.test-d.ts @@ -1,5 +1,6 @@ import { expectError, expectType } from 'tsd' -import { PostgrestClient } from '../src/index' +import { PostgrestClient, PostgrestSingleResponse } from '../src/index' +import { SelectQueryError } from '../src/select-query-parser' import { Database, Json } from './types' const REST_URL = 'http://localhost:3000' @@ -81,3 +82,9 @@ const postgrest = new PostgrestClient(REST_URL) } expectType(user.messages) } + +// referencing missing column +{ + const res = await postgrest.from('users').select('username, dat') + expectType[]>>(res) +}