uql-orm 0.112.0 → 0.113.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/browser/http/httpTransport.d.ts +29 -0
- package/dist/browser/http/httpTransport.js +59 -0
- package/dist/browser/http/index.d.ts +1 -2
- package/dist/browser/http/index.js +1 -2
- package/dist/browser/index.d.ts +1 -0
- package/dist/browser/querier/clientQuerier.d.ts +7 -0
- package/dist/browser/querier/clientQuerier.js +43 -0
- package/dist/browser/querier/index.d.ts +2 -1
- package/dist/browser/querier/index.js +2 -1
- package/dist/browser/querier/queryOptions.d.ts +23 -0
- package/dist/browser/querier/queryOptions.js +35 -0
- package/dist/browser/type/clientQuerier.d.ts +10 -11
- package/dist/browser/type/index.d.ts +1 -1
- package/dist/browser/type/index.js +1 -1
- package/dist/browser/type/transport.d.ts +13 -0
- package/dist/dialect/abstractDialect.d.ts +2 -2
- package/dist/dialect/abstractSqlDialect.js +3 -3
- package/dist/dialect/jsonSql.js +2 -3
- package/dist/dialect/operators.js +4 -5
- package/dist/express/index.d.ts +1 -1
- package/dist/express/index.js +1 -1
- package/dist/express/router.d.ts +8 -0
- package/dist/express/router.js +50 -0
- package/dist/http/api.d.ts +36 -0
- package/dist/http/api.js +136 -0
- package/dist/http/apiCall.d.ts +59 -0
- package/dist/http/apiCall.js +52 -0
- package/dist/http/errors.d.ts +20 -0
- package/dist/http/errors.js +27 -0
- package/dist/http/exposure.d.ts +54 -0
- package/dist/http/exposure.js +171 -0
- package/dist/http/handler.d.ts +23 -88
- package/dist/http/handler.js +42 -155
- package/dist/http/index.d.ts +8 -4
- package/dist/http/index.js +6 -3
- package/dist/http/route.d.ts +34 -0
- package/dist/http/route.js +82 -0
- package/dist/http/wireCall.d.ts +115 -0
- package/dist/http/wireCall.js +126 -0
- package/dist/http/wireQuery.d.ts +8 -0
- package/dist/http/wireQuery.js +51 -0
- package/dist/http/wireRow.d.ts +20 -0
- package/dist/http/wireRow.js +170 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -1
- package/dist/migrate/introspection/mysqlIntrospector.js +12 -2
- package/dist/mongodb/mongoDialect.d.ts +6 -6
- package/dist/mongodb/mongoDialect.js +6 -6
- package/dist/mongodb/mongodbQuerier.d.ts +8 -8
- package/dist/mssql/mssqlDialect.js +2 -2
- package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
- package/dist/nestjs/uqlContextInterceptor.js +7 -7
- package/dist/nestjs/uqlModule.d.ts +5 -11
- package/dist/nestjs/uqlModule.js +10 -15
- package/dist/querier/abstractQuerier.d.ts +8 -8
- package/dist/querier/abstractQuerier.js +15 -8
- package/dist/querier/abstractSqlQuerier.d.ts +8 -8
- package/dist/querier/keyset.d.ts +15 -0
- package/dist/querier/keyset.js +16 -11
- package/dist/sqlite/localSqliteQuerierPool.d.ts +1 -1
- package/dist/type/column.d.ts +4 -1
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +18 -4
- package/dist/type/universalQuerier.d.ts +16 -16
- package/dist/type/wire.d.ts +1 -31
- package/dist/util/dialect.util.d.ts +9 -16
- package/dist/util/dialect.util.js +20 -26
- package/dist/util/field.util.d.ts +4 -1
- package/dist/util/field.util.js +5 -2
- package/dist/util/object.util.d.ts +5 -2
- package/dist/util/object.util.js +12 -15
- package/dist/util/query.util.js +3 -10
- package/dist/util/uqlError.d.ts +27 -1
- package/dist/util/uqlError.js +43 -0
- package/package.json +5 -10
- package/skills/uql-orm/SKILL.md +4 -1
- package/dist/browser/http/bus.d.ts +0 -3
- package/dist/browser/http/bus.js +0 -12
- package/dist/browser/http/http.d.ts +0 -20
- package/dist/browser/http/http.js +0 -67
- package/dist/browser/querier/httpQuerier.d.ts +0 -46
- package/dist/browser/querier/httpQuerier.js +0 -64
- package/dist/browser/type/request.d.ts +0 -27
- package/dist/browser/uql-browser.min.js +0 -4
- package/dist/browser/uql-browser.min.js.map +0 -19
- package/dist/express/querierMiddleware.d.ts +0 -11
- package/dist/express/querierMiddleware.js +0 -39
- package/dist/http/contract.d.ts +0 -98
- package/dist/http/contract.js +0 -83
- package/dist/http/fetchHandler.d.ts +0 -13
- package/dist/http/fetchHandler.js +0 -63
- package/dist/http/query.d.ts +0 -28
- package/dist/http/query.js +0 -119
- /package/dist/browser/type/{request.js → transport.js} +0 -0
package/README.md
CHANGED
|
@@ -143,7 +143,7 @@ const posts = await pool.findMany(Post, {
|
|
|
143
143
|
|
|
144
144
|
The result is typed to what the query selected: `posts[0].author?.email` compiles, `posts[0].likes` does not.
|
|
145
145
|
|
|
146
|
-
The same queries run from the browser too: [serve them over
|
|
146
|
+
The same queries run from the browser too: [serve them over REST, tRPC or oRPC](https://uql-orm.dev/http), each field exposed as you declare, scoped to the signed-in user by [filters no `$where` can widen](https://uql-orm.dev/multi-tenancy).
|
|
147
147
|
|
|
148
148
|
## Why UQL?
|
|
149
149
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { RequestFailure } from '../../http/errors.js';
|
|
2
|
+
import { type ReadMethod } from '../../http/route.js';
|
|
3
|
+
import { type QueryErrorKind, type UqlErrorPath } from '../../util/uqlError.js';
|
|
4
|
+
import type { ClientTransport } from '../type/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* A failed call, as the API answered it: its HTTP status, what kind of failure it is (`queryErrorKind`'s), and where
|
|
7
|
+
* in the call the refused value sits, so a form can point at the field.
|
|
8
|
+
*/
|
|
9
|
+
export declare class RequestError extends Error implements RequestFailure {
|
|
10
|
+
name: string;
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly kind?: QueryErrorKind;
|
|
13
|
+
readonly path?: UqlErrorPath;
|
|
14
|
+
constructor({ message, status, ...where }: RequestFailure);
|
|
15
|
+
}
|
|
16
|
+
export type HttpTransportOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* Headers sent with every request, merged under per-call headers: a project key, the user's `Authorization`.
|
|
19
|
+
* Create one transport per request (e.g. during SSR) to scope auth headers safely.
|
|
20
|
+
*/
|
|
21
|
+
readonly headers?: Record<string, string>;
|
|
22
|
+
/**
|
|
23
|
+
* How reads travel: `GET` (the default) caches and needs nothing of any proxy; `QUERY` (RFC 10008) and `POST` carry
|
|
24
|
+
* the call in the body, past a URL's length limit, and `QUERY` needs infrastructure that forwards the method.
|
|
25
|
+
*/
|
|
26
|
+
readonly readMethod?: ReadMethod;
|
|
27
|
+
};
|
|
28
|
+
/** Calls an API mounted at `baseUrl` (e.g. `'/api/v1'`) with `fetch`. */
|
|
29
|
+
export declare function httpTransport(baseUrl: string, defaults?: HttpTransportOptions): ClientTransport;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { encodeCall } from '../../http/route.js';
|
|
2
|
+
import { isRecord } from '../../util/object.util.js';
|
|
3
|
+
import { isQueryErrorKind } from '../../util/uqlError.js';
|
|
4
|
+
/**
|
|
5
|
+
* A failed call, as the API answered it: its HTTP status, what kind of failure it is (`queryErrorKind`'s), and where
|
|
6
|
+
* in the call the refused value sits, so a form can point at the field.
|
|
7
|
+
*/
|
|
8
|
+
export class RequestError extends Error {
|
|
9
|
+
name = 'RequestError';
|
|
10
|
+
status;
|
|
11
|
+
constructor({ message, status, ...where }) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.status = status;
|
|
14
|
+
Object.assign(this, where);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Calls an API mounted at `baseUrl` (e.g. `'/api/v1'`) with `fetch`. */
|
|
18
|
+
export function httpTransport(baseUrl, defaults = {}) {
|
|
19
|
+
return async (call, opts) => {
|
|
20
|
+
const { method, path, body } = encodeCall(call, defaults.readMethod);
|
|
21
|
+
// A content type only with a body: on a GET it is not a CORS-safelisted header, so it would cost a preflight.
|
|
22
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
23
|
+
method,
|
|
24
|
+
headers: {
|
|
25
|
+
accept: 'application/json',
|
|
26
|
+
...(body !== undefined && { 'content-type': 'application/json' }),
|
|
27
|
+
...defaults.headers,
|
|
28
|
+
...opts?.headers,
|
|
29
|
+
},
|
|
30
|
+
...(body !== undefined && { body }),
|
|
31
|
+
...(opts?.signal && { signal: opts.signal }),
|
|
32
|
+
});
|
|
33
|
+
const answer = await response.json().catch(() => undefined);
|
|
34
|
+
// A success is the API's only as its envelope: an HTML page a wrong base URL lands on is none.
|
|
35
|
+
if (response.ok) {
|
|
36
|
+
if (isRecord(answer)) {
|
|
37
|
+
return answer['data'];
|
|
38
|
+
}
|
|
39
|
+
throw new RequestError({
|
|
40
|
+
message: "the response is no API answer: no JSON '{ data }' envelope",
|
|
41
|
+
status: response.status,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
throw failureOf(answer, response);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function isErrorPath(value) {
|
|
48
|
+
return Array.isArray(value) && value.every((key) => typeof key === 'string' || typeof key === 'number');
|
|
49
|
+
}
|
|
50
|
+
function failureOf(answer, response) {
|
|
51
|
+
const error = isRecord(answer) && isRecord(answer['error']) ? answer['error'] : {};
|
|
52
|
+
const { message, status, kind, path } = error;
|
|
53
|
+
return new RequestError({
|
|
54
|
+
message: typeof message === 'string' ? message : response.statusText,
|
|
55
|
+
status: typeof status === 'number' ? status : response.status,
|
|
56
|
+
...(isQueryErrorKind(kind) && { kind }),
|
|
57
|
+
...(isErrorPath(path) && { path }),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
export * from './
|
|
2
|
-
export * from './http.js';
|
|
1
|
+
export * from './httpTransport.js';
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
export * from './
|
|
2
|
-
export * from './http.js';
|
|
1
|
+
export * from './httpTransport.js';
|
package/dist/browser/index.d.ts
CHANGED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type EntityPathOptions } from '../../http/wireCall.js';
|
|
2
|
+
import type { ClientQuerier, ClientTransport } from '../type/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* The querier a client runs against an API, over `transport`: the server querier's methods, answering what it
|
|
5
|
+
* answers, each row read back as the entity holds it (a `Date` as a `Date`, a `bigint` exact).
|
|
6
|
+
*/
|
|
7
|
+
export declare function createClientQuerier(transport: ClientTransport, opts?: EntityPathOptions): ClientQuerier;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { getMeta } from '../../entity/metadata/definition.js';
|
|
2
|
+
import { API_OPS, entityPathOf } from '../../http/wireCall.js';
|
|
3
|
+
import { readWireData } from '../../http/wireRow.js';
|
|
4
|
+
import { isScalarId } from '../../util/object.util.js';
|
|
5
|
+
import { UqlUsageError } from '../../util/uqlError.js';
|
|
6
|
+
/** The id as a call carries it, refusing a composite key, which a call has no spelling for yet. */
|
|
7
|
+
function idOf(entity, id) {
|
|
8
|
+
if (!isScalarId(id)) {
|
|
9
|
+
throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which a call cannot carry.`);
|
|
10
|
+
}
|
|
11
|
+
return typeof id === 'number' ? id : String(id);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The querier a client runs against an API, over `transport`: the server querier's methods, answering what it
|
|
15
|
+
* answers, each row read back as the entity holds it (a `Date` as a `Date`, a `bigint` exact).
|
|
16
|
+
*/
|
|
17
|
+
export function createClientQuerier(transport, opts = {}) {
|
|
18
|
+
const pathOf = entityPathOf(opts);
|
|
19
|
+
/** The result is the API's, read by the entity: the network is where its type is taken on trust. */
|
|
20
|
+
async function send(entity, op, fields, options) {
|
|
21
|
+
const answer = await transport({ entity: pathOf(entity), op, ...fields }, options);
|
|
22
|
+
return readWireData(getMeta(entity), answer, API_OPS[op].answers);
|
|
23
|
+
}
|
|
24
|
+
const querier = {
|
|
25
|
+
findOneById: async (entity, id, query, options) => send(entity, 'findOneById', { id: idOf(entity, id), query }, options),
|
|
26
|
+
findOne: (entity, query, options) => send(entity, 'findOne', { query }, options),
|
|
27
|
+
findMany: (entity, query, options) => send(entity, 'findMany', { query }, options),
|
|
28
|
+
findManyAndCount: (entity, query, options) => send(entity, 'findManyAndCount', { query }, options),
|
|
29
|
+
findManyPage: (entity, query, options) => send(entity, 'findManyPage', { query }, options),
|
|
30
|
+
count: (entity, query, options) => send(entity, 'count', { query }, options),
|
|
31
|
+
/** The count capped at one row, so existence needs no op of its own. */
|
|
32
|
+
exists: async (entity, query, options) => (await querier.count(entity, { ...query, $limit: 1 }, options)) > 0,
|
|
33
|
+
insertOne: (entity, payload, options) => send(entity, 'insertOne', { payload }, options),
|
|
34
|
+
insertMany: (entity, payload, options) => send(entity, 'insertMany', { payload }, options),
|
|
35
|
+
saveOne: (entity, payload, options) => send(entity, 'saveOne', { payload }, options),
|
|
36
|
+
saveMany: (entity, payload, options) => send(entity, 'saveMany', { payload }, options),
|
|
37
|
+
updateOneById: async (entity, id, payload, options) => send(entity, 'updateOneById', { id: idOf(entity, id), payload }, options),
|
|
38
|
+
updateMany: (entity, query, payload, options) => send(entity, 'updateMany', { query, payload }, options),
|
|
39
|
+
deleteOneById: async (entity, id, options) => send(entity, 'deleteOneById', { id: idOf(entity, id), hardDelete: options?.hardDelete }, options),
|
|
40
|
+
deleteMany: (entity, query, options) => send(entity, 'deleteMany', { query, hardDelete: options?.hardDelete }, options),
|
|
41
|
+
};
|
|
42
|
+
return querier;
|
|
43
|
+
}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export * from './
|
|
1
|
+
export * from './clientQuerier.js';
|
|
2
|
+
export * from './queryOptions.js';
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export * from './
|
|
1
|
+
export * from './clientQuerier.js';
|
|
2
|
+
export * from './queryOptions.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type EntityPathOptions } from '../../http/wireCall.js';
|
|
2
|
+
import type { AbstractType } from '../../type/index.js';
|
|
3
|
+
import type { ClientQuerier, ClientTransport } from '../type/index.js';
|
|
4
|
+
/** A cache key for a read: `['uql', entityPath, op, the rest of the call as JSON carries it]`, prefixed by entity. */
|
|
5
|
+
export type UqlQueryKey = readonly ['uql', string, ...unknown[]];
|
|
6
|
+
/** What `useQuery`, `queryOptions` and `prefetchQuery` take: the key a read is cached under, and the read. */
|
|
7
|
+
export type UqlQueryOptions<T> = {
|
|
8
|
+
readonly queryKey: UqlQueryKey;
|
|
9
|
+
readonly queryFn: (context: {
|
|
10
|
+
readonly signal: AbortSignal;
|
|
11
|
+
}) => Promise<T>;
|
|
12
|
+
};
|
|
13
|
+
/** Query options for a read, and `key(entity)`, the prefix every read of an entity is cached under. */
|
|
14
|
+
export type QueryOptionsFor = {
|
|
15
|
+
<T>(read: (querier: ClientQuerier) => Promise<T>): UqlQueryOptions<T>;
|
|
16
|
+
key(entity: AbstractType<unknown>): UqlQueryKey;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Query options (TanStack Query's, or any cache keyed by JSON) for reads over `transport`: each keyed by the one call
|
|
20
|
+
* the read makes, so the key cannot drift from the fetch, two ops on one query never share an entry, and invalidating
|
|
21
|
+
* `key(User)` reaches every read of `User`. Takes the client's options, so a key names an entity as its call does.
|
|
22
|
+
*/
|
|
23
|
+
export declare function createQueryOptions(transport: ClientTransport, opts?: EntityPathOptions): QueryOptionsFor;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { entityPathOf, wireJson } from '../../http/wireCall.js';
|
|
2
|
+
import { UqlUsageError } from '../../util/uqlError.js';
|
|
3
|
+
import { createClientQuerier } from './clientQuerier.js';
|
|
4
|
+
/**
|
|
5
|
+
* Query options (TanStack Query's, or any cache keyed by JSON) for reads over `transport`: each keyed by the one call
|
|
6
|
+
* the read makes, so the key cannot drift from the fetch, two ops on one query never share an entry, and invalidating
|
|
7
|
+
* `key(User)` reaches every read of `User`. Takes the client's options, so a key names an entity as its call does.
|
|
8
|
+
*/
|
|
9
|
+
export function createQueryOptions(transport, opts = {}) {
|
|
10
|
+
const pathOf = entityPathOf(opts);
|
|
11
|
+
const options = (read) => {
|
|
12
|
+
const { entity, op, ...rest } = callOf(read, opts);
|
|
13
|
+
return {
|
|
14
|
+
queryKey: ['uql', entity, op, JSON.parse(wireJson(rest))],
|
|
15
|
+
queryFn: ({ signal }) => read(createClientQuerier((call, given) => transport(call, { ...given, signal }), opts)),
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
return Object.assign(options, { key: (entity) => ['uql', pathOf(entity)] });
|
|
19
|
+
}
|
|
20
|
+
/** The call `read` makes, recorded without sending it: a querier hands its call to the transport before it awaits. */
|
|
21
|
+
function callOf(read, opts) {
|
|
22
|
+
const calls = [];
|
|
23
|
+
const recorder = createClientQuerier((call) => {
|
|
24
|
+
calls.push(call);
|
|
25
|
+
return new Promise(() => { });
|
|
26
|
+
}, opts);
|
|
27
|
+
// Never settles once it has made its call; one that fails before it does is refused below.
|
|
28
|
+
read(recorder).catch(() => { });
|
|
29
|
+
const [call] = calls;
|
|
30
|
+
if (!call || calls.length > 1) {
|
|
31
|
+
const why = call ? '' : ': run the read outside `uql()` to see whether it failed before its call';
|
|
32
|
+
throw new UqlUsageError(`a query reads by one call to the API, not ${calls.length}${why}`);
|
|
33
|
+
}
|
|
34
|
+
return call;
|
|
35
|
+
}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import type { Type, EntityWrite,
|
|
2
|
-
import type {
|
|
1
|
+
import type { Type, EntityWrite, QueryOptions, SharedQuerier, WrittenId } from '../../type/index.js';
|
|
2
|
+
import type { CallOptions } from './transport.js';
|
|
3
3
|
/**
|
|
4
|
-
* Client-side querier: {@link SharedQuerier} on the `'client'` transport,
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @see UniversalQuerier for the same operations with direct return types.
|
|
4
|
+
* Client-side querier: {@link SharedQuerier} on the `'client'` transport, answering what the server querier
|
|
5
|
+
* answers, every method taking an extra `opts?: CallOptions` for its transport. The writes are restated here: the
|
|
6
|
+
* server's infer what `returning` reads back from their options, which the client's take none of.
|
|
8
7
|
*/
|
|
9
|
-
export interface ClientQuerier extends SharedQuerier<'client',
|
|
10
|
-
insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?:
|
|
11
|
-
insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?:
|
|
12
|
-
saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?:
|
|
13
|
-
saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?:
|
|
8
|
+
export interface ClientQuerier extends SharedQuerier<'client', CallOptions, QueryOptions & CallOptions> {
|
|
9
|
+
insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?: CallOptions): Promise<NonNullable<WrittenId<E>>>;
|
|
10
|
+
insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: CallOptions): Promise<NonNullable<WrittenId<E>>[]>;
|
|
11
|
+
saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?: CallOptions): Promise<NonNullable<WrittenId<E>>>;
|
|
12
|
+
saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: CallOptions): Promise<NonNullable<WrittenId<E>>[]>;
|
|
14
13
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export * from './clientQuerier.js';
|
|
2
|
-
export * from './
|
|
2
|
+
export * from './transport.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export * from './clientQuerier.js';
|
|
2
|
-
export * from './
|
|
2
|
+
export * from './transport.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { WireCall } from '../../http/wireCall.js';
|
|
2
|
+
/** What a call hands its transport beside the call itself. */
|
|
3
|
+
export type CallOptions = {
|
|
4
|
+
/** Extra headers merged over the transport's defaults (e.g. `{ Authorization: 'Bearer ...' }`). */
|
|
5
|
+
readonly headers?: Record<string, string>;
|
|
6
|
+
/** Abort and timeout control, e.g. `AbortSignal.timeout(120_000)` for a long-running call. */
|
|
7
|
+
readonly signal?: AbortSignal;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Carries a call to an API and resolves to its result as the API answered it, as JSON carries it or already typed:
|
|
11
|
+
* HTTP (`httpTransport`), a tRPC or oRPC procedure, a server action. Rejects on a failure.
|
|
12
|
+
*/
|
|
13
|
+
export type ClientTransport = (call: WireCall, opts?: CallOptions) => Promise<unknown>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, FieldOptions, InsertIdSource, NamingStrategy, Query,
|
|
1
|
+
import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, FieldOptions, InsertIdSource, NamingStrategy, Query, StatementOptions, QueryWhere, AbstractType } from '../type/index.js';
|
|
2
2
|
import { type EngineName } from '../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* Options for initializing a dialect.
|
|
@@ -77,7 +77,7 @@ export declare abstract class AbstractDialect {
|
|
|
77
77
|
* new query scope, so a scope cannot be rendered with its `security: true` filters skipped.
|
|
78
78
|
* Recursion within one scope renders the returned map directly instead.
|
|
79
79
|
*/
|
|
80
|
-
protected scopedWhere<E>(meta: EntityMeta<E>, where?: QueryWhere<E>, opts?:
|
|
80
|
+
protected scopedWhere<E>(meta: EntityMeta<E>, where?: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
|
|
81
81
|
/**
|
|
82
82
|
* Whether a `$where` reads a relation at any depth: filters by one, or by a relation aggregate. What
|
|
83
83
|
* cannot host that read - a MongoDB filter, a write without {@link DialectFeatures.correlatedWrites} -
|
|
@@ -3,7 +3,7 @@ import { generatesKey, valueFieldOf } from '../entity/metadata/definition.js';
|
|
|
3
3
|
import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, REF_ENTITY, REF_KEY, ColumnRef, renderSql, RAW_ALIAS, } from '../type/index.js';
|
|
4
4
|
import { utcTimestamp } from '../util/date.js';
|
|
5
5
|
import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys, lacksValueOnInsert, } from '../util/field.util.js';
|
|
6
|
-
import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, hasTriggers, foundRowAssigned, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys,
|
|
6
|
+
import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, hasTriggers, foundRowAssigned, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isPlainObject, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, columnRef, refOwner, throwUnknownAggregateColumn, } from '../util/index.js';
|
|
7
7
|
import { cachedIn, isJsonScalar } from '../util/object.util.js';
|
|
8
8
|
import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
|
|
9
9
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
@@ -823,7 +823,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
823
823
|
read: (mode) => this.jsonElemValue(slot, alias, mode),
|
|
824
824
|
};
|
|
825
825
|
const conditions = values.map((value) => {
|
|
826
|
-
const holds =
|
|
826
|
+
const holds = isPlainObject(value) || Array.isArray(value)
|
|
827
827
|
? this.jsonHolds(ctx, element, value, scope)
|
|
828
828
|
: [this.jsonElemEquals(ctx, slot, alias, value)];
|
|
829
829
|
return jsonElemExists(from, holds, this.jsonElemHint);
|
|
@@ -2241,7 +2241,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
2241
2241
|
}
|
|
2242
2242
|
/** `<distance> <op> ?`, the `$where` half of a vector search, its bounds checked here since `/http` input is untyped. */
|
|
2243
2243
|
vectorNearCondition(ctx, meta, key, near, prefix) {
|
|
2244
|
-
if (!
|
|
2244
|
+
if (!isPlainObject(near)) {
|
|
2245
2245
|
throw new UqlUsageError(`$near on '${key}' expects an object of its $vector and bounds, got ${kindOf(near)}`);
|
|
2246
2246
|
}
|
|
2247
2247
|
const bounds = Object.entries(near).filter(([op, val]) => !VECTOR_QUERY_KEY_SET.has(op) && val !== undefined);
|
package/dist/dialect/jsonSql.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { QuerySql } from '../type/index.js';
|
|
2
|
-
import { isOperatorMap } from '../util/dialect.util.js';
|
|
3
2
|
import { columnFamily, declaresNotNull, jsonPathKeys } from '../util/field.util.js';
|
|
4
|
-
import { isOperatorKey, someKey } from '../util/object.util.js';
|
|
3
|
+
import { isOperatorKey, isPlainObject, someKey } from '../util/object.util.js';
|
|
5
4
|
import { JSON_SKIP_KEY } from './aliases.js';
|
|
6
5
|
/**
|
|
7
6
|
* A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
|
|
@@ -108,5 +107,5 @@ export function holdsOperator(value) {
|
|
|
108
107
|
if (Array.isArray(value)) {
|
|
109
108
|
return value.some(holdsOperator);
|
|
110
109
|
}
|
|
111
|
-
return
|
|
110
|
+
return isPlainObject(value) && someKey(value, (key) => isOperatorKey(key) || holdsOperator(value[key]));
|
|
112
111
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ColumnRef, QuerySql, REF_ENTITY, REF_KEY, VECTOR_QUERY_KEYS, } from '../type/index.js';
|
|
2
|
-
import { isOperatorMap } from '../util/dialect.util.js';
|
|
3
2
|
import { aggregateOf, isInlinedExpression } from '../util/field.util.js';
|
|
4
|
-
import { getKeys, hasKeys, isOperatorKey,
|
|
3
|
+
import { getKeys, hasKeys, isOperatorKey, isPlainObject, isRecord, someKey } from '../util/object.util.js';
|
|
5
4
|
import { escapeRegExp } from '../util/string.util.js';
|
|
6
5
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
7
6
|
/**
|
|
@@ -37,7 +36,7 @@ export function namesRows(where) {
|
|
|
37
36
|
return (where !== undefined &&
|
|
38
37
|
someKey(where, (key) => isGroupOp(key)
|
|
39
38
|
? groupClauses(key, where[key]).some((clause) => clause instanceof QuerySql || namesRows(clause))
|
|
40
|
-
: !(
|
|
39
|
+
: !(isPlainObject(where[key]) && !hasKeys(where[key]))));
|
|
41
40
|
}
|
|
42
41
|
/**
|
|
43
42
|
* The fields of `meta` a `$where` reads, through every group: each key, a JSON path by its column, and each ref to
|
|
@@ -78,7 +77,7 @@ export function fieldsRead(meta, where) {
|
|
|
78
77
|
* anything else `$eq`. Each key is checked here, once, refused as `refusal` where it is no operator.
|
|
79
78
|
*/
|
|
80
79
|
export function whereOperators(val, refusal) {
|
|
81
|
-
const ops = Array.isArray(val) ? { $in: val } :
|
|
80
|
+
const ops = Array.isArray(val) ? { $in: val } : isPlainObject(val) ? val : { $eq: val };
|
|
82
81
|
return Object.entries(ops).map(([op, value]) => {
|
|
83
82
|
if (!isFieldOp(op)) {
|
|
84
83
|
throw new UqlUsageError(`${refusal}: ${op}`);
|
|
@@ -164,7 +163,7 @@ export function sizeComparisons(size) {
|
|
|
164
163
|
if (typeof size === 'number') {
|
|
165
164
|
return [['$eq', size]];
|
|
166
165
|
}
|
|
167
|
-
if (!
|
|
166
|
+
if (!isPlainObject(size)) {
|
|
168
167
|
throw new UqlUsageError(`$size expects a number or bounds, got ${kindOf(size)}`);
|
|
169
168
|
}
|
|
170
169
|
const comparisons = Object.entries(size).filter(([, bound]) => bound !== undefined);
|
package/dist/express/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from './
|
|
1
|
+
export * from './router.js';
|
package/dist/express/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from './
|
|
1
|
+
export * from './router.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Request, type Router } from 'express';
|
|
2
|
+
import type { Api } from '../http/api.js';
|
|
3
|
+
/**
|
|
4
|
+
* The API as an express router, handing the express `Request` to the API as its context. Mount it under the API's
|
|
5
|
+
* base, e.g. `app.use('/api/v1', toExpress(api))`. It reads a body only on a route it serves, and a route it does
|
|
6
|
+
* not serve falls through via `next()`, so it composes with custom routes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function toExpress(api: Api<Request>): Router;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import express, {} from 'express';
|
|
2
|
+
import { toErrorResponse } from '../http/errors.js';
|
|
3
|
+
import { answerRequest } from '../http/handler.js';
|
|
4
|
+
import { isRecord } from '../util/object.util.js';
|
|
5
|
+
import { UqlRequestError } from '../util/uqlError.js';
|
|
6
|
+
/**
|
|
7
|
+
* The API as an express router, handing the express `Request` to the API as its context. Mount it under the API's
|
|
8
|
+
* base, e.g. `app.use('/api/v1', toExpress(api))`. It reads a body only on a route it serves, and a route it does
|
|
9
|
+
* not serve falls through via `next()`, so it composes with custom routes.
|
|
10
|
+
*/
|
|
11
|
+
export function toExpress(api) {
|
|
12
|
+
const router = express.Router();
|
|
13
|
+
// As text, for the API to parse once it takes the method and the content type; one parsed already passes as it is.
|
|
14
|
+
const text = express.text({ type: 'application/json' });
|
|
15
|
+
router.all('/:entityPath/:op', (req, res, next) => {
|
|
16
|
+
const { entityPath, op } = req.params;
|
|
17
|
+
if (!api.serves(entityPath, op)) {
|
|
18
|
+
next();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
text(req, res, (err) => {
|
|
22
|
+
if (err) {
|
|
23
|
+
send(res, toErrorResponse(unread(err)));
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const answered = answerRequest(api, {
|
|
27
|
+
method: req.method,
|
|
28
|
+
entityPath,
|
|
29
|
+
op,
|
|
30
|
+
q: req.query['q'],
|
|
31
|
+
body: req.body,
|
|
32
|
+
contentType: req.get('content-type'),
|
|
33
|
+
context: req,
|
|
34
|
+
});
|
|
35
|
+
void answered.then((response) => send(res, response));
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
return router;
|
|
39
|
+
}
|
|
40
|
+
function send(res, { status, body, headers }) {
|
|
41
|
+
res
|
|
42
|
+
.status(status)
|
|
43
|
+
.set(headers ?? {})
|
|
44
|
+
.json(body);
|
|
45
|
+
}
|
|
46
|
+
/** What the body reader refused, an oversized body or an unknown charset, as the request it refuses: a 4xx. */
|
|
47
|
+
function unread(err) {
|
|
48
|
+
const status = isRecord(err) && typeof err['status'] === 'number' && err['status'] < 500 ? err['status'] : 400;
|
|
49
|
+
return new UqlRequestError('the body could not be read', status);
|
|
50
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { QuerierPool, Type, UqlContext } from '../type/index.js';
|
|
2
|
+
import { type ApiMiddleware } from './apiCall.js';
|
|
3
|
+
import { type Served } from './exposure.js';
|
|
4
|
+
import { type ApiOp, type EntityPathOptions } from './wireCall.js';
|
|
5
|
+
export type ApiOptions<Ctx = unknown> = EntityPathOptions & {
|
|
6
|
+
/**
|
|
7
|
+
* The entities served, and the only ones a call reaches, through a relation too: nothing is served by being
|
|
8
|
+
* defined, so an entity holding secrets (a session's token) stays off the wire unless named. `serve(User, {...})`
|
|
9
|
+
* narrows what a client may do to one, and runs middleware of its own.
|
|
10
|
+
*/
|
|
11
|
+
include: readonly (Type<object> | Served<object, Ctx>)[];
|
|
12
|
+
/** Run around every call, first to last, before an entity's own. */
|
|
13
|
+
use?: readonly ApiMiddleware<Ctx>[];
|
|
14
|
+
/**
|
|
15
|
+
* Derive the ambient {@link UqlContext} (e.g. `{ tenantId, userId }`) from the transport's context, which the whole
|
|
16
|
+
* call then runs inside, so `security` filters scope it. Derive it from a verified source (a session, a JWT).
|
|
17
|
+
* Without it, a call runs in whatever context its caller set (a tRPC middleware's).
|
|
18
|
+
*/
|
|
19
|
+
contextOf?: (context: Ctx) => UqlContext | undefined | Promise<UqlContext | undefined>;
|
|
20
|
+
/**
|
|
21
|
+
* The pool a call runs on. A function is called per call, after `contextOf` and every middleware, with the
|
|
22
|
+
* transport's context and the context the call runs in: a database per tenant.
|
|
23
|
+
*/
|
|
24
|
+
pool: QuerierPool | ((context: Ctx, appContext: UqlContext) => QuerierPool | Promise<QuerierPool>);
|
|
25
|
+
};
|
|
26
|
+
export type Api<Ctx = unknown> = {
|
|
27
|
+
/** Whether `op` on the entity at `path` is a call this API serves: what a transport that falls through on others asks. */
|
|
28
|
+
serves(path: string, op: string): op is ApiOp;
|
|
29
|
+
/**
|
|
30
|
+
* Run a client's call, which arrives as JSON from any transport and is checked here, and resolve to its result as
|
|
31
|
+
* JSON carries it. Refuses what the call may not reach before any middleware runs, so what a middleware adds is
|
|
32
|
+
* the server's own.
|
|
33
|
+
*/
|
|
34
|
+
call(call: unknown, context: Ctx): Promise<unknown>;
|
|
35
|
+
};
|
|
36
|
+
export declare function createApi<Ctx = unknown>(opts: ApiOptions<Ctx>): Api<Ctx>;
|