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/dist/type/column.d.ts
CHANGED
|
@@ -111,7 +111,10 @@ export interface ColumnBuilder<in out O, in out V, F extends Family> extends Col
|
|
|
111
111
|
comment(text: string): With<O, V, {
|
|
112
112
|
readonly comment: string;
|
|
113
113
|
}, F>;
|
|
114
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Leaves the column out of a read naming no fields. A read naming it still gets it, so it keeps no secret from a
|
|
116
|
+
* client: an API's `serve(Entity, { members: { field: false } })` does.
|
|
117
|
+
*/
|
|
115
118
|
eager(eager: false): With<O, V, {
|
|
116
119
|
readonly eager: false;
|
|
117
120
|
}, F>;
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -46,11 +46,11 @@ export type EngineName = (typeof ENGINE_NAMES)[DialectName] | 'Cloudflare D1' |
|
|
|
46
46
|
* **first** on purpose: when no signature matches, TypeScript reports the error of the *last* one, so a
|
|
47
47
|
* typo'd query key is reported as itself rather than as a missing `$entity`.
|
|
48
48
|
*/
|
|
49
|
-
type DualRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<
|
|
49
|
+
type DualRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<unknown>> = (<E extends object, const Q extends ReadQueries<E, QuerySql>[K] & {
|
|
50
50
|
$entity: Type<E>;
|
|
51
51
|
}>(q: Captured<ReadQueries<E, QuerySql>[K] & {
|
|
52
52
|
$entity: Type<E>;
|
|
53
|
-
}, Q>, opts?: QueryOptions) => ReadResults<
|
|
53
|
+
}, Q>, opts?: QueryOptions) => ReadResults<QueryFindResult<E, Q>>[R]) & EntityRead<K, R, 'server', QueryOptions>;
|
|
54
54
|
/** Each method below taking a query takes the entity first or as the query's `$entity`, as {@link DualRead} does. */
|
|
55
55
|
export interface Querier extends UniversalQuerier {
|
|
56
56
|
findOne: DualRead<'one', 'one'>;
|
package/dist/type/query.d.ts
CHANGED
|
@@ -24,11 +24,15 @@ export type QueryOptions = {
|
|
|
24
24
|
unfiltered?: boolean;
|
|
25
25
|
};
|
|
26
26
|
/**
|
|
27
|
-
* What a statement
|
|
28
|
-
*
|
|
29
|
-
* and none of this is a caller's to set: an alias is the dialect's to choose and to spell.
|
|
27
|
+
* What a statement runs with, on top of the options its caller passed. Kept apart from {@link QueryOptions}
|
|
28
|
+
* because that one is public, the third argument of every querier method, and none of this is a caller's to set.
|
|
30
29
|
*/
|
|
31
|
-
export type
|
|
30
|
+
export type StatementOptions = QueryOptions & {
|
|
31
|
+
/** What the statement does, which picks the `security` filters scoping it: a read by default. A write's reads take its own. */
|
|
32
|
+
readonly access?: EntityAccess;
|
|
33
|
+
};
|
|
34
|
+
/** What a statement is rendered with: an alias is the dialect's to choose and to spell. */
|
|
35
|
+
export type QueryRenderOptions = StatementOptions & {
|
|
32
36
|
/** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */
|
|
33
37
|
prefix?: string;
|
|
34
38
|
/**
|
|
@@ -106,6 +110,10 @@ export type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined)
|
|
|
106
110
|
* `throw` fails closed (the default for `security` filters).
|
|
107
111
|
*/
|
|
108
112
|
export type FilterOnMissing = 'skip' | 'throw';
|
|
113
|
+
/** What a field takes: reading it (select, filter, sort, distinct, aggregate) and writing it. */
|
|
114
|
+
export type FieldAccess = 'read' | 'insert' | 'update';
|
|
115
|
+
/** What a statement does to an entity's rows: a field's access, and deleting rows, which no field has a part in. */
|
|
116
|
+
export type EntityAccess = FieldAccess | 'delete';
|
|
109
117
|
/**
|
|
110
118
|
* Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.
|
|
111
119
|
*/
|
|
@@ -117,6 +125,7 @@ export type FilterOptions<E = unknown> = {
|
|
|
117
125
|
readonly security?: false;
|
|
118
126
|
/** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */
|
|
119
127
|
readonly onMissing?: FilterOnMissing;
|
|
128
|
+
readonly ops?: never;
|
|
120
129
|
} | {
|
|
121
130
|
/**
|
|
122
131
|
* Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and
|
|
@@ -124,6 +133,11 @@ export type FilterOptions<E = unknown> = {
|
|
|
124
133
|
*/
|
|
125
134
|
readonly security: true;
|
|
126
135
|
readonly onMissing?: 'throw';
|
|
136
|
+
/**
|
|
137
|
+
* The statements it holds, every one by default: `['insert', 'update', 'delete']` lets anyone read a row
|
|
138
|
+
* and only its author write it. An update or a delete reads the rows it changes, so read ones hold it too.
|
|
139
|
+
*/
|
|
140
|
+
readonly ops?: readonly EntityAccess[];
|
|
127
141
|
});
|
|
128
142
|
/**
|
|
129
143
|
* direction for the sort, and where nulls land in it.
|
|
@@ -2,33 +2,33 @@ import type { EntityId, EntityWrite, FieldKey, UpdateWrite } from './entity.js';
|
|
|
2
2
|
import type { Captured, CursorPage, Query, QueryUpsert, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, WriteResults, WriteOptions } from './query.js';
|
|
3
3
|
import type { QueryAggregate, QueryAggregateResult } from './queryAggregate.js';
|
|
4
4
|
import type { BooleanLike, Type } from './utility.js';
|
|
5
|
-
import type {
|
|
5
|
+
import type { QuerierSql, QuerierTransport } from './wire.js';
|
|
6
6
|
/** The query each read takes, keyed by the kind of read. */
|
|
7
7
|
export type ReadQueries<E, Sql> = {
|
|
8
8
|
readonly one: QueryOne<E, Sql>;
|
|
9
9
|
readonly many: Query<E, Sql>;
|
|
10
10
|
readonly page: QueryKeyset<E, Sql>;
|
|
11
11
|
};
|
|
12
|
-
/** The result type of each read
|
|
13
|
-
export type ReadResults<
|
|
14
|
-
readonly one:
|
|
15
|
-
readonly many:
|
|
16
|
-
readonly counted:
|
|
17
|
-
readonly page:
|
|
12
|
+
/** The result type of each read, keyed by the kind of read: alike on the server and the client. */
|
|
13
|
+
export type ReadResults<T> = {
|
|
14
|
+
readonly one: Promise<T | undefined>;
|
|
15
|
+
readonly many: Promise<T[]>;
|
|
16
|
+
readonly counted: Promise<[T[], number]>;
|
|
17
|
+
readonly page: Promise<CursorPage<T>>;
|
|
18
18
|
readonly stream: AsyncIterable<T>;
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
21
|
* A read that takes the entity first, then the query, and returns rows narrowed to what the query projected. `K` picks
|
|
22
|
-
* the query type, `R` the result type
|
|
22
|
+
* the query type, `R` the result type, `W` the transport, whose SQL its queries may carry, and `O` the options.
|
|
23
23
|
*/
|
|
24
|
-
export type EntityRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<
|
|
24
|
+
export type EntityRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<unknown>, W extends QuerierTransport, O> = <E extends object, const Q extends ReadQueries<E, QuerierSql<W>>[K]>(entity: Type<E>, q: Captured<ReadQueries<E, QuerierSql<W>>[K], Q>, opts?: O) => ReadResults<QueryFindResult<E, Q>>[R];
|
|
25
25
|
/**
|
|
26
26
|
* The operations the server and the browser client declare alike, per transport `W`, options `O`,
|
|
27
27
|
* and delete options `DO`, which on the client also carry the {@link QueryOptions} it cannot pass otherwise.
|
|
28
28
|
*/
|
|
29
29
|
export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
|
|
30
30
|
/** Find the record with the given primary key. */
|
|
31
|
-
findOneById<E extends object, const Q extends QueryOne<E, QuerierSql<W>> = {}>(entity: Type<E>, id: EntityId<E>, q?: Captured<QueryOne<E, QuerierSql<W>>, Q>, opts?: O):
|
|
31
|
+
findOneById<E extends object, const Q extends QueryOne<E, QuerierSql<W>> = {}>(entity: Type<E>, id: EntityId<E>, q?: Captured<QueryOne<E, QuerierSql<W>>, Q>, opts?: O): Promise<QueryFindResult<E, Q> | undefined>;
|
|
32
32
|
/**
|
|
33
33
|
* obtains the first record matching the given search parameters.
|
|
34
34
|
* @param entity the target entity
|
|
@@ -52,27 +52,27 @@ export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
|
|
|
52
52
|
*/
|
|
53
53
|
findManyPage: EntityRead<'page', 'page', W, O>;
|
|
54
54
|
/** Count the records matching the filter, or those a page of them takes. */
|
|
55
|
-
count<E extends object>(entity: Type<E>, q?: QueryPage<E, QuerierSql<W>>, opts?: O):
|
|
55
|
+
count<E extends object>(entity: Type<E>, q?: QueryPage<E, QuerierSql<W>>, opts?: O): Promise<number>;
|
|
56
56
|
/** Whether any record matches: a count capped at one row, so the engine stops at the first match. */
|
|
57
|
-
exists<E extends object>(entity: Type<E>, q?: QueryFilter<E, QuerierSql<W>>, opts?: O):
|
|
57
|
+
exists<E extends object>(entity: Type<E>, q?: QueryFilter<E, QuerierSql<W>>, opts?: O): Promise<boolean>;
|
|
58
58
|
/** Update the record with the given primary key; resolves to the number of affected rows. */
|
|
59
|
-
updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O):
|
|
59
|
+
updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): Promise<number>;
|
|
60
60
|
/** Update the records matching the query; resolves to the number of affected rows. */
|
|
61
|
-
updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O):
|
|
61
|
+
updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): Promise<number>;
|
|
62
62
|
/**
|
|
63
63
|
* delete or SoftDelete a record.
|
|
64
64
|
* @param entity the entity to persist on
|
|
65
65
|
* @param id the primary key of the record
|
|
66
66
|
* @return the number of affected records
|
|
67
67
|
*/
|
|
68
|
-
deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: DO):
|
|
68
|
+
deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: DO): Promise<number>;
|
|
69
69
|
/**
|
|
70
70
|
* delete or SoftDelete records.
|
|
71
71
|
* @param entity the entity to persist on
|
|
72
72
|
* @param q the criteria to look for the records
|
|
73
73
|
* @return the number of affected records
|
|
74
74
|
*/
|
|
75
|
-
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, opts?: DO):
|
|
75
|
+
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, opts?: DO): Promise<number>;
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
78
|
* A `querier` allows to interact with the datasource to perform persistence operations on any entity.
|
package/dist/type/wire.d.ts
CHANGED
|
@@ -1,20 +1,6 @@
|
|
|
1
1
|
import type { QuerySql } from './querySql.js';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*/
|
|
5
|
-
export type RequestSuccessResponse<E> = {
|
|
6
|
-
data: E;
|
|
7
|
-
count?: number;
|
|
8
|
-
};
|
|
9
|
-
/**
|
|
10
|
-
* A {@link RequestSuccessResponse} whose `count` is always present - what `findManyAndCount` sends.
|
|
11
|
-
*/
|
|
12
|
-
export type RequestCountedSuccessResponse<E> = RequestSuccessResponse<E> & {
|
|
13
|
-
count: number;
|
|
14
|
-
};
|
|
15
|
-
/**
|
|
16
|
-
* Which side of the wire a querier sits on. A server querier hands the result back directly, a
|
|
17
|
-
* client one hands back the envelope its transport wrapped it in.
|
|
3
|
+
* Which side of the wire a querier sits on, which says what SQL its queries may carry: both answer alike.
|
|
18
4
|
*/
|
|
19
5
|
export type QuerierTransport = 'server' | 'client';
|
|
20
6
|
/**
|
|
@@ -25,19 +11,3 @@ export type QuerierSql<W extends QuerierTransport> = {
|
|
|
25
11
|
server: QuerySql;
|
|
26
12
|
client: never;
|
|
27
13
|
}[W];
|
|
28
|
-
/**
|
|
29
|
-
* A querier method's result on a transport: `Promise<User[]>` on the server, the response envelope on
|
|
30
|
-
* the client. A map indexed by the transport, which resolves away in hovers.
|
|
31
|
-
*/
|
|
32
|
-
export type QuerierResult<W extends QuerierTransport, T> = {
|
|
33
|
-
server: Promise<T>;
|
|
34
|
-
client: Promise<RequestSuccessResponse<T>>;
|
|
35
|
-
}[W];
|
|
36
|
-
/**
|
|
37
|
-
* `findManyAndCount`'s result: the one shape the transports disagree on past the envelope, a tuple
|
|
38
|
-
* on the server against a counted envelope on the client.
|
|
39
|
-
*/
|
|
40
|
-
export type QuerierCountedResult<W extends QuerierTransport, T> = {
|
|
41
|
-
server: Promise<[T[], number]>;
|
|
42
|
-
client: Promise<RequestCountedSuccessResponse<T[]>>;
|
|
43
|
-
}[W];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexType } from '../schema/types.js';
|
|
2
|
-
import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
|
|
2
|
+
import { type AggregateCall, type CascadeType, type EntityAccess, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type StatementOptions, type UpdatePayload, type VectorDistance } from '../type/index.js';
|
|
3
3
|
export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
|
|
4
4
|
/** The keys of `payload` a write persists as columns. */
|
|
5
5
|
export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
|
|
@@ -135,12 +135,12 @@ export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof
|
|
|
135
135
|
* `$where` with the entity's active filters merged in, against the ambient {@link UqlContext}. A convenience
|
|
136
136
|
* filter yields to a `$where` on its key; a `security` one is always ANDed, from {@link securityConditions}.
|
|
137
137
|
*/
|
|
138
|
-
export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?:
|
|
138
|
+
export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
|
|
139
139
|
/**
|
|
140
|
-
*
|
|
141
|
-
* `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
|
|
140
|
+
* The condition of each `security` filter holding any of `accesses`, by name, resolved against the ambient context.
|
|
141
|
+
* One resolving to `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
|
|
142
142
|
*/
|
|
143
|
-
export declare function securityConditions<E>(meta: EntityMeta<E
|
|
143
|
+
export declare function securityConditions<E>(meta: EntityMeta<E>, accesses: readonly EntityAccess[]): [name: string, condition: QueryWhere<E>][];
|
|
144
144
|
/**
|
|
145
145
|
* Holds written rows to the `security` filters, as {@link applyFilters} holds reads: an inserted row gets
|
|
146
146
|
* each field a condition names and it leaves out, and a row naming one must carry the condition's value.
|
|
@@ -181,10 +181,10 @@ export declare function parseGroupMap<E>(group?: QueryGroupMap<E>, select?: Quer
|
|
|
181
181
|
/** A JSON object, matched by what it holds: a plain object with no operator key. */
|
|
182
182
|
export declare function isJsonObject(value: unknown): value is Record<string, unknown>;
|
|
183
183
|
/**
|
|
184
|
-
* A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
184
|
+
* A page operand, checked before it reaches an engine. These arrive from page arithmetic and from a
|
|
185
|
+
* client's call, where JSON carries a fraction or a negative alike, and each engine's own complaint
|
|
186
|
+
* names neither the clause nor the value - or, for `$limit: 0`, quietly means something else.
|
|
187
|
+
* Shared so every backend rejects the same input.
|
|
188
188
|
*/
|
|
189
189
|
export declare function assertNonNegativeInteger(value: number, clause: string): number;
|
|
190
190
|
/**
|
|
@@ -433,16 +433,24 @@ export function applyFilters(meta, whereMap, opts) {
|
|
|
433
433
|
}
|
|
434
434
|
}
|
|
435
435
|
const merged = result;
|
|
436
|
-
const security = securityConditions(meta).map(([, condition]) => condition);
|
|
436
|
+
const security = securityConditions(meta, SCOPED_BY[opts?.access ?? 'read']).map(([, condition]) => condition);
|
|
437
437
|
return security.length ? whereAnd(merged, security) : merged;
|
|
438
438
|
}
|
|
439
|
+
/** The accesses whose `security` filters scope a statement: an update or a delete reads the rows it changes too. */
|
|
440
|
+
const SCOPED_BY = {
|
|
441
|
+
read: ['read'],
|
|
442
|
+
insert: ['insert'],
|
|
443
|
+
update: ['read', 'update'],
|
|
444
|
+
delete: ['read', 'delete'],
|
|
445
|
+
};
|
|
439
446
|
/**
|
|
440
|
-
*
|
|
441
|
-
* `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
|
|
447
|
+
* The condition of each `security` filter holding any of `accesses`, by name, resolved against the ambient context.
|
|
448
|
+
* One resolving to `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
|
|
442
449
|
*/
|
|
443
|
-
export function securityConditions(meta) {
|
|
450
|
+
export function securityConditions(meta, accesses) {
|
|
444
451
|
return Object.entries(meta.filters ?? {}).flatMap(([name, filter]) => {
|
|
445
|
-
const
|
|
452
|
+
const holds = filter.security && (!filter.ops || filter.ops.some((op) => accesses.includes(op)));
|
|
453
|
+
const condition = holds ? resolveFilter(meta, name, filter) : undefined;
|
|
446
454
|
return condition && hasKeys(condition) ? [[name, condition]] : [];
|
|
447
455
|
});
|
|
448
456
|
}
|
|
@@ -462,7 +470,7 @@ function resolveFilter(meta, name, filter) {
|
|
|
462
470
|
* See architecture/security-filter-writes.md.
|
|
463
471
|
*/
|
|
464
472
|
export function guardWrite(meta, rows, write) {
|
|
465
|
-
for (const [name, condition] of securityConditions(meta)) {
|
|
473
|
+
for (const [name, condition] of securityConditions(meta, [write])) {
|
|
466
474
|
const values = condition;
|
|
467
475
|
const keys = fieldKeys(meta, () => true).filter((key) => Object.hasOwn(values, key));
|
|
468
476
|
const equalities = keys.length === getKeys(values).length;
|
|
@@ -576,10 +584,10 @@ export function isJsonObject(value) {
|
|
|
576
584
|
return isPlainObject(value) && !isOperatorObject(value);
|
|
577
585
|
}
|
|
578
586
|
/**
|
|
579
|
-
* A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
|
|
580
|
-
*
|
|
581
|
-
*
|
|
582
|
-
*
|
|
587
|
+
* A page operand, checked before it reaches an engine. These arrive from page arithmetic and from a
|
|
588
|
+
* client's call, where JSON carries a fraction or a negative alike, and each engine's own complaint
|
|
589
|
+
* names neither the clause nor the value - or, for `$limit: 0`, quietly means something else.
|
|
590
|
+
* Shared so every backend rejects the same input.
|
|
583
591
|
*/
|
|
584
592
|
export function assertNonNegativeInteger(value, clause) {
|
|
585
593
|
if (!Number.isInteger(value) || value < 0) {
|
|
@@ -54,7 +54,10 @@ export declare function lacksValue(column: {
|
|
|
54
54
|
* holds a value too, unlike on the rows a migration finds.
|
|
55
55
|
*/
|
|
56
56
|
export declare function lacksValueOnInsert(field: FieldOptions): boolean;
|
|
57
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
|
|
59
|
+
* a client's `constructor` is none.
|
|
60
|
+
*/
|
|
58
61
|
export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
|
|
59
62
|
/** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
|
|
60
63
|
export declare function fieldKeys<E>(meta: EntityMeta<E>, pick: (field: FieldMeta) => unknown): FieldKey<E>[];
|
package/dist/util/field.util.js
CHANGED
|
@@ -107,9 +107,12 @@ export function lacksValueOnInsert(field) {
|
|
|
107
107
|
isAutoIncrement: field.autoIncrement === true,
|
|
108
108
|
}));
|
|
109
109
|
}
|
|
110
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
|
|
112
|
+
* a client's `constructor` is none.
|
|
113
|
+
*/
|
|
111
114
|
export function isFieldKey(meta, key) {
|
|
112
|
-
return meta.fields[key] !== undefined;
|
|
115
|
+
return Object.hasOwn(meta.fields, key) && meta.fields[key] !== undefined;
|
|
113
116
|
}
|
|
114
117
|
/** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
|
|
115
118
|
export function fieldKeys(meta, pick) {
|
package/dist/util/uqlError.d.ts
CHANGED
|
@@ -4,11 +4,26 @@
|
|
|
4
4
|
* failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
|
|
5
5
|
* caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
|
|
6
6
|
*/
|
|
7
|
-
export
|
|
7
|
+
export declare const QUERY_ERROR_KINDS: readonly ['uniqueViolation', 'foreignKeyViolation', 'notNullViolation', 'checkViolation', 'optimisticLock', 'retryable', 'usage', 'security'];
|
|
8
|
+
export type QueryErrorKind = (typeof QUERY_ERROR_KINDS)[number];
|
|
9
|
+
export declare function isQueryErrorKind(value: unknown): value is QueryErrorKind;
|
|
10
|
+
/**
|
|
11
|
+
* Where in a call the refused value sits, as `['query', '$where', 'password']`: a form highlights the field by it. A
|
|
12
|
+
* querier's refusal names it within the query, `['$limit']`, which the API places within the call.
|
|
13
|
+
*/
|
|
14
|
+
export type UqlErrorPath = readonly (string | number)[];
|
|
15
|
+
export type UqlErrorOptions = ErrorOptions & {
|
|
16
|
+
readonly path?: UqlErrorPath;
|
|
17
|
+
/** What HTTP answers beside the status, as a 405's `allow`. */
|
|
18
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
19
|
+
};
|
|
8
20
|
/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
|
|
9
21
|
export declare abstract class UqlError extends Error {
|
|
10
22
|
abstract readonly kind: QueryErrorKind;
|
|
11
23
|
abstract readonly status: number;
|
|
24
|
+
readonly path?: UqlErrorPath;
|
|
25
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
26
|
+
constructor(message?: string, opts?: UqlErrorOptions);
|
|
12
27
|
}
|
|
13
28
|
/**
|
|
14
29
|
* Thrown where the caller used the API in a way no statement can carry out: an update payload with no
|
|
@@ -20,6 +35,17 @@ export declare class UqlUsageError extends UqlError {
|
|
|
20
35
|
readonly kind = "usage";
|
|
21
36
|
readonly status = 400;
|
|
22
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
|
|
40
|
+
* not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
|
|
41
|
+
* a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
|
|
42
|
+
*/
|
|
43
|
+
export declare class UqlRequestError extends UqlError {
|
|
44
|
+
readonly status: number;
|
|
45
|
+
name: string;
|
|
46
|
+
readonly kind = "usage";
|
|
47
|
+
constructor(message: string, status: number, opts?: UqlErrorOptions);
|
|
48
|
+
}
|
|
23
49
|
/**
|
|
24
50
|
* Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
|
|
25
51
|
* Fails the statement closed.
|
package/dist/util/uqlError.js
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
|
|
3
|
+
* with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
|
|
4
|
+
* failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
|
|
5
|
+
* caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
|
|
6
|
+
*/
|
|
7
|
+
export const QUERY_ERROR_KINDS = [
|
|
8
|
+
'uniqueViolation',
|
|
9
|
+
'foreignKeyViolation',
|
|
10
|
+
'notNullViolation',
|
|
11
|
+
'checkViolation',
|
|
12
|
+
'optimisticLock',
|
|
13
|
+
'retryable',
|
|
14
|
+
'usage',
|
|
15
|
+
'security',
|
|
16
|
+
];
|
|
17
|
+
const KINDS = new Set(QUERY_ERROR_KINDS);
|
|
18
|
+
export function isQueryErrorKind(value) {
|
|
19
|
+
return KINDS.has(value);
|
|
20
|
+
}
|
|
1
21
|
/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
|
|
2
22
|
export class UqlError extends Error {
|
|
23
|
+
constructor(message, opts) {
|
|
24
|
+
super(message, opts);
|
|
25
|
+
if (opts?.path) {
|
|
26
|
+
this.path = opts.path;
|
|
27
|
+
}
|
|
28
|
+
if (opts?.headers) {
|
|
29
|
+
this.headers = opts.headers;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
3
32
|
}
|
|
4
33
|
/**
|
|
5
34
|
* Thrown where the caller used the API in a way no statement can carry out: an update payload with no
|
|
@@ -11,6 +40,20 @@ export class UqlUsageError extends UqlError {
|
|
|
11
40
|
kind = 'usage';
|
|
12
41
|
status = 400;
|
|
13
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
|
|
45
|
+
* not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
|
|
46
|
+
* a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
|
|
47
|
+
*/
|
|
48
|
+
export class UqlRequestError extends UqlError {
|
|
49
|
+
status;
|
|
50
|
+
name = 'UqlRequestError';
|
|
51
|
+
kind = 'usage';
|
|
52
|
+
constructor(message, status, opts) {
|
|
53
|
+
super(message, opts);
|
|
54
|
+
this.status = status;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
14
57
|
/**
|
|
15
58
|
* Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
|
|
16
59
|
* Fails the statement closed.
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.113.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -91,7 +91,8 @@ export class Post {
|
|
|
91
91
|
- A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so no `!`; an upsert's may be `undefined`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
|
|
92
92
|
- `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
|
|
93
93
|
- `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
|
|
94
|
-
-
|
|
94
|
+
- Serve entities to a client with `createApi({ pool, include, contextOf, use })` from `uql-orm/http`, mounted under a versioned base as `toFetchHandler(api)` on a catch-all, `app.use('/api/v1', toExpress(api))` (`uql-orm/express`) or `toRequestHandler(api)`; the wire is `{base}/:entity/:op` (`GET ?q=` or a JSON `POST` for reads, a JSON `POST` for writes) and a failure answers `{ error: { message, status, kind, path } }`, or called inside a tRPC or oRPC procedure as `api.call(input, ctx.req)`, which checks the call itself. `include` is required and fences relations too; `serve(User, { ops: ['read', 'update'], members: { passwordHash: false, role: ['read'], password: ['insert'] }, use: [...] })` narrows one, where a member's `read` covers select, filter, sort and aggregate and an unlisted member keeps every op. A middleware is `(call, context, next) => next(call)`: the API's `use` runs on every call, a `serve`'s on its entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). `.eager(false)` only leaves a field out of a read naming no fields, so a client's `$select` still reads it: hide a secret (`password`, a token) with `members: { password: false }`. Scope tenants with a `security` filter and `contextOf`, never a middleware; without `contextOf` a call keeps its caller's context.
|
|
95
|
+
- The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport; it answers what the pool answers (rows, not `{ data }`) and reads rows back by the entity it is handed, which must be registered (importing its class does it): a `Date` field is a `Date` and a `bigint` exact, so its rows are not plain JSON and a cache persisting them needs a serializer. For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.
|
|
95
96
|
- A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
|
|
96
97
|
- A relation decorator takes its target first, then its options, as `rel.*` does. `mappedBy` and `references` may be left out where only one member fits, and then the options too: `@OneToMany(() => Post)`. `@ManyToMany(() => Tag, { through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
|
|
97
98
|
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
|
|
@@ -177,7 +178,7 @@ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
|
|
|
177
178
|
- A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
|
|
178
179
|
- `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
|
|
179
180
|
- A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
|
|
180
|
-
- `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
|
|
181
|
+
- `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. `ops: ['insert', 'update', 'delete']` makes one hold those statements alone (anyone reads a row, only its author writes it); an update or delete is also held to the read ones. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
|
|
181
182
|
|
|
182
183
|
## Queries
|
|
183
184
|
|
|
@@ -290,4 +291,5 @@ Upgrading uql itself: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which
|
|
|
290
291
|
- JSON paths and operators: https://uql-orm.dev/querying/json.md
|
|
291
292
|
- Full-text and vector search: https://uql-orm.dev/querying/full-text.md, https://uql-orm.dev/querying/semantic-search.md
|
|
292
293
|
- Computed fields: https://uql-orm.dev/entities/computed-fields.md
|
|
294
|
+
- Serving queries to a client: https://uql-orm.dev/http.md, https://uql-orm.dev/browser.md
|
|
293
295
|
- Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
|
package/dist/browser/http/bus.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
const subscriptors = new Set();
|
|
2
|
-
export function notify(notification) {
|
|
3
|
-
for (const subscriptor of subscriptors) {
|
|
4
|
-
subscriptor(notification);
|
|
5
|
-
}
|
|
6
|
-
}
|
|
7
|
-
export function on(cb) {
|
|
8
|
-
subscriptors.add(cb);
|
|
9
|
-
return () => {
|
|
10
|
-
subscriptors.delete(cb);
|
|
11
|
-
};
|
|
12
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { RequestSuccessResponse } from '../../type/index.js';
|
|
2
|
-
import type { RequestOptions } from '../type/index.js';
|
|
3
|
-
/**
|
|
4
|
-
* Error thrown for non-2xx responses. Carries the HTTP status so callers can key
|
|
5
|
-
* behavior on it (401 redirects, 402 payment flows, error-boundary routing).
|
|
6
|
-
*/
|
|
7
|
-
export declare class RequestError extends Error {
|
|
8
|
-
readonly status: number;
|
|
9
|
-
constructor(message: string, status: number);
|
|
10
|
-
}
|
|
11
|
-
export declare function get<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
12
|
-
export declare function post<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
13
|
-
export declare function patch<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
14
|
-
export declare function put<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
15
|
-
export declare function remove<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
16
|
-
/**
|
|
17
|
-
* HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
|
|
18
|
-
* request body, avoiding URL-length limits.
|
|
19
|
-
*/
|
|
20
|
-
export declare function query<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { wireJson } from '../../http/query.js';
|
|
2
|
-
import { notify } from './bus.js';
|
|
3
|
-
/**
|
|
4
|
-
* Error thrown for non-2xx responses. Carries the HTTP status so callers can key
|
|
5
|
-
* behavior on it (401 redirects, 402 payment flows, error-boundary routing).
|
|
6
|
-
*/
|
|
7
|
-
export class RequestError extends Error {
|
|
8
|
-
status;
|
|
9
|
-
constructor(message, status) {
|
|
10
|
-
super(message);
|
|
11
|
-
this.status = status;
|
|
12
|
-
this.name = 'RequestError';
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
// Methods are upper-case because `fetch` normalizes only the classic verbs: a lowercase `patch` or `query`
|
|
16
|
-
// is sent as written, and servers refuse it.
|
|
17
|
-
export function get(url, opts) {
|
|
18
|
-
return request(url, { method: 'GET' }, opts);
|
|
19
|
-
}
|
|
20
|
-
export function post(url, payload, opts) {
|
|
21
|
-
return request(url, { method: 'POST', body: wireJson(payload) }, opts);
|
|
22
|
-
}
|
|
23
|
-
export function patch(url, payload, opts) {
|
|
24
|
-
return request(url, { method: 'PATCH', body: wireJson(payload) }, opts);
|
|
25
|
-
}
|
|
26
|
-
export function put(url, payload, opts) {
|
|
27
|
-
return request(url, { method: 'PUT', body: wireJson(payload) }, opts);
|
|
28
|
-
}
|
|
29
|
-
export function remove(url, opts) {
|
|
30
|
-
return request(url, { method: 'DELETE' }, opts);
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
|
|
34
|
-
* request body, avoiding URL-length limits.
|
|
35
|
-
*/
|
|
36
|
-
export function query(url, payload, opts) {
|
|
37
|
-
return request(url, { method: 'QUERY', body: wireJson(payload) }, opts);
|
|
38
|
-
}
|
|
39
|
-
function request(url, init, opts) {
|
|
40
|
-
notify({ phase: 'start', opts });
|
|
41
|
-
init.headers = {
|
|
42
|
-
accept: 'application/json',
|
|
43
|
-
'content-type': 'application/json',
|
|
44
|
-
...opts?.headers,
|
|
45
|
-
};
|
|
46
|
-
if (opts?.signal) {
|
|
47
|
-
init.signal = opts.signal;
|
|
48
|
-
}
|
|
49
|
-
return fetch(url, init)
|
|
50
|
-
.then((rawResp) => rawResp.json().then((resp) => {
|
|
51
|
-
const isSuccess = rawResp.status >= 200 && rawResp.status < 300;
|
|
52
|
-
if (isSuccess) {
|
|
53
|
-
notify({ phase: 'success', opts });
|
|
54
|
-
return resp;
|
|
55
|
-
}
|
|
56
|
-
const errorResp = resp;
|
|
57
|
-
const error = {
|
|
58
|
-
message: errorResp?.error?.message ?? rawResp.statusText,
|
|
59
|
-
code: errorResp?.error?.code ?? rawResp.status,
|
|
60
|
-
};
|
|
61
|
-
notify({ phase: 'error', error, opts });
|
|
62
|
-
throw new RequestError(error.message, error.code);
|
|
63
|
-
}))
|
|
64
|
-
.finally(() => {
|
|
65
|
-
notify({ phase: 'complete', opts });
|
|
66
|
-
});
|
|
67
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { type HttpMethod } from '../../http/contract.js';
|
|
2
|
-
import type { SharedQuerier, AbstractType } from '../../type/index.js';
|
|
3
|
-
import type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';
|
|
4
|
-
export type HttpQuerierDefaults = {
|
|
5
|
-
/**
|
|
6
|
-
* headers sent with every request from this instance, merged under per-call headers.
|
|
7
|
-
* Create one instance per request (e.g. during SSR) to scope auth headers safely.
|
|
8
|
-
*/
|
|
9
|
-
readonly headers?: Record<string, string>;
|
|
10
|
-
/**
|
|
11
|
-
* transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the
|
|
12
|
-
* JSON query in the request body, avoiding URL-length limits for large queries; requires
|
|
13
|
-
* infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.
|
|
14
|
-
*/
|
|
15
|
-
readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;
|
|
16
|
-
/**
|
|
17
|
-
* The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same
|
|
18
|
-
* option the server handler takes, so one map serves both. State it where the default cannot: a
|
|
19
|
-
* build that minifies class names renames every route.
|
|
20
|
-
*/
|
|
21
|
-
readonly entityPath?: (entity: AbstractType<unknown>) => string;
|
|
22
|
-
};
|
|
23
|
-
export declare class HttpQuerier implements ClientQuerier {
|
|
24
|
-
readonly basePath: string;
|
|
25
|
-
readonly defaults: HttpQuerierDefaults;
|
|
26
|
-
constructor(basePath: string, defaults?: HttpQuerierDefaults);
|
|
27
|
-
readonly findOneById: ClientQuerier['findOneById'];
|
|
28
|
-
readonly findOne: ClientQuerier['findOne'];
|
|
29
|
-
readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'];
|
|
30
|
-
readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'];
|
|
31
|
-
readonly findManyPage: ClientQuerier['findManyPage'];
|
|
32
|
-
readonly count: ClientQuerier['count'];
|
|
33
|
-
/** The `count` route capped at one row, so existence needs no endpoint of its own. */
|
|
34
|
-
readonly exists: ClientQuerier['exists'];
|
|
35
|
-
readonly insertOne: ClientQuerier['insertOne'];
|
|
36
|
-
readonly insertMany: ClientQuerier['insertMany'];
|
|
37
|
-
readonly updateOneById: ClientQuerier['updateOneById'];
|
|
38
|
-
readonly updateMany: ClientQuerier['updateMany'];
|
|
39
|
-
readonly saveOne: ClientQuerier['saveOne'];
|
|
40
|
-
readonly saveMany: ClientQuerier['saveMany'];
|
|
41
|
-
readonly deleteOneById: ClientQuerier['deleteOneById'];
|
|
42
|
-
readonly deleteMany: ClientQuerier['deleteMany'];
|
|
43
|
-
getBasePath<E>(entity: AbstractType<E>): string;
|
|
44
|
-
protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions): Promise<import("../../type/wire.js").RequestSuccessResponse<T>>;
|
|
45
|
-
protected buildOptions(opts?: RequestOptions): RequestOptions | undefined;
|
|
46
|
-
}
|