Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: query parser: handle empty embedded resources () #499

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/select-query-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ type ConstructFieldDefinition<
Field['children'],
unknown
>
: Field extends { children: [] }
? {}
: Field extends { name: string; original: string; hint: string; children: unknown[] }
? {
[_ in Field['name']]: GetResultHelper<
Expand Down Expand Up @@ -460,19 +462,22 @@ type ParseJsonAccessor<Input extends string> = Input extends `->${infer Remainde

/**
* Parses an embedded resource, which is an opening `(`, followed by a sequence of
* nodes, separated by `,`, then a closing `)`.
* 0 or more nodes separated by `,`, then a closing `)`.
*
* Returns a tuple of ["Parsed fields", "Remainder of text"], an error,
* or the original string input indicating that no opening `(` was found.
*/
type ParseEmbeddedResource<Input extends string> = Input extends `(${infer Remainder}`
? ParseNodes<EatWhitespace<Remainder>> extends [infer Fields, `${infer Remainder}`]
? EatWhitespace<Remainder> extends `)${infer Remainder}`
? Fields extends []
? ParserError<'Expected fields after `(`'>
: [Fields, EatWhitespace<Remainder>]
? [Fields, EatWhitespace<Remainder>]
: ParserError<`Expected ")"`>
: ParseNodes<EatWhitespace<Remainder>>
: // If no nodes were detected, check for `)` for empty embedded resources `()`.
ParseNodes<EatWhitespace<Remainder>> extends ParserError<string>
? EatWhitespace<Remainder> extends `)${infer Remainder}`
? [[], EatWhitespace<Remainder>]
: ParseNodes<EatWhitespace<Remainder>>
: ParserError<'Expected embedded resource fields or `)`'>
: Input

/**
Expand Down
9 changes: 9 additions & 0 deletions test/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ const postgrest = new PostgrestClient<Database>(REST_URL)
)
}

// embedded resource with no fields
{
const { data, error } = await postgrest.from('messages').select('message, users()').single()
if (error) {
throw new Error(error.message)
}
expectType<{ message: string | null }>(data)
}

// json accessor in select query
{
const { data, error } = await postgrest
Expand Down
Loading