uql-orm 0.112.1 → 0.114.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 +2 -2
- 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/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definition.js +3 -0
- 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 +140 -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 +38 -0
- package/dist/http/exposure.js +157 -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/migrate/codegen/entityCodeGenerator.js +2 -2
- 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 +9 -1
- package/dist/type/definedEntity.d.ts +3 -0
- package/dist/type/entity.d.ts +14 -4
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +24 -4
- package/dist/type/universalQuerier.d.ts +17 -18
- package/dist/type/wire.d.ts +1 -31
- package/dist/util/dialect.util.d.ts +10 -10
- package/dist/util/dialect.util.js +20 -12
- package/dist/util/field.util.d.ts +7 -1
- package/dist/util/field.util.js +9 -2
- package/dist/util/fieldOption.util.js +2 -0
- 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 +32 -4
- 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,14 +143,14 @@ 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 HTTP](https://uql-orm.dev/http), scoped to the signed-in user by [filters no `$where` can widen](https://uql-orm.dev/multi-tenancy).
|
|
146
|
+
The same queries run from the browser too: [serve them over HTTP, 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
|
|
|
150
150
|
- **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node 22.18+, Bun, [Cloudflare Workers](https://uql-orm.dev/cloudflare-d1), [AWS Lambda and Vercel](https://uql-orm.dev/serverless), and [the browser](https://uql-orm.dev/browser), with no native binaries on the `fetch`-based drivers.
|
|
151
151
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
152
152
|
- **Decorators or plain data, your call.** An entity is a class with [standard TC39 decorators](https://uql-orm.dev/entities/basic), or plain data via [`defineEntity`](https://uql-orm.dev/entities/define-entity), its row type derived. Both are typed the same, mix in one project, and need no compiler flags or `reflect-metadata`.
|
|
153
|
-
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about
|
|
153
|
+
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 49 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
154
154
|
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), and [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches.
|
|
155
155
|
- **SQL when you need it.** [`sql()`](https://uql-orm.dev/querying/raw-sql) fits anywhere a value or a field goes, [computed fields](https://uql-orm.dev/entities/computed-fields) are SQL you can filter and sort on, and a migration can be plain SQL.
|
|
156
156
|
- **The fastest ORM.** On a full PostgreSQL round trip it adds the least over hand-written driver code of any ORM in our open-source [benchmark](https://github.com/rogerpadilla/ts-orm-benchmark), on Bun and Node alike. The same benchmark [scores the types](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) by compiling ordinary mistakes in each ORM's API: UQL is the only one that catches them all.
|
|
@@ -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} -
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
|
-
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance } from '../type/index.js';
|
|
2
|
+
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance, type Wire } from '../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
|
|
5
5
|
* `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
|
|
@@ -20,6 +20,7 @@ export declare class ColumnOptionsBuilder {
|
|
|
20
20
|
name(name: string): ColumnOptionsBuilder;
|
|
21
21
|
comment(comment: string): ColumnOptionsBuilder;
|
|
22
22
|
eager(eager: false): ColumnOptionsBuilder;
|
|
23
|
+
wire(wire: Wire): ColumnOptionsBuilder;
|
|
23
24
|
columnType(columnType: ColumnType): ColumnOptionsBuilder;
|
|
24
25
|
columnType(columnType: QuerySql): ColumnOptionsBuilder;
|
|
25
26
|
references(references: () => Type<object>): ColumnOptionsBuilder;
|
|
@@ -220,6 +220,7 @@ function settleEntity(entity) {
|
|
|
220
220
|
name: options.table,
|
|
221
221
|
schema: options.schema,
|
|
222
222
|
abstract: options.abstract,
|
|
223
|
+
wire: options.wire,
|
|
223
224
|
indexes: sections.indexes,
|
|
224
225
|
checks: sections.checks,
|
|
225
226
|
triggers: sections.triggers,
|
|
@@ -327,6 +328,7 @@ export function registerEntity(entity, opts = {}, members) {
|
|
|
327
328
|
meta.derivedName = opts.name === undefined;
|
|
328
329
|
meta.schema = opts.schema;
|
|
329
330
|
meta.abstract = opts.abstract;
|
|
331
|
+
meta.wire = opts.wire;
|
|
330
332
|
inheritFrom(meta, parentOf(entity));
|
|
331
333
|
if (!hasKeys(meta.fields)) {
|
|
332
334
|
throw new UqlUsageError(`'${entity.name}' must have fields`);
|
|
@@ -782,6 +784,7 @@ function extendMeta(target, source) {
|
|
|
782
784
|
}
|
|
783
785
|
}
|
|
784
786
|
target.fields = { ...sourceFields, ...target.fields };
|
|
787
|
+
target.wire ??= source.wire;
|
|
785
788
|
// Inherit user-defined filters from the parent (child overrides by name). The built-in soft-delete
|
|
786
789
|
// filter + `meta.softDelete` are (re)derived from the merged fields at registration.
|
|
787
790
|
if (source.filters) {
|
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. Each entity's `wire`
|
|
9
|
+
* says what a client may do to it; `serve(User, { use })` 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,140 @@
|
|
|
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 { exposedQuery, servedEntry } 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 entries = include.map(servedEntry);
|
|
24
|
+
const entities = entries.map(([entity]) => entity);
|
|
25
|
+
const served = new Map(entries);
|
|
26
|
+
const unwired = entities.filter((entity) => getMeta(entity).wire === false);
|
|
27
|
+
if (unwired.length) {
|
|
28
|
+
throw new UqlUsageError(`'wire: false' keeps ${unwired.map((entity) => `'${entity.name}'`).join(', ')} off every API: remove from 'include'`);
|
|
29
|
+
}
|
|
30
|
+
// All of them at once, so fixing the first collision does not just reveal the next.
|
|
31
|
+
const byPath = Map.groupBy(entities, pathOf);
|
|
32
|
+
const collisions = [...byPath].filter(([, clashing]) => clashing.length > 1);
|
|
33
|
+
if (collisions.length) {
|
|
34
|
+
const lines = collisions.map(([path, clashing]) => ` /${path} <- ${clashing.map(tableOf).join(', ')}`);
|
|
35
|
+
throw new UqlUsageError(`every entity below shares a path with another, so all but the first are unreachable:\n${lines.join('\n')}\n` +
|
|
36
|
+
"A path is the kebab-cased class name unless 'entityPath' says otherwise. Name them apart, " +
|
|
37
|
+
"pass an 'entityPath', or pass only one of them in 'include'.");
|
|
38
|
+
}
|
|
39
|
+
const entityByPath = new Map([...byPath].map(([path, [entity]]) => [path, entity]));
|
|
40
|
+
return {
|
|
41
|
+
serves: (path, op) => entityByPath.has(path) && isApiOp(op),
|
|
42
|
+
call: async (input, context) => {
|
|
43
|
+
const sent = parseWireCall(input);
|
|
44
|
+
const entity = entityByPath.get(sent.entity);
|
|
45
|
+
if (!entity) {
|
|
46
|
+
// A 404, as a route that names no entity is: the call is well formed, its entity is not here.
|
|
47
|
+
throw new UqlRequestError(`'${sent.entity}' is not an entity this API serves`, 404);
|
|
48
|
+
}
|
|
49
|
+
return run(entity, sent, context);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
async function run(entity, sent, context) {
|
|
53
|
+
const meta = getMeta(entity);
|
|
54
|
+
const shape = API_OPS[sent.op];
|
|
55
|
+
const call = decodedCall(entity, sent, served);
|
|
56
|
+
const appContext = contextOf ? ((await contextOf(context)) ?? {}) : (ambientContext() ?? {});
|
|
57
|
+
const around = served.get(entity);
|
|
58
|
+
const answer = () => chain(around ? [...use, around] : use, context, async (reshaped) => {
|
|
59
|
+
if (!isCallOf(entity, reshaped)) {
|
|
60
|
+
throw new UqlUsageError(`a middleware moved a call to '${entity.name}' to another entity`);
|
|
61
|
+
}
|
|
62
|
+
// Resolved after the middleware: one that aborts the call must not reach the pool at all.
|
|
63
|
+
const resolved = typeof pool === 'function' ? await pool(context, appContext) : pool;
|
|
64
|
+
// A read acquires and releases; a write is one transaction, so a failing cascade takes its parent with it.
|
|
65
|
+
const execute = (querier) => executeOn(querier, reshaped);
|
|
66
|
+
const pending = shape.access === 'read' ? resolved.withQuerier(execute) : resolved.transaction(execute);
|
|
67
|
+
return pending.catch(placedInQuery);
|
|
68
|
+
})(call);
|
|
69
|
+
// Scope the whole call (middleware, querier, relation and cascade queries) to the context `contextOf` resolved;
|
|
70
|
+
// without one, the call keeps the context its caller runs in.
|
|
71
|
+
const result = await (contextOf ? withContext(appContext, answer) : answer());
|
|
72
|
+
return writeWireData(meta, result, shape.answers);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The call `sent` asks of `entity` as the querier takes it: its query and payload read back as the entity holds them,
|
|
77
|
+
* checked against what its op takes and what the API exposes. Run on what the client sent, before any middleware, so
|
|
78
|
+
* what a middleware adds is the server's own to add.
|
|
79
|
+
*/
|
|
80
|
+
function decodedCall(entity, sent, served) {
|
|
81
|
+
const meta = getMeta(entity);
|
|
82
|
+
const { op } = sent;
|
|
83
|
+
const query = readWireQuery(meta, parseWireQuery(sent.query));
|
|
84
|
+
const payload = readWirePayload(meta, sent.payload);
|
|
85
|
+
return callOf({
|
|
86
|
+
entity,
|
|
87
|
+
op,
|
|
88
|
+
id: sent.id,
|
|
89
|
+
query: exposedQuery(meta, op, query, payload, served),
|
|
90
|
+
payload,
|
|
91
|
+
hardDelete: sent.hardDelete ?? false,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/** A querier's refusal names its place within the query it refused: within the call, that is under `query`. */
|
|
95
|
+
function placedInQuery(err) {
|
|
96
|
+
if (err instanceof UqlError && err.path) {
|
|
97
|
+
Object.defineProperty(err, 'path', { value: ['query', ...err.path] });
|
|
98
|
+
}
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
async function executeOn(querier, call) {
|
|
102
|
+
const { entity, query, hardDelete } = call;
|
|
103
|
+
/** The query scoped to the one row the call addresses. */
|
|
104
|
+
const byId = (id) => ({
|
|
105
|
+
...query,
|
|
106
|
+
$where: whereWith(soleIdOf(getMeta(entity), 'the API'), id, query.$where),
|
|
107
|
+
});
|
|
108
|
+
switch (call.op) {
|
|
109
|
+
case 'findOne':
|
|
110
|
+
return querier.findOne(entity, query);
|
|
111
|
+
case 'findOneById':
|
|
112
|
+
return querier.findOne(entity, byId(call.id));
|
|
113
|
+
case 'count':
|
|
114
|
+
return querier.count(entity, query);
|
|
115
|
+
case 'findMany':
|
|
116
|
+
return querier.findMany(entity, query);
|
|
117
|
+
case 'findManyAndCount':
|
|
118
|
+
return querier.findManyAndCount(entity, query);
|
|
119
|
+
case 'findManyPage':
|
|
120
|
+
assertPageable(getMeta(entity), query);
|
|
121
|
+
return querier.findManyPage(entity, query);
|
|
122
|
+
case 'insertOne':
|
|
123
|
+
return querier.insertOne(entity, call.payload);
|
|
124
|
+
case 'saveOne':
|
|
125
|
+
return querier.saveOne(entity, call.payload);
|
|
126
|
+
case 'insertMany':
|
|
127
|
+
return querier.insertMany(entity, call.payload);
|
|
128
|
+
case 'saveMany':
|
|
129
|
+
return querier.saveMany(entity, call.payload);
|
|
130
|
+
// A write answers how many rows it changed, and the querier still refuses a delete that names no rows.
|
|
131
|
+
case 'updateMany':
|
|
132
|
+
return querier.updateMany(entity, query, call.payload);
|
|
133
|
+
case 'updateOneById':
|
|
134
|
+
return querier.updateMany(entity, byId(call.id), call.payload);
|
|
135
|
+
case 'deleteMany':
|
|
136
|
+
return querier.deleteMany(entity, query, { hardDelete });
|
|
137
|
+
case 'deleteOneById':
|
|
138
|
+
return querier.deleteMany(entity, byId(call.id), { hardDelete });
|
|
139
|
+
}
|
|
140
|
+
}
|