edgedb-js icon indicating copy to clipboard operation
edgedb-js copied to clipboard

Type-aware query middleware

Open emrosenf opened this issue 1 year ago • 2 comments

Problem

Suppose you want to toggle query performance logging, toEdgeQL() debug logging, or a security assert before every query is run.

There is currently no pattern to do so in a terse, efficient manner.

The library doesn't provide middleware functionality, and it is non-trivial to write a runner function.

Runner Function

I had assumed that it would be easier to write a runner function than to update the edgeql-js library.

My hope was to have a simple function that I could call instead of query.run(client, args) that would be type-aware so that Typescript would know the return type.

Sikari helped me prototype a function but the types are not correct.

import { Executor } from "edgedb";

import { $infer } from "../../dbschema/edgeql-js";
import { QueryableWithParamsExpression } from "../../dbschema/edgeql-js/params";

const runQuery = async <T extends QueryableWithParamsExpression>(query: T, client: Executor, params?: Parameters<T["run"]>[1]) => {
  return query.run(client, params ?? {}) as Promise<$infer<T>>;
};

If we could figure out the Typescript signature, this function anyone to efficiently add functionality before/after a query is run.

emrosenf avatar Mar 08 '24 13:03 emrosenf

This is what I do https://github.com/SeedCompany/cord-api-v3/blob/24dce245ab4e2ab6a116b45bd68dff5f0d8eeb88/src/core/edgedb/edgedb.service.ts#L36-L87

CarsonF avatar Mar 09 '24 16:03 CarsonF

Thank you @CarsonF, your solution works perfectly. I'll leave this open for @scotttrinh to triage. It wouldn't be a bad idea to add this pattern to the docs

emrosenf avatar Mar 11 '24 18:03 emrosenf