uql-orm 0.112.1 → 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/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 -158
- 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 +4 -2
- package/dist/http/wireRow.js +15 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mongodb/mongoDialect.d.ts +6 -6
- package/dist/mongodb/mongodbQuerier.d.ts +8 -8
- 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/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 -9
- package/dist/util/dialect.util.js +18 -10
- package/dist/util/field.util.d.ts +4 -1
- package/dist/util/field.util.js +5 -2
- package/dist/util/uqlError.d.ts +27 -1
- package/dist/util/uqlError.js +43 -0
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +4 -2
- 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 -70
- package/dist/browser/type/request.d.ts +0 -27
- package/dist/express/querierMiddleware.d.ts +0 -11
- package/dist/express/querierMiddleware.js +0 -39
- package/dist/http/contract.d.ts +0 -113
- 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 -26
- 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} -
|
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>;
|
package/dist/http/api.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { getContext as ambientContext, withContext } from '../context/context.js';
|
|
2
|
+
import { getMeta, soleIdOf } from '../entity/index.js';
|
|
3
|
+
import { assertPageable } from '../querier/keyset.js';
|
|
4
|
+
import { whereWith } from '../util/query.util.js';
|
|
5
|
+
import { UqlError, UqlRequestError, UqlUsageError } from '../util/uqlError.js';
|
|
6
|
+
import { callOf, chain, isCallOf } from './apiCall.js';
|
|
7
|
+
import { entityOf, exposedQuery, exposuresOf } from './exposure.js';
|
|
8
|
+
import { API_OPS, entityPathOf, isApiOp, parseWireCall, } from './wireCall.js';
|
|
9
|
+
import { parseWireQuery } from './wireQuery.js';
|
|
10
|
+
import { readWirePayload, readWireQuery, writeWireData } from './wireRow.js';
|
|
11
|
+
/** `Company (crm.Company)`: the class, and the table it maps, which is what tells two apart. */
|
|
12
|
+
function tableOf(entity) {
|
|
13
|
+
const meta = getMeta(entity);
|
|
14
|
+
return `${entity.name} (${meta.schema ? `${meta.schema}.${meta.name}` : meta.name})`;
|
|
15
|
+
}
|
|
16
|
+
export function createApi(opts) {
|
|
17
|
+
const { include, use = [], contextOf, pool } = opts;
|
|
18
|
+
const pathOf = entityPathOf(opts);
|
|
19
|
+
// Refused rather than defaulted to every entity defined, which would serve whatever one registers.
|
|
20
|
+
if (!include?.length) {
|
|
21
|
+
throw new UqlUsageError("name the entities the API serves in 'include': it serves those alone");
|
|
22
|
+
}
|
|
23
|
+
const exposures = exposuresOf(include);
|
|
24
|
+
const entities = include.map(entityOf);
|
|
25
|
+
const aroundOf = new Map(include.flatMap((item) => typeof item === 'function' || !item.around ? [] : [[item.entity, item.around]]));
|
|
26
|
+
// All of them at once, so fixing the first collision does not just reveal the next.
|
|
27
|
+
const byPath = Map.groupBy(entities, pathOf);
|
|
28
|
+
const collisions = [...byPath].filter(([, clashing]) => clashing.length > 1);
|
|
29
|
+
if (collisions.length) {
|
|
30
|
+
const lines = collisions.map(([path, clashing]) => ` /${path} <- ${clashing.map(tableOf).join(', ')}`);
|
|
31
|
+
throw new UqlUsageError(`every entity below shares a path with another, so all but the first are unreachable:\n${lines.join('\n')}\n` +
|
|
32
|
+
"A path is the kebab-cased class name unless 'entityPath' says otherwise. Name them apart, " +
|
|
33
|
+
"pass an 'entityPath', or pass only one of them in 'include'.");
|
|
34
|
+
}
|
|
35
|
+
const entityByPath = new Map([...byPath].map(([path, [entity]]) => [path, entity]));
|
|
36
|
+
return {
|
|
37
|
+
serves: (path, op) => entityByPath.has(path) && isApiOp(op),
|
|
38
|
+
call: async (input, context) => {
|
|
39
|
+
const wire = parseWireCall(input);
|
|
40
|
+
const entity = entityByPath.get(wire.entity);
|
|
41
|
+
if (!entity) {
|
|
42
|
+
// A 404, as a route that names no entity is: the call is well formed, its entity is not here.
|
|
43
|
+
throw new UqlRequestError(`'${wire.entity}' is not an entity this API serves`, 404);
|
|
44
|
+
}
|
|
45
|
+
return run(entity, wire, context);
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
async function run(entity, wire, context) {
|
|
49
|
+
const meta = getMeta(entity);
|
|
50
|
+
const shape = API_OPS[wire.op];
|
|
51
|
+
const call = decodedCall(entity, wire, exposures);
|
|
52
|
+
const appContext = contextOf ? ((await contextOf(context)) ?? {}) : (ambientContext() ?? {});
|
|
53
|
+
const around = aroundOf.get(entity);
|
|
54
|
+
const answer = () => chain(around ? [...use, around] : use, context, async (reshaped) => {
|
|
55
|
+
if (!isCallOf(entity, reshaped)) {
|
|
56
|
+
throw new UqlUsageError(`a middleware moved a call to '${entity.name}' to another entity`);
|
|
57
|
+
}
|
|
58
|
+
// Resolved after the middleware: one that aborts the call must not reach the pool at all.
|
|
59
|
+
const resolved = typeof pool === 'function' ? await pool(context, appContext) : pool;
|
|
60
|
+
// A read acquires and releases; a write is one transaction, so a failing cascade takes its parent with it.
|
|
61
|
+
const execute = (querier) => executeOn(querier, reshaped);
|
|
62
|
+
const pending = shape.access === 'read' ? resolved.withQuerier(execute) : resolved.transaction(execute);
|
|
63
|
+
return pending.catch(placedInQuery);
|
|
64
|
+
})(call);
|
|
65
|
+
// Scope the whole call (middleware, querier, relation and cascade queries) to the context `contextOf` resolved;
|
|
66
|
+
// without one, the call keeps the context its caller runs in.
|
|
67
|
+
const result = await (contextOf ? withContext(appContext, answer) : answer());
|
|
68
|
+
return writeWireData(meta, result, shape.answers);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The call `wire` asks of `entity` as the querier takes it: its query and payload read back as the entity holds them,
|
|
73
|
+
* checked against what its op takes and what the API exposes. Run on what the client sent, before any middleware, so
|
|
74
|
+
* what a middleware adds is the server's own to add.
|
|
75
|
+
*/
|
|
76
|
+
function decodedCall(entity, wire, exposures) {
|
|
77
|
+
const meta = getMeta(entity);
|
|
78
|
+
const { op } = wire;
|
|
79
|
+
const query = readWireQuery(meta, parseWireQuery(wire.query));
|
|
80
|
+
const payload = readWirePayload(meta, wire.payload);
|
|
81
|
+
return callOf({
|
|
82
|
+
entity,
|
|
83
|
+
op,
|
|
84
|
+
id: wire.id,
|
|
85
|
+
query: exposedQuery(meta, op, query, payload, exposures),
|
|
86
|
+
payload,
|
|
87
|
+
hardDelete: wire.hardDelete ?? false,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** A querier's refusal names its place within the query it refused: within the call, that is under `query`. */
|
|
91
|
+
function placedInQuery(err) {
|
|
92
|
+
if (err instanceof UqlError && err.path) {
|
|
93
|
+
Object.defineProperty(err, 'path', { value: ['query', ...err.path] });
|
|
94
|
+
}
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
async function executeOn(querier, call) {
|
|
98
|
+
const { entity, query, hardDelete } = call;
|
|
99
|
+
/** The query scoped to the one row the call addresses. */
|
|
100
|
+
const byId = (id) => ({
|
|
101
|
+
...query,
|
|
102
|
+
$where: whereWith(soleIdOf(getMeta(entity), 'the API'), id, query.$where),
|
|
103
|
+
});
|
|
104
|
+
switch (call.op) {
|
|
105
|
+
case 'findOne':
|
|
106
|
+
return querier.findOne(entity, query);
|
|
107
|
+
case 'findOneById':
|
|
108
|
+
return querier.findOne(entity, byId(call.id));
|
|
109
|
+
case 'count':
|
|
110
|
+
return querier.count(entity, query);
|
|
111
|
+
case 'findMany':
|
|
112
|
+
return querier.findMany(entity, query);
|
|
113
|
+
case 'findManyAndCount':
|
|
114
|
+
return querier.findManyAndCount(entity, query);
|
|
115
|
+
case 'findManyPage':
|
|
116
|
+
assertPageable(getMeta(entity), query);
|
|
117
|
+
return querier.findManyPage(entity, query);
|
|
118
|
+
case 'insertOne':
|
|
119
|
+
return querier.insertOne(entity, call.payload);
|
|
120
|
+
case 'saveOne':
|
|
121
|
+
return querier.saveOne(entity, call.payload);
|
|
122
|
+
case 'insertMany':
|
|
123
|
+
return querier.insertMany(entity, call.payload);
|
|
124
|
+
case 'saveMany':
|
|
125
|
+
return querier.saveMany(entity, call.payload);
|
|
126
|
+
// A write answers how many rows it changed, and the querier still refuses a delete that names no rows.
|
|
127
|
+
case 'updateMany':
|
|
128
|
+
return querier.updateMany(entity, query, call.payload);
|
|
129
|
+
case 'updateOneById':
|
|
130
|
+
return querier.updateMany(entity, byId(call.id), call.payload);
|
|
131
|
+
case 'deleteMany':
|
|
132
|
+
return querier.deleteMany(entity, query, { hardDelete });
|
|
133
|
+
case 'deleteOneById':
|
|
134
|
+
return querier.deleteMany(entity, byId(call.id), { hardDelete });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { EntityWrite, Query, Type, UpdateWrite } from '../type/index.js';
|
|
2
|
+
import type { API_OPS, ApiOp } from './wireCall.js';
|
|
3
|
+
import type { WireCursors } from './wireQuery.js';
|
|
4
|
+
/** Each kind of payload an op writes, as the entity holds it. */
|
|
5
|
+
type Payloads<E> = {
|
|
6
|
+
readonly row: EntityWrite<E>;
|
|
7
|
+
readonly rows: readonly EntityWrite<E>[];
|
|
8
|
+
readonly changes: UpdateWrite<E>;
|
|
9
|
+
};
|
|
10
|
+
type PayloadOf<E, Op extends ApiOp> = (typeof API_OPS)[Op] extends {
|
|
11
|
+
readonly writes: infer W extends keyof Payloads<E>;
|
|
12
|
+
} ? {
|
|
13
|
+
readonly payload: Payloads<E>[W];
|
|
14
|
+
} : {
|
|
15
|
+
readonly payload?: undefined;
|
|
16
|
+
};
|
|
17
|
+
/** The row an op by id addresses, which no other op names. */
|
|
18
|
+
type IdOf<Op extends ApiOp> = (typeof API_OPS)[Op] extends {
|
|
19
|
+
readonly byId: true;
|
|
20
|
+
} ? {
|
|
21
|
+
readonly id: string | number;
|
|
22
|
+
} : {
|
|
23
|
+
readonly id?: undefined;
|
|
24
|
+
};
|
|
25
|
+
type CallOf<E, Op extends ApiOp> = {
|
|
26
|
+
readonly entity: Type<E>;
|
|
27
|
+
readonly op: Op;
|
|
28
|
+
readonly query: Query<E> & WireCursors;
|
|
29
|
+
readonly hardDelete: boolean;
|
|
30
|
+
} & IdOf<Op> & PayloadOf<E, Op>;
|
|
31
|
+
/**
|
|
32
|
+
* A call as the API runs it, decoded and checked, for a middleware to read or reshape: one member per op, so
|
|
33
|
+
* narrowing on `op` types the payload (`call.op === 'insertOne'` makes it a row).
|
|
34
|
+
*/
|
|
35
|
+
export type ApiCall<E, Op extends ApiOp = ApiOp> = Op extends ApiOp ? CallOf<E, Op> : never;
|
|
36
|
+
/** What a middleware hands on to: the next middleware, the querier last. */
|
|
37
|
+
export type ApiNext<E> = (call: ApiCall<E>) => Promise<unknown>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs around each call to one entity: reshape it before `next`, abort by throwing (a numeric `status` on the error
|
|
40
|
+
* is honored), or reshape what `next` resolves to, the result as the entity holds it. `context` is the transport's.
|
|
41
|
+
*/
|
|
42
|
+
export type EntityMiddleware<E, Ctx = unknown> = (call: ApiCall<E>, context: Ctx, next: ApiNext<E>) => Promise<unknown>;
|
|
43
|
+
/** A middleware run around a call to any entity, for what reads no entity's members: logging, timing, a refusal. */
|
|
44
|
+
export type ApiMiddleware<Ctx = unknown> = <E extends object>(call: ApiCall<E>, context: Ctx, next: ApiNext<E>) => Promise<unknown>;
|
|
45
|
+
/** Whether `call` is a call to `entity`, for a middleware typed by it. */
|
|
46
|
+
export declare function isCallOf<E extends object>(entity: Type<E>, call: ApiCall<object>): call is ApiCall<E>;
|
|
47
|
+
/** Runs `use` around `last`, first to last. */
|
|
48
|
+
export declare function chain<E, Ctx>(use: readonly EntityMiddleware<E, Ctx>[], context: Ctx, last: ApiNext<E>): ApiNext<E>;
|
|
49
|
+
type Decoded<E> = {
|
|
50
|
+
readonly entity: Type<E>;
|
|
51
|
+
readonly op: ApiOp;
|
|
52
|
+
readonly id?: string | number;
|
|
53
|
+
readonly query: Query<E> & WireCursors;
|
|
54
|
+
readonly payload: unknown;
|
|
55
|
+
readonly hardDelete: boolean;
|
|
56
|
+
};
|
|
57
|
+
/** The call `decoded` asks for, the id and the payload's shape its op needs checked. */
|
|
58
|
+
export declare function callOf<E extends object>({ op, id, payload, ...rest }: Decoded<E>): ApiCall<E>;
|
|
59
|
+
export {};
|