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
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isRecord } from '../util/object.util.js';
|
|
2
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
3
|
+
/** Whether `call` is a call to `entity`, for a middleware typed by it. */
|
|
4
|
+
export function isCallOf(entity, call) {
|
|
5
|
+
return call.entity === entity;
|
|
6
|
+
}
|
|
7
|
+
/** Runs `use` around `last`, first to last. */
|
|
8
|
+
export function chain(use, context, last) {
|
|
9
|
+
return use.reduceRight((next, middleware) => (call) => middleware(call, context, next), last);
|
|
10
|
+
}
|
|
11
|
+
/** The call `decoded` asks for, the id and the payload's shape its op needs checked. */
|
|
12
|
+
export function callOf({ op, id, payload, ...rest }) {
|
|
13
|
+
switch (op) {
|
|
14
|
+
case 'insertOne':
|
|
15
|
+
case 'saveOne':
|
|
16
|
+
return { ...rest, op, payload: recordOf(payload) };
|
|
17
|
+
case 'insertMany':
|
|
18
|
+
case 'saveMany':
|
|
19
|
+
return { ...rest, op, payload: rowsOf(payload) };
|
|
20
|
+
case 'updateMany':
|
|
21
|
+
return { ...rest, op, payload: recordOf(payload) };
|
|
22
|
+
case 'updateOneById':
|
|
23
|
+
return { ...rest, op, id: idOf(op, id), payload: recordOf(payload) };
|
|
24
|
+
case 'findOneById':
|
|
25
|
+
case 'deleteOneById':
|
|
26
|
+
return { ...rest, op, id: idOf(op, id) };
|
|
27
|
+
default:
|
|
28
|
+
return { ...rest, op };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function idOf(op, id) {
|
|
32
|
+
if (id === undefined) {
|
|
33
|
+
throw new UqlUsageError(`'${op}' names the row it addresses in 'id'`, { path: ['id'] });
|
|
34
|
+
}
|
|
35
|
+
return id;
|
|
36
|
+
}
|
|
37
|
+
/** Whether `value` is a row, or changes to one, as JSON carries it: its fields are the querier's to check. */
|
|
38
|
+
function isRecordOf(value) {
|
|
39
|
+
return isRecord(value);
|
|
40
|
+
}
|
|
41
|
+
function recordOf(payload) {
|
|
42
|
+
if (!isRecordOf(payload)) {
|
|
43
|
+
throw new UqlUsageError('the payload must be a JSON object', { path: ['payload'] });
|
|
44
|
+
}
|
|
45
|
+
return payload;
|
|
46
|
+
}
|
|
47
|
+
function rowsOf(payload) {
|
|
48
|
+
if (!Array.isArray(payload) || !payload.every((row) => isRecordOf(row))) {
|
|
49
|
+
throw new UqlUsageError('the payload must be a JSON array of rows', { path: ['payload'] });
|
|
50
|
+
}
|
|
51
|
+
return payload;
|
|
52
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type QueryErrorKind, type UqlErrorPath } from '../util/uqlError.js';
|
|
2
|
+
/** A failure as JSON carries it: the HTTP status, what kind of failure it is, and where in the call it sits. */
|
|
3
|
+
export type RequestFailure = {
|
|
4
|
+
readonly message: string;
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly kind?: QueryErrorKind;
|
|
7
|
+
readonly path?: UqlErrorPath;
|
|
8
|
+
};
|
|
9
|
+
export type RequestErrorResponse = {
|
|
10
|
+
readonly error: RequestFailure;
|
|
11
|
+
};
|
|
12
|
+
/** What a transport answers: a status, a JSON body, and any header it calls for. */
|
|
13
|
+
export type HandlerResponse<Body = unknown> = {
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly body: Body;
|
|
16
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
17
|
+
};
|
|
18
|
+
export type ErrorResponse = HandlerResponse<RequestErrorResponse>;
|
|
19
|
+
/** A thrown error as the status, `{ error }` body and headers a transport answers with, a `UqlError`'s own headers included. */
|
|
20
|
+
export declare function toErrorResponse(err: unknown): ErrorResponse;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { queryErrorKind } from '../querier/queryError.js';
|
|
2
|
+
import { UqlError } from '../util/uqlError.js';
|
|
3
|
+
/** Generic on purpose: a driver's message names tables and constraints, and Postgres echoes the value. */
|
|
4
|
+
const KIND_ERRORS = new Map([
|
|
5
|
+
['uniqueViolation', 'Conflict', 409],
|
|
6
|
+
['foreignKeyViolation', 'Conflict', 409],
|
|
7
|
+
['notNullViolation', 'Bad Request', 400],
|
|
8
|
+
['checkViolation', 'Bad Request', 400],
|
|
9
|
+
['retryable', 'Service Unavailable', 503],
|
|
10
|
+
].map(([kind, message, status]) => [kind, { message, status, kind }]));
|
|
11
|
+
const INTERNAL_ERROR = { message: 'Internal Server Error', status: 500 };
|
|
12
|
+
/**
|
|
13
|
+
* `err` as a client may see it: a `UqlError` whole, anything else by its kind alone, generically. A `status` on any
|
|
14
|
+
* other error is not taken: an HTTP driver's (libSQL's) comes with a message naming tables.
|
|
15
|
+
*/
|
|
16
|
+
function failureOf(err) {
|
|
17
|
+
if (err instanceof UqlError) {
|
|
18
|
+
return { message: err.message, status: err.status, kind: err.kind, ...(err.path && { path: err.path }) };
|
|
19
|
+
}
|
|
20
|
+
return KIND_ERRORS.get(queryErrorKind(err)) ?? INTERNAL_ERROR;
|
|
21
|
+
}
|
|
22
|
+
/** A thrown error as the status, `{ error }` body and headers a transport answers with, a `UqlError`'s own headers included. */
|
|
23
|
+
export function toErrorResponse(err) {
|
|
24
|
+
const error = failureOf(err);
|
|
25
|
+
const headers = err instanceof UqlError ? err.headers : undefined;
|
|
26
|
+
return { status: error.status, body: { error }, ...(headers && { headers }) };
|
|
27
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { AbstractType, EntityAccess, EntityMeta, FieldAccess, FieldKey, RelationKey, Type } from '../type/index.js';
|
|
2
|
+
import { type EntityMiddleware } from './apiCall.js';
|
|
3
|
+
import { type ApiOp } from './wireCall.js';
|
|
4
|
+
/**
|
|
5
|
+
* What a client may do to an entity and each of its members, fields and relations: what is not listed takes every
|
|
6
|
+
* operation, and `false` takes none. The map is declared over `F`, so a rename follows and a typo does not compile.
|
|
7
|
+
*/
|
|
8
|
+
export type Exposure<E, F extends keyof E = FieldKey<E> | RelationKey<E>> = {
|
|
9
|
+
readonly ops?: readonly EntityAccess[];
|
|
10
|
+
readonly members?: {
|
|
11
|
+
readonly [K in F]?: false | readonly FieldAccess[];
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
/** An entity an API serves under an {@link Exposure}, as `include` lists it beside an entity served whole. */
|
|
15
|
+
export type Served<E, Ctx = unknown> = {
|
|
16
|
+
readonly entity: Type<E>;
|
|
17
|
+
readonly exposure: Exposure<E>;
|
|
18
|
+
/** Its middleware, run on its own calls alone, after the API's; none where it names none. */
|
|
19
|
+
readonly around?: EntityMiddleware<object, Ctx>;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Serve `entity` under `exposure`, in an API's `include`, with middleware of its own in `use`: typed by the entity,
|
|
23
|
+
* so it reads and writes its members, and run on the entity's own calls alone.
|
|
24
|
+
*/
|
|
25
|
+
export declare function serve<E extends object, Ctx = unknown>(entity: Type<E>, { use, ...exposure }: Exposure<E> & {
|
|
26
|
+
readonly use?: readonly EntityMiddleware<E, Ctx>[];
|
|
27
|
+
}): Served<E, Ctx>;
|
|
28
|
+
/** An exposure worked out once: an entity's operations, and the members it narrows, each to what it takes. */
|
|
29
|
+
type Policy = {
|
|
30
|
+
readonly ops: ReadonlySet<EntityAccess>;
|
|
31
|
+
readonly members: ReadonlyMap<string, ReadonlySet<FieldAccess>>;
|
|
32
|
+
};
|
|
33
|
+
export type Exposures = ReadonlyMap<AbstractType<object>, Policy>;
|
|
34
|
+
/** The entity an `include` item serves. */
|
|
35
|
+
export declare function entityOf<Ctx>(item: Type<object> | Served<object, Ctx>): Type<object>;
|
|
36
|
+
/** Each entity `include` lists, by its class, with what it takes. */
|
|
37
|
+
export declare function exposuresOf<Ctx>(include: readonly (Type<object> | Served<object, Ctx>)[]): Exposures;
|
|
38
|
+
/**
|
|
39
|
+
* Refuses what a client's call reaches that the API does not expose: the op on its entity, a relation to an entity
|
|
40
|
+
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
41
|
+
* keys of the entity it sits on.
|
|
42
|
+
*/
|
|
43
|
+
export declare function assertExposed<E extends object>(meta: EntityMeta<E>, op: ApiOp, query: object, payload: unknown, exposures: Exposures): void;
|
|
44
|
+
/**
|
|
45
|
+
* `query` reading none of what the API does not let be read, at every depth its `$populate` reaches. Run on a call
|
|
46
|
+
* {@link assertExposed} took, which names none of it: a projection naming the fields it reads stays as it is.
|
|
47
|
+
*/
|
|
48
|
+
export declare function hideUnreadable<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, query: Q, exposures: Exposures): Q;
|
|
49
|
+
/**
|
|
50
|
+
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
51
|
+
* answering rows, leaving out what it may not read.
|
|
52
|
+
*/
|
|
53
|
+
export declare function exposedQuery<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, op: ApiOp, query: Q, payload: unknown, exposures: Exposures): Q;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { getMeta } from '../entity/metadata/definition.js';
|
|
2
|
+
import { isCascadable } from '../util/dialect.util.js';
|
|
3
|
+
import { isFieldKey } from '../util/field.util.js';
|
|
4
|
+
import { isPlainObject, isRecord } from '../util/object.util.js';
|
|
5
|
+
import { UqlSecurityError } from '../util/uqlError.js';
|
|
6
|
+
import { chain, isCallOf } from './apiCall.js';
|
|
7
|
+
import { API_OPS } from './wireCall.js';
|
|
8
|
+
/**
|
|
9
|
+
* Serve `entity` under `exposure`, in an API's `include`, with middleware of its own in `use`: typed by the entity,
|
|
10
|
+
* so it reads and writes its members, and run on the entity's own calls alone.
|
|
11
|
+
*/
|
|
12
|
+
export function serve(entity, { use = [], ...exposure }) {
|
|
13
|
+
if (!use.length) {
|
|
14
|
+
return { entity, exposure };
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
entity,
|
|
18
|
+
exposure,
|
|
19
|
+
around: (call, context, next) => (isCallOf(entity, call) ? chain(use, context, next)(call) : next(call)),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const EVERY_OP = new Set(['read', 'insert', 'update', 'delete']);
|
|
23
|
+
/** The entity an `include` item serves. */
|
|
24
|
+
export function entityOf(item) {
|
|
25
|
+
return typeof item === 'function' ? item : item.entity;
|
|
26
|
+
}
|
|
27
|
+
/** Each entity `include` lists, by its class, with what it takes. */
|
|
28
|
+
export function exposuresOf(include) {
|
|
29
|
+
return new Map(include.map((item) => {
|
|
30
|
+
const entity = entityOf(item);
|
|
31
|
+
const exposure = typeof item === 'function' ? {} : item.exposure;
|
|
32
|
+
const members = Object.entries(exposure.members ?? {}).map(([key, takes]) => [key, new Set(takes || [])]);
|
|
33
|
+
return [entity, { ops: exposure.ops ? new Set(exposure.ops) : EVERY_OP, members: new Map(members) }];
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
const PAST = {
|
|
37
|
+
read: 'read',
|
|
38
|
+
insert: 'inserted',
|
|
39
|
+
update: 'updated',
|
|
40
|
+
delete: 'deleted',
|
|
41
|
+
};
|
|
42
|
+
/** What a save does to the rows it writes, as a cascade does to the rows a write nests: inserts new ones, updates listed ones. */
|
|
43
|
+
const SAVED = ['insert', 'update'];
|
|
44
|
+
/** What `op` does to the rows it writes, a save doing either. */
|
|
45
|
+
function writesOf(op) {
|
|
46
|
+
const { access } = API_OPS[op];
|
|
47
|
+
return access === 'save' ? SAVED : access === 'insert' || access === 'update' ? [access] : [];
|
|
48
|
+
}
|
|
49
|
+
/** The relation `key` names on `meta`, a client's key included: an own key alone, never one of `Object`'s. */
|
|
50
|
+
function relationAt(meta, key) {
|
|
51
|
+
const relations = meta.relations;
|
|
52
|
+
return Object.hasOwn(relations, key) ? relations[key] : undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Refuses what a client's call reaches that the API does not expose: the op on its entity, a relation to an entity
|
|
56
|
+
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
57
|
+
* keys of the entity it sits on.
|
|
58
|
+
*/
|
|
59
|
+
export function assertExposed(meta, op, query, payload, exposures) {
|
|
60
|
+
const { access } = API_OPS[op];
|
|
61
|
+
const writes = writesOf(op);
|
|
62
|
+
assertOps(meta, access === 'save' ? writes : [access], exposures);
|
|
63
|
+
walk(meta, query, ['read'], exposures, ['query']);
|
|
64
|
+
walk(meta, payload, writes, exposures, ['payload']);
|
|
65
|
+
}
|
|
66
|
+
/** An entity the API does not serve takes nothing. */
|
|
67
|
+
const DENIED = { ops: new Set(), members: new Map() };
|
|
68
|
+
function policyOf(meta, exposures) {
|
|
69
|
+
return exposures.get(meta.entity) ?? DENIED;
|
|
70
|
+
}
|
|
71
|
+
function assertOps(meta, needs, exposures, path) {
|
|
72
|
+
const missing = needs.find((need) => !policyOf(meta, exposures).ops.has(need));
|
|
73
|
+
if (missing) {
|
|
74
|
+
throw new UqlSecurityError(`'${meta.entity.name}' cannot be ${PAST[missing]} through this API`, { path });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** The members `path` names, as a refusal reads them: `author.email`, not its clauses and indexes. */
|
|
78
|
+
function membersOf(path) {
|
|
79
|
+
return path
|
|
80
|
+
.slice(1)
|
|
81
|
+
.filter((key) => typeof key === 'string' && !key.startsWith('$'))
|
|
82
|
+
.join('.');
|
|
83
|
+
}
|
|
84
|
+
function walk(meta, sent, needs, exposures, path) {
|
|
85
|
+
if (Array.isArray(sent)) {
|
|
86
|
+
sent.forEach((item, index) => walk(meta, item, needs, exposures, [...path, index]));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (!isRecord(sent)) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const { members } = policyOf(meta, exposures);
|
|
93
|
+
const writing = !needs.includes('read');
|
|
94
|
+
for (const [key, value] of Object.entries(sent)) {
|
|
95
|
+
if (key.startsWith('$')) {
|
|
96
|
+
walk(meta, value, needs, exposures, [...path, key]);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
// A JSON path (`kind.plan`) reads the member it starts at.
|
|
100
|
+
const [member] = key.split('.');
|
|
101
|
+
const relation = relationAt(meta, member);
|
|
102
|
+
if (!relation && !isFieldKey(meta, member)) {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const at = [...path, key];
|
|
106
|
+
const takes = members.get(member);
|
|
107
|
+
const missing = takes && needs.find((need) => !takes.has(need));
|
|
108
|
+
if (missing) {
|
|
109
|
+
throw new UqlSecurityError(`'${membersOf(at)}' cannot be ${PAST[missing]} through this API`, { path: at });
|
|
110
|
+
}
|
|
111
|
+
// The querier writes a relation a payload names only where it cascades, saving its rows whatever the op.
|
|
112
|
+
if (relation && (!writing || isCascadable('persist', relation.cascade))) {
|
|
113
|
+
const target = getMeta(relation.entity());
|
|
114
|
+
if (!exposures.has(target.entity)) {
|
|
115
|
+
throw new UqlSecurityError(`'${membersOf(at)}' reaches '${target.entity.name}', which this API does not serve`, { path: at });
|
|
116
|
+
}
|
|
117
|
+
const nested = writing ? SAVED : needs;
|
|
118
|
+
// An update of a to-many replaces its rows: those it stops listing are deleted.
|
|
119
|
+
const replaces = relation.cardinality === '1m' && needs.includes('update');
|
|
120
|
+
assertOps(target, replaces ? [...nested, 'delete'] : nested, exposures, at);
|
|
121
|
+
walk(target, value, nested, exposures, at);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** What a projection of `meta` leaves out because the API does not let it be read: its fields alone, never a relation. */
|
|
126
|
+
function unreadableOf(meta, exposures) {
|
|
127
|
+
const { members } = policyOf(meta, exposures);
|
|
128
|
+
return [...members].filter(([key, takes]) => !takes.has('read') && isFieldKey(meta, key)).map(([key]) => key);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* `query` reading none of what the API does not let be read, at every depth its `$populate` reaches. Run on a call
|
|
132
|
+
* {@link assertExposed} took, which names none of it: a projection naming the fields it reads stays as it is.
|
|
133
|
+
*/
|
|
134
|
+
export function hideUnreadable(meta, query, exposures) {
|
|
135
|
+
const hidden = unreadableOf(meta, exposures);
|
|
136
|
+
const select = query['$select'];
|
|
137
|
+
const leavesOut = select === undefined || (isPlainObject(select) && Object.values(select).every((value) => !value));
|
|
138
|
+
const $select = hidden.length && leavesOut
|
|
139
|
+
? { ...(isPlainObject(select) && select), ...Object.fromEntries(hidden.map((key) => [key, false])) }
|
|
140
|
+
: select;
|
|
141
|
+
const $populate = isPlainObject(query['$populate'])
|
|
142
|
+
? populateOf(meta, query['$populate'], exposures)
|
|
143
|
+
: query['$populate'];
|
|
144
|
+
if ($select === select && $populate === query['$populate']) {
|
|
145
|
+
return query;
|
|
146
|
+
}
|
|
147
|
+
return { ...query, ...($select !== undefined && { $select }), ...($populate !== undefined && { $populate }) };
|
|
148
|
+
}
|
|
149
|
+
function populateOf(meta, populate, exposures) {
|
|
150
|
+
let changed = false;
|
|
151
|
+
const entries = Object.entries(populate).map(([key, nested]) => {
|
|
152
|
+
const relation = relationAt(meta, key);
|
|
153
|
+
if (!relation || !nested) {
|
|
154
|
+
return [key, nested];
|
|
155
|
+
}
|
|
156
|
+
const read = hideUnreadable(getMeta(relation.entity()), isPlainObject(nested) ? nested : {}, exposures);
|
|
157
|
+
const hid = isPlainObject(nested) ? read !== nested : Object.keys(read).length > 0;
|
|
158
|
+
changed ||= hid;
|
|
159
|
+
return [key, hid ? read : nested];
|
|
160
|
+
});
|
|
161
|
+
return changed ? Object.fromEntries(entries) : populate;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
165
|
+
* answering rows, leaving out what it may not read.
|
|
166
|
+
*/
|
|
167
|
+
export function exposedQuery(meta, op, query, payload, exposures) {
|
|
168
|
+
assertExposed(meta, op, query, payload, exposures);
|
|
169
|
+
const { access, answers } = API_OPS[op];
|
|
170
|
+
return access === 'read' && answers !== 'count' ? hideUnreadable(meta, query, exposures) : query;
|
|
171
|
+
}
|
package/dist/http/handler.d.ts
CHANGED
|
@@ -1,92 +1,27 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type
|
|
3
|
-
import { type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
readonly method: string;
|
|
10
|
-
readonly entityPath: string;
|
|
11
|
-
readonly subPath?: string;
|
|
12
|
-
/**
|
|
13
|
-
* raw query-string entries; JSON values may still be stringified.
|
|
14
|
-
*/
|
|
15
|
-
readonly query?: Record<string, unknown>;
|
|
16
|
-
/**
|
|
17
|
-
* parsed JSON body.
|
|
18
|
-
*/
|
|
19
|
-
readonly body?: unknown;
|
|
20
|
-
/**
|
|
21
|
-
* adapter-supplied request context (express `req`, fetch `Request`, ...), passed through to hooks.
|
|
22
|
-
*/
|
|
23
|
-
readonly context: Ctx;
|
|
24
|
-
};
|
|
25
|
-
export type HandlerResponse = {
|
|
26
|
-
readonly status: number;
|
|
27
|
-
readonly body: unknown;
|
|
28
|
-
};
|
|
29
|
-
export type RequestHookContext<E extends object, Ctx = unknown> = {
|
|
30
|
-
readonly meta: EntityMeta<E>;
|
|
31
|
-
readonly op: CrudOperation;
|
|
32
|
-
readonly method: HttpMethod;
|
|
33
|
-
/** The parsed query, to reshape in place. Scope rows with a `security` filter instead, which a client cannot override. */
|
|
34
|
-
query: Query<E> & WireFlags & WireCursors;
|
|
35
|
-
/**
|
|
36
|
-
* request payload - reassignable for sanitization or field injection.
|
|
37
|
-
*/
|
|
38
|
-
body?: unknown;
|
|
39
|
-
/**
|
|
40
|
-
* adapter-supplied request context - the auth/tenant source (e.g. `req.user`).
|
|
41
|
-
*/
|
|
1
|
+
import type { Api } from './api.js';
|
|
2
|
+
import { type HandlerResponse } from './errors.js';
|
|
3
|
+
import { type HttpRequest } from './route.js';
|
|
4
|
+
import type { ApiOp } from './wireCall.js';
|
|
5
|
+
/** A request to `/{entityPath}/{op}` as a framework adapter reduces it, with what `contextOf` and middleware get. */
|
|
6
|
+
export type HandlerRequest<Ctx = unknown> = Omit<HttpRequest, 'op'> & {
|
|
7
|
+
readonly op: string;
|
|
8
|
+
/** The adapter's own request (express `req`, fetch `Request`, ...): the auth and tenant source. */
|
|
42
9
|
readonly context: Ctx;
|
|
43
10
|
};
|
|
44
|
-
export type RequestHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>) => void | Promise<void>;
|
|
45
|
-
export type ResponseHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>, envelope: RequestSuccessResponse<unknown>) => void | Promise<void>;
|
|
46
|
-
export type RequestHandlerOptions<Ctx = unknown> = {
|
|
47
|
-
/**
|
|
48
|
-
* The entities served, and the only ones a request reaches, through a relation too: nothing is served
|
|
49
|
-
* by being defined, so an entity holding secrets (a session's token) stays off the wire unless named.
|
|
50
|
-
*/
|
|
51
|
-
include: readonly Type<object>[];
|
|
52
|
-
/** The URL segment an entity is addressed by, its kebab-cased class name by default; the browser client takes the same option. */
|
|
53
|
-
entityPath?: (entity: AbstractType<unknown>) => string;
|
|
54
|
-
/**
|
|
55
|
-
* Allow augment any kind of request before it runs. Hooks may be async
|
|
56
|
-
* and abort the request by throwing (a numeric `status` on the error is honored).
|
|
57
|
-
*/
|
|
58
|
-
pre?: RequestHook<Ctx>;
|
|
59
|
-
/**
|
|
60
|
-
* Allow augment a save request (POST | PUT | PATCH) before it runs.
|
|
61
|
-
*/
|
|
62
|
-
preSave?: RequestHook<Ctx>;
|
|
63
|
-
/**
|
|
64
|
-
* Allow augment a filter request (GET | DELETE) before it runs.
|
|
65
|
-
*/
|
|
66
|
-
preFilter?: RequestHook<Ctx>;
|
|
67
|
-
/**
|
|
68
|
-
* Shape the successful response before it is sent: strip sensitive fields,
|
|
69
|
-
* derive presentation fields, or coerce null data. Mutate `envelope.data` in place
|
|
70
|
-
* or reassign it. Runs after the operation (and after commit for writes).
|
|
71
|
-
*/
|
|
72
|
-
post?: ResponseHook<Ctx>;
|
|
73
|
-
/**
|
|
74
|
-
* Derive the ambient {@link UqlContext} (e.g. `{ tenantId, userId }`) from the adapter request.
|
|
75
|
-
* The whole request runs inside `withContext`, so parameterized/`security` filters are scoped
|
|
76
|
-
* automatically. Derive tenant/auth from a verified source (session, JWT) - never trust the client.
|
|
77
|
-
*/
|
|
78
|
-
getContext?: (context: Ctx) => UqlContext | undefined | Promise<UqlContext | undefined>;
|
|
79
|
-
/**
|
|
80
|
-
* The pool this handler runs on. A function is called per request, after `getContext`, with the
|
|
81
|
-
* adapter's request and the context that resolved from it - which is what lets one deployment
|
|
82
|
-
* serve a database per tenant, where a process-wide default could only serve one.
|
|
83
|
-
*/
|
|
84
|
-
pool: QuerierPool | ((context: Ctx, appContext: UqlContext) => QuerierPool | Promise<QuerierPool>);
|
|
85
|
-
};
|
|
86
11
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
|
|
12
|
+
* Answers a request with a status and a JSON body, a failure included, or `undefined` for an entity or an op the API
|
|
13
|
+
* does not serve, so an adapter can fall through (express `next()`).
|
|
14
|
+
*/
|
|
15
|
+
export type RequestHandler<Ctx = unknown> = (req: HandlerRequest<Ctx>) => Promise<HandlerResponse | undefined>;
|
|
16
|
+
/** The API over HTTP for any framework: mount it on `{base}/:entityPath/:op`, e.g. `/api/v1/:entityPath/:op`. */
|
|
17
|
+
export declare function toRequestHandler<Ctx>(api: Api<Ctx>): RequestHandler<Ctx>;
|
|
18
|
+
/** Answers a request to an op the API serves (`api.serves`) with a status and a JSON body, a failure included. */
|
|
19
|
+
export declare function answerRequest<Ctx>(api: Api<Ctx>, { context, ...req }: HandlerRequest<Ctx> & {
|
|
20
|
+
readonly op: ApiOp;
|
|
21
|
+
}): Promise<HandlerResponse>;
|
|
22
|
+
/**
|
|
23
|
+
* The API as `(request: Request) => Promise<Response>`, for any fetch-native runtime (Hono, Next.js route handlers,
|
|
24
|
+
* Bun.serve, Cloudflare Workers, SvelteKit, Astro), handing the `Request` to the API as its context. Mount it on a
|
|
25
|
+
* catch-all under the API's base: it reads the last two segments of the path as the entity and the op.
|
|
90
26
|
*/
|
|
91
|
-
export
|
|
92
|
-
export declare function createRequestHandler<Ctx = unknown>(opts: RequestHandlerOptions<Ctx>): RequestHandler<Ctx>;
|
|
27
|
+
export declare function toFetchHandler(api: Api<Request>): (request: Request) => Promise<Response>;
|