SurrealX icon indicating copy to clipboard operation
SurrealX copied to clipboard

Typesafe `queryX`

Open SorenHolstHansen opened this issue 2 years ago • 0 comments

It would be amazing to make a typesafe version of query.

Don't know if SurrealDB has some build in introspection for queries, otherwise I guess it would require parsing some SurrealQL AST.

However I guess the setup would be something like this:

The user has defined some queries throughout their code

await db.queryX("SELECT * FROM user:123;");
await db.queryX('SELECT title FROM post WHERE status INSIDE $status', {status: ["live", "draft"]});

And then something like the following would be generated

type Queries = {
  'SELECT * FROM user:123': {
    output: User,
    input: undefined
  },
  'SELECT title FROM post WHERE status INSIDE $status': {
    output: {title: string}[],
    input: {status: Status[]}
  }
}

class SurrealX {
  ...
  queryX<T extends string | keyof Queries>(thing: T, vars: T extends keyof Queries ? Queries[T].input : Record<string, unknown> | undefined): T extends keyof Queries ? Queries[T].output : string {
    return super.query(thing, vars) as any
  }
}

SorenHolstHansen avatar Feb 01 '23 21:02 SorenHolstHansen