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
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { getMeta } from '../../entity/metadata/definition.js';
|
|
2
|
-
import { CRUD_ROUTES, entityPath } from '../../http/contract.js';
|
|
3
|
-
import { stringifyQuery } from '../../http/query.js';
|
|
4
|
-
import { readWireData } from '../../http/wireRow.js';
|
|
5
|
-
import { isScalarId } from '../../util/object.util.js';
|
|
6
|
-
import { UqlUsageError } from '../../util/uqlError.js';
|
|
7
|
-
import { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';
|
|
8
|
-
/** A response with its `data` as the entity holds it, by what its route answers: JSON carried dates and keys as text. */
|
|
9
|
-
function dataOf(entity, response, answers) {
|
|
10
|
-
return { ...response, data: readWireData(getMeta(entity), response.data, answers) };
|
|
11
|
-
}
|
|
12
|
-
/** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */
|
|
13
|
-
function idSegment(entity, id) {
|
|
14
|
-
if (!isScalarId(id)) {
|
|
15
|
-
throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);
|
|
16
|
-
}
|
|
17
|
-
return String(id);
|
|
18
|
-
}
|
|
19
|
-
export class HttpQuerier {
|
|
20
|
-
basePath;
|
|
21
|
-
defaults;
|
|
22
|
-
constructor(basePath, defaults = {}) {
|
|
23
|
-
this.basePath = basePath;
|
|
24
|
-
this.defaults = defaults;
|
|
25
|
-
}
|
|
26
|
-
// Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.
|
|
27
|
-
findOneById = async (entity, id, q, opts) => dataOf(entity, await get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts)), CRUD_ROUTES.findOneById.answers);
|
|
28
|
-
findOne = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts), CRUD_ROUTES.findOne.answers);
|
|
29
|
-
findMany = async (entity, q, opts) => dataOf(entity, await this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts), CRUD_ROUTES.findMany.answers);
|
|
30
|
-
findManyAndCount = async (entity, q, opts) => {
|
|
31
|
-
const response = await this.findMany(entity, q, { ...opts, count: true });
|
|
32
|
-
if (typeof response.count !== 'number') {
|
|
33
|
-
throw new TypeError('findManyAndCount response has an invalid count');
|
|
34
|
-
}
|
|
35
|
-
return { ...response, count: response.count };
|
|
36
|
-
};
|
|
37
|
-
findManyPage = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts), CRUD_ROUTES.findManyPage.answers);
|
|
38
|
-
count = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);
|
|
39
|
-
/** The `count` route capped at one row, so existence needs no endpoint of its own. */
|
|
40
|
-
exists = async (entity, q, opts) => {
|
|
41
|
-
const res = await this.count(entity, { ...q, $limit: 1 }, opts);
|
|
42
|
-
return { ...res, data: res.data > 0 };
|
|
43
|
-
};
|
|
44
|
-
insertOne = async (entity, payload, opts) => dataOf(entity, await post(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.insertOne.answers);
|
|
45
|
-
insertMany = async (entity, payload, opts) => dataOf(entity, await post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.insertMany.answers);
|
|
46
|
-
updateOneById = async (entity, id, payload, opts) => patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));
|
|
47
|
-
updateMany = (entity, q, payload, opts) => patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));
|
|
48
|
-
saveOne = async (entity, payload, opts) => dataOf(entity, await put(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.saveOne.answers);
|
|
49
|
-
saveMany = async (entity, payload, opts) => dataOf(entity, await put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.saveMany.answers);
|
|
50
|
-
deleteOneById = async (entity, id, opts = {}) => {
|
|
51
|
-
const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';
|
|
52
|
-
return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
|
|
53
|
-
};
|
|
54
|
-
deleteMany = (entity, q, opts = {}) => remove(`${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`, this.buildOptions(opts));
|
|
55
|
-
getBasePath(entity) {
|
|
56
|
-
return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;
|
|
57
|
-
}
|
|
58
|
-
read(path, q, opts) {
|
|
59
|
-
if (this.defaults.readMethod === 'QUERY') {
|
|
60
|
-
return httpQuery(path, q ?? {}, this.buildOptions(opts));
|
|
61
|
-
}
|
|
62
|
-
return get(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));
|
|
63
|
-
}
|
|
64
|
-
buildOptions(opts) {
|
|
65
|
-
if (!this.defaults.headers && !opts?.headers) {
|
|
66
|
-
return opts;
|
|
67
|
-
}
|
|
68
|
-
return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };
|
|
69
|
-
}
|
|
70
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import type { RequestErrorResponse } from '../../http/contract.js';
|
|
2
|
-
export type RequestOptions = {
|
|
3
|
-
silent?: boolean;
|
|
4
|
-
/**
|
|
5
|
-
* extra headers merged over the defaults (e.g. `{ Authorization: 'Bearer ...' }`).
|
|
6
|
-
*/
|
|
7
|
-
headers?: Record<string, string>;
|
|
8
|
-
/**
|
|
9
|
-
* abort/timeout control, e.g. `AbortSignal.timeout(120_000)` for long-running calls.
|
|
10
|
-
*/
|
|
11
|
-
signal?: AbortSignal;
|
|
12
|
-
};
|
|
13
|
-
export type RequestFindOptions = RequestOptions & {
|
|
14
|
-
count?: boolean;
|
|
15
|
-
};
|
|
16
|
-
type RequestBaseNotification = {
|
|
17
|
-
readonly opts?: RequestOptions;
|
|
18
|
-
};
|
|
19
|
-
type RequestSuccessNotification = {
|
|
20
|
-
readonly phase: 'start' | 'success' | 'complete';
|
|
21
|
-
} & RequestBaseNotification;
|
|
22
|
-
type RequestErrorNotification = {
|
|
23
|
-
readonly phase: 'error';
|
|
24
|
-
} & RequestErrorResponse & RequestBaseNotification;
|
|
25
|
-
export type RequestNotification = RequestSuccessNotification | RequestErrorNotification;
|
|
26
|
-
export type RequestCallback = (msg: RequestNotification) => void;
|
|
27
|
-
export {};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type NextFunction, type Request, type Response, type Router } from 'express';
|
|
2
|
-
import { type RequestHandlerOptions } from '../http/handler.js';
|
|
3
|
-
export type MiddlewareOptions = RequestHandlerOptions<Request>;
|
|
4
|
-
/**
|
|
5
|
-
* Express adapter over the framework-agnostic {@link createRequestHandler}.
|
|
6
|
-
* Unknown entities and routes fall through via `next()` so the middleware
|
|
7
|
-
* composes with custom routes; errors go to `next(err)` so user error
|
|
8
|
-
* middleware (e.g. {@link errorHandler}) keeps working.
|
|
9
|
-
*/
|
|
10
|
-
export declare function querierMiddleware(opts: MiddlewareOptions): Router;
|
|
11
|
-
export declare function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): void;
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { Router as expressRouter } from 'express';
|
|
2
|
-
import { toErrorResponse } from '../http/contract.js';
|
|
3
|
-
import { createRequestHandler } from '../http/handler.js';
|
|
4
|
-
/**
|
|
5
|
-
* Express adapter over the framework-agnostic {@link createRequestHandler}.
|
|
6
|
-
* Unknown entities and routes fall through via `next()` so the middleware
|
|
7
|
-
* composes with custom routes; errors go to `next(err)` so user error
|
|
8
|
-
* middleware (e.g. {@link errorHandler}) keeps working.
|
|
9
|
-
*/
|
|
10
|
-
export function querierMiddleware(opts) {
|
|
11
|
-
const handle = createRequestHandler(opts);
|
|
12
|
-
const router = expressRouter();
|
|
13
|
-
router.all('/:entityPath{/:subPath}', async (req, res, next) => {
|
|
14
|
-
const pending = handle({
|
|
15
|
-
method: req.method,
|
|
16
|
-
entityPath: req.params.entityPath,
|
|
17
|
-
subPath: req.params.subPath,
|
|
18
|
-
query: req.query,
|
|
19
|
-
body: req.body,
|
|
20
|
-
context: req,
|
|
21
|
-
});
|
|
22
|
-
if (!pending) {
|
|
23
|
-
next();
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
try {
|
|
27
|
-
const { status, body } = await pending;
|
|
28
|
-
res.status(status).json(body);
|
|
29
|
-
}
|
|
30
|
-
catch (err) {
|
|
31
|
-
next(err);
|
|
32
|
-
}
|
|
33
|
-
});
|
|
34
|
-
return router;
|
|
35
|
-
}
|
|
36
|
-
export function errorHandler(err, _req, res, _next) {
|
|
37
|
-
const { status, body } = toErrorResponse(err);
|
|
38
|
-
res.status(status).json(body);
|
|
39
|
-
}
|
package/dist/http/contract.d.ts
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import type { AbstractType } from '../type/index.js';
|
|
2
|
-
/** What a route answers in `data`, which says how its values cross JSON: rows, a page of them, keys, or a count. */
|
|
3
|
-
export type WireAnswer = 'rows' | 'page' | 'ids' | 'count';
|
|
4
|
-
/**
|
|
5
|
-
* Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.
|
|
6
|
-
* Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method
|
|
7
|
-
* (or routing a non-existent one) is a compile error.
|
|
8
|
-
*/
|
|
9
|
-
export declare const CRUD_ROUTES: {
|
|
10
|
-
readonly findMany: {
|
|
11
|
-
readonly method: 'GET';
|
|
12
|
-
readonly path: '';
|
|
13
|
-
readonly answers: 'rows';
|
|
14
|
-
};
|
|
15
|
-
readonly findManyPage: {
|
|
16
|
-
readonly method: 'GET';
|
|
17
|
-
readonly path: '/page';
|
|
18
|
-
readonly answers: 'page';
|
|
19
|
-
};
|
|
20
|
-
readonly findOne: {
|
|
21
|
-
readonly method: 'GET';
|
|
22
|
-
readonly path: '/one';
|
|
23
|
-
readonly answers: 'rows';
|
|
24
|
-
};
|
|
25
|
-
readonly count: {
|
|
26
|
-
readonly method: 'GET';
|
|
27
|
-
readonly path: '/count';
|
|
28
|
-
readonly answers: 'count';
|
|
29
|
-
};
|
|
30
|
-
readonly findOneById: {
|
|
31
|
-
readonly method: 'GET';
|
|
32
|
-
readonly path: '/:id';
|
|
33
|
-
readonly answers: 'rows';
|
|
34
|
-
};
|
|
35
|
-
readonly insertOne: {
|
|
36
|
-
readonly method: 'POST';
|
|
37
|
-
readonly path: '';
|
|
38
|
-
readonly answers: 'ids';
|
|
39
|
-
};
|
|
40
|
-
readonly insertMany: {
|
|
41
|
-
readonly method: 'POST';
|
|
42
|
-
readonly path: '/many';
|
|
43
|
-
readonly answers: 'ids';
|
|
44
|
-
};
|
|
45
|
-
readonly saveOne: {
|
|
46
|
-
readonly method: 'PUT';
|
|
47
|
-
readonly path: '';
|
|
48
|
-
readonly answers: 'ids';
|
|
49
|
-
};
|
|
50
|
-
readonly saveMany: {
|
|
51
|
-
readonly method: 'PUT';
|
|
52
|
-
readonly path: '/many';
|
|
53
|
-
readonly answers: 'ids';
|
|
54
|
-
};
|
|
55
|
-
readonly updateMany: {
|
|
56
|
-
readonly method: 'PATCH';
|
|
57
|
-
readonly path: '';
|
|
58
|
-
readonly answers: 'count';
|
|
59
|
-
};
|
|
60
|
-
readonly updateOneById: {
|
|
61
|
-
readonly method: 'PATCH';
|
|
62
|
-
readonly path: '/:id';
|
|
63
|
-
readonly answers: 'count';
|
|
64
|
-
};
|
|
65
|
-
readonly deleteOneById: {
|
|
66
|
-
readonly method: 'DELETE';
|
|
67
|
-
readonly path: '/:id';
|
|
68
|
-
readonly answers: 'count';
|
|
69
|
-
};
|
|
70
|
-
readonly deleteMany: {
|
|
71
|
-
readonly method: 'DELETE';
|
|
72
|
-
readonly path: '';
|
|
73
|
-
readonly answers: 'count';
|
|
74
|
-
};
|
|
75
|
-
};
|
|
76
|
-
export type CrudOperation = keyof typeof CRUD_ROUTES;
|
|
77
|
-
export type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];
|
|
78
|
-
/**
|
|
79
|
-
* `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the
|
|
80
|
-
* GET routes, but the JSON query travels in the request body instead of the query string,
|
|
81
|
-
* avoiding URL-length limits for large queries.
|
|
82
|
-
*/
|
|
83
|
-
export type HttpMethod = CrudRoute['method'] | 'QUERY';
|
|
84
|
-
/**
|
|
85
|
-
* URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.
|
|
86
|
-
*/
|
|
87
|
-
export declare function entityPath<E>(entity: AbstractType<E>): string;
|
|
88
|
-
export type RouteMatch = {
|
|
89
|
-
readonly op: CrudOperation;
|
|
90
|
-
/**
|
|
91
|
-
* the resolved transport method - differs from the op's canonical route method for QUERY.
|
|
92
|
-
*/
|
|
93
|
-
readonly method: HttpMethod;
|
|
94
|
-
readonly id?: string;
|
|
95
|
-
};
|
|
96
|
-
/**
|
|
97
|
-
* Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.
|
|
98
|
-
*/
|
|
99
|
-
export declare function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined;
|
|
100
|
-
export type RequestErrorResponse = {
|
|
101
|
-
readonly error: {
|
|
102
|
-
readonly message: string;
|
|
103
|
-
readonly code: number;
|
|
104
|
-
};
|
|
105
|
-
};
|
|
106
|
-
/**
|
|
107
|
-
* Map a thrown error to the wire error envelope. Honors a numeric `status` on the error
|
|
108
|
-
* (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.
|
|
109
|
-
*/
|
|
110
|
-
export declare function toErrorResponse(err: unknown): {
|
|
111
|
-
status: number;
|
|
112
|
-
body: RequestErrorResponse;
|
|
113
|
-
};
|
package/dist/http/contract.js
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import { queryErrorKind } from '../querier/queryError.js';
|
|
2
|
-
// the specific util modules, not the barrel, which reaches every dialect helper and would land in the browser bundle
|
|
3
|
-
import { getKeys } from '../util/object.util.js';
|
|
4
|
-
import { kebabCase } from '../util/string.util.js';
|
|
5
|
-
/**
|
|
6
|
-
* Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.
|
|
7
|
-
* Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method
|
|
8
|
-
* (or routing a non-existent one) is a compile error.
|
|
9
|
-
*/
|
|
10
|
-
export const CRUD_ROUTES = {
|
|
11
|
-
findMany: { method: 'GET', path: '', answers: 'rows' },
|
|
12
|
-
findManyPage: { method: 'GET', path: '/page', answers: 'page' },
|
|
13
|
-
findOne: { method: 'GET', path: '/one', answers: 'rows' },
|
|
14
|
-
count: { method: 'GET', path: '/count', answers: 'count' },
|
|
15
|
-
findOneById: { method: 'GET', path: '/:id', answers: 'rows' },
|
|
16
|
-
insertOne: { method: 'POST', path: '', answers: 'ids' },
|
|
17
|
-
insertMany: { method: 'POST', path: '/many', answers: 'ids' },
|
|
18
|
-
saveOne: { method: 'PUT', path: '', answers: 'ids' },
|
|
19
|
-
saveMany: { method: 'PUT', path: '/many', answers: 'ids' },
|
|
20
|
-
updateMany: { method: 'PATCH', path: '', answers: 'count' },
|
|
21
|
-
updateOneById: { method: 'PATCH', path: '/:id', answers: 'count' },
|
|
22
|
-
deleteOneById: { method: 'DELETE', path: '/:id', answers: 'count' },
|
|
23
|
-
deleteMany: { method: 'DELETE', path: '', answers: 'count' },
|
|
24
|
-
};
|
|
25
|
-
const CRUD_OPS = getKeys(CRUD_ROUTES);
|
|
26
|
-
// derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place
|
|
27
|
-
const QUERY_READ_OPS = new Map(CRUD_OPS.filter((op) => CRUD_ROUTES[op].method === 'GET' && CRUD_ROUTES[op].path !== '/:id').map((op) => [
|
|
28
|
-
CRUD_ROUTES[op].path,
|
|
29
|
-
op,
|
|
30
|
-
]));
|
|
31
|
-
/**
|
|
32
|
-
* URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.
|
|
33
|
-
*/
|
|
34
|
-
export function entityPath(entity) {
|
|
35
|
-
return kebabCase(entity.name);
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.
|
|
39
|
-
*/
|
|
40
|
-
export function matchRoute(method, subPath) {
|
|
41
|
-
const raw = method.toUpperCase();
|
|
42
|
-
const literal = subPath === undefined ? '' : `/${subPath}`;
|
|
43
|
-
if (raw === 'QUERY') {
|
|
44
|
-
const op = QUERY_READ_OPS.get(literal);
|
|
45
|
-
return op ? { op, method: 'QUERY' } : undefined;
|
|
46
|
-
}
|
|
47
|
-
// HEAD reads like GET per HTTP semantics; the server runtime omits the response body
|
|
48
|
-
const verb = raw === 'HEAD' ? 'GET' : raw;
|
|
49
|
-
let idOp;
|
|
50
|
-
for (const op of CRUD_OPS) {
|
|
51
|
-
const route = CRUD_ROUTES[op];
|
|
52
|
-
if (route.method !== verb) {
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
if (route.path === literal) {
|
|
56
|
-
return { op, method: route.method };
|
|
57
|
-
}
|
|
58
|
-
if (route.path === '/:id') {
|
|
59
|
-
idOp = op;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return idOp && subPath !== undefined ? { op: idOp, method: CRUD_ROUTES[idOp].method, id: subPath } : undefined;
|
|
63
|
-
}
|
|
64
|
-
/** Generic on purpose: a driver's constraint message names tables and constraints, and Postgres echoes the value. */
|
|
65
|
-
const CONSTRAINT_ERRORS = new Map([
|
|
66
|
-
['uniqueViolation', { message: 'Conflict', code: 409 }],
|
|
67
|
-
['foreignKeyViolation', { message: 'Conflict', code: 409 }],
|
|
68
|
-
['notNullViolation', { message: 'Bad Request', code: 400 }],
|
|
69
|
-
['checkViolation', { message: 'Bad Request', code: 400 }],
|
|
70
|
-
]);
|
|
71
|
-
/**
|
|
72
|
-
* Map a thrown error to the wire error envelope. Honors a numeric `status` on the error
|
|
73
|
-
* (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.
|
|
74
|
-
*/
|
|
75
|
-
export function toErrorResponse(err) {
|
|
76
|
-
const error = err instanceof Error && 'status' in err && typeof err.status === 'number'
|
|
77
|
-
? { message: err.message, code: err.status }
|
|
78
|
-
: (CONSTRAINT_ERRORS.get(queryErrorKind(err)) ?? {
|
|
79
|
-
message: err instanceof Error ? err.message : 'Internal Server Error',
|
|
80
|
-
code: 500,
|
|
81
|
-
});
|
|
82
|
-
return { status: error.code, body: { error } };
|
|
83
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { type RequestHandlerOptions } from './handler.js';
|
|
2
|
-
export type FetchHandlerOptions = RequestHandlerOptions<Request> & {
|
|
3
|
-
/**
|
|
4
|
-
* URL prefix to strip before matching entity routes, e.g. '/api'. Defaults to ''.
|
|
5
|
-
*/
|
|
6
|
-
readonly basePath?: string;
|
|
7
|
-
};
|
|
8
|
-
/**
|
|
9
|
-
* Web-standard adapter over {@link createRequestHandler}: mount the returned
|
|
10
|
-
* `(request: Request) => Promise<Response>` in any fetch-native runtime
|
|
11
|
-
* (Hono, Next.js route handlers, Bun.serve, Cloudflare Workers, SvelteKit).
|
|
12
|
-
*/
|
|
13
|
-
export declare function createFetchHandler(opts: FetchHandlerOptions): (request: Request) => Promise<Response>;
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { UqlUsageError } from '../util/uqlError.js';
|
|
2
|
-
import { toErrorResponse } from './contract.js';
|
|
3
|
-
import { createRequestHandler } from './handler.js';
|
|
4
|
-
/**
|
|
5
|
-
* Web-standard adapter over {@link createRequestHandler}: mount the returned
|
|
6
|
-
* `(request: Request) => Promise<Response>` in any fetch-native runtime
|
|
7
|
-
* (Hono, Next.js route handlers, Bun.serve, Cloudflare Workers, SvelteKit).
|
|
8
|
-
*/
|
|
9
|
-
export function createFetchHandler(opts) {
|
|
10
|
-
const { basePath = '', ...handlerOpts } = opts;
|
|
11
|
-
const handle = createRequestHandler(handlerOpts);
|
|
12
|
-
return async (request) => {
|
|
13
|
-
try {
|
|
14
|
-
const url = new URL(request.url);
|
|
15
|
-
let path = url.pathname;
|
|
16
|
-
if (basePath && (path === basePath || path.startsWith(`${basePath}/`))) {
|
|
17
|
-
path = path.slice(basePath.length);
|
|
18
|
-
}
|
|
19
|
-
const segments = path.split('/').filter((segment) => segment.length);
|
|
20
|
-
if (segments.length === 0 || segments.length > 2) {
|
|
21
|
-
return notFound();
|
|
22
|
-
}
|
|
23
|
-
const [entityPath, subPath] = segments;
|
|
24
|
-
const method = request.method.toUpperCase();
|
|
25
|
-
const pending = handle({
|
|
26
|
-
method,
|
|
27
|
-
entityPath,
|
|
28
|
-
subPath,
|
|
29
|
-
query: Object.fromEntries(url.searchParams),
|
|
30
|
-
body: await parseBody(request, method),
|
|
31
|
-
context: request,
|
|
32
|
-
});
|
|
33
|
-
if (!pending) {
|
|
34
|
-
return notFound();
|
|
35
|
-
}
|
|
36
|
-
const { status, body } = await pending;
|
|
37
|
-
return Response.json(body, { status });
|
|
38
|
-
}
|
|
39
|
-
catch (err) {
|
|
40
|
-
const { status, body } = toErrorResponse(err);
|
|
41
|
-
return Response.json(body, { status });
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
async function parseBody(request, method) {
|
|
46
|
-
if (method !== 'POST' && method !== 'PUT' && method !== 'PATCH' && method !== 'QUERY') {
|
|
47
|
-
return undefined;
|
|
48
|
-
}
|
|
49
|
-
const text = await request.text();
|
|
50
|
-
if (!text) {
|
|
51
|
-
return undefined;
|
|
52
|
-
}
|
|
53
|
-
try {
|
|
54
|
-
return JSON.parse(text);
|
|
55
|
-
}
|
|
56
|
-
catch {
|
|
57
|
-
throw new UqlUsageError('invalid JSON body');
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
function notFound() {
|
|
61
|
-
const body = { error: { message: 'not found', code: 404 } };
|
|
62
|
-
return Response.json(body, { status: 404 });
|
|
63
|
-
}
|
package/dist/http/query.d.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import type { QueryKeyset, WireQuery } from '../type/index.js';
|
|
2
|
-
/** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */
|
|
3
|
-
declare const WIRE_FLAGS: ["hardDelete", "count"];
|
|
4
|
-
/** {@link WIRE_FLAGS} as the booleans {@link parseQueryParams} decodes them to, where a hook may also set them. */
|
|
5
|
-
export type WireFlags = {
|
|
6
|
-
readonly [K in (typeof WIRE_FLAGS)[number]]?: boolean;
|
|
7
|
-
};
|
|
8
|
-
/** The cursors a page request carries; only `findManyPage` reads them. */
|
|
9
|
-
export type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;
|
|
10
|
-
/**
|
|
11
|
-
* Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query
|
|
12
|
-
* object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.
|
|
13
|
-
*/
|
|
14
|
-
export declare function parseQueryParams<E = unknown>(params?: unknown): WireQuery<E> & WireFlags & WireCursors;
|
|
15
|
-
/**
|
|
16
|
-
* Serialize a UQL query object into a percent-encoded query string where object values
|
|
17
|
-
* are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.
|
|
18
|
-
*/
|
|
19
|
-
export declare function stringifyQuery(query?: Record<string, unknown>): string;
|
|
20
|
-
/**
|
|
21
|
-
* What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
|
|
22
|
-
* statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
|
|
23
|
-
* as its digits and a `Date` as its ISO text, which the server reads back by the entity.
|
|
24
|
-
*/
|
|
25
|
-
export declare function wireJson(value: unknown): string;
|
|
26
|
-
export {};
|
package/dist/http/query.js
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
// the clause table itself, not the barrel: this module is in the browser bundle's graph
|
|
2
|
-
import { QUERY_CLAUSES } from '../type/query.js';
|
|
3
|
-
// the brand, which a `sql` fragment and a column ref both carry
|
|
4
|
-
import { SQL_FN } from '../type/querySql.js';
|
|
5
|
-
// the specific util module, not the barrel, which reaches every dialect helper
|
|
6
|
-
import { getKeys, isRecord, isPlainObject } from '../util/object.util.js';
|
|
7
|
-
// the error class alone, from its own leaf module: `queryError.ts` carries every driver's code map
|
|
8
|
-
import { UqlUsageError } from '../util/uqlError.js';
|
|
9
|
-
/** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */
|
|
10
|
-
const WIRE_FLAGS = ['hardDelete', 'count'];
|
|
11
|
-
/**
|
|
12
|
-
* The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})
|
|
13
|
-
* HTTP carries, plus the {@link WIRE_FLAGS}. Any other `$` key is refused, since dropping a clause answers a read
|
|
14
|
-
* other than the one asked for; any other key (e.g. `filters`, `context`) is dropped, so a remote client can't
|
|
15
|
-
* bypass a security filter or inject ambient context.
|
|
16
|
-
*/
|
|
17
|
-
const WIRE_VALUES = new Map([
|
|
18
|
-
...getKeys(QUERY_CLAUSES)
|
|
19
|
-
.filter((key) => carriedOverHttp(QUERY_CLAUSES[key]))
|
|
20
|
-
.map((key) => [key, QUERY_CLAUSES[key].value]),
|
|
21
|
-
...WIRE_FLAGS.map((flag) => [flag, 'boolean']),
|
|
22
|
-
]);
|
|
23
|
-
function carriedOverHttp(clause) {
|
|
24
|
-
return clause.wire !== false;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query
|
|
28
|
-
* object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.
|
|
29
|
-
*/
|
|
30
|
-
export function parseQueryParams(params = {}) {
|
|
31
|
-
if (!isRecord(params)) {
|
|
32
|
-
throw new UqlUsageError('the query must be a JSON object');
|
|
33
|
-
}
|
|
34
|
-
const query = {};
|
|
35
|
-
for (const key of getKeys(params)) {
|
|
36
|
-
const shape = WIRE_VALUES.get(key);
|
|
37
|
-
if (!shape && key.startsWith('$')) {
|
|
38
|
-
throw new UqlUsageError(`'${key}' is not a query key HTTP takes`);
|
|
39
|
-
}
|
|
40
|
-
if (shape && params[key] !== undefined) {
|
|
41
|
-
query[key] = decodeWireValue(key, shape, params[key]);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
query['$where'] ??= {};
|
|
45
|
-
if (!isPlainObject(query['$where'])) {
|
|
46
|
-
throw new UqlUsageError("'$where' must be a JSON object");
|
|
47
|
-
}
|
|
48
|
-
return query;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Decodes a value to the type its clause declares. A query string carries every value as text, so a boolean
|
|
52
|
-
* must be decoded: `'false'` is a non-empty string, and taken as is, `$distinct=false` would turn it on.
|
|
53
|
-
*/
|
|
54
|
-
function decodeWireValue(key, shape, value) {
|
|
55
|
-
switch (shape) {
|
|
56
|
-
case 'object':
|
|
57
|
-
return typeof value === 'string' ? parseJson(key, value) : value;
|
|
58
|
-
case 'number':
|
|
59
|
-
return Number(value);
|
|
60
|
-
case 'boolean':
|
|
61
|
-
return value === true || value === 'true';
|
|
62
|
-
case 'string':
|
|
63
|
-
// A cursor arrives as the exact text a page handed out, never as JSON, so any other value is not a cursor.
|
|
64
|
-
if (typeof value !== 'string') {
|
|
65
|
-
throw new UqlUsageError(`'${key}' must be a cursor a page handed out`);
|
|
66
|
-
}
|
|
67
|
-
return value;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
function parseJson(key, text) {
|
|
71
|
-
try {
|
|
72
|
-
return JSON.parse(text);
|
|
73
|
-
}
|
|
74
|
-
catch {
|
|
75
|
-
throw new UqlUsageError(`invalid JSON in '${key}'`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Serialize a UQL query object into a percent-encoded query string where object values
|
|
80
|
-
* are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.
|
|
81
|
-
*/
|
|
82
|
-
export function stringifyQuery(query) {
|
|
83
|
-
if (!query) {
|
|
84
|
-
return '';
|
|
85
|
-
}
|
|
86
|
-
const params = new URLSearchParams();
|
|
87
|
-
for (const key of getKeys(query)) {
|
|
88
|
-
const value = query[key];
|
|
89
|
-
if (value === undefined) {
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
params.append(key, typeof value === 'object' && value !== null ? wireJson(value) : String(value));
|
|
93
|
-
}
|
|
94
|
-
const qs = params.toString();
|
|
95
|
-
return qs ? `?${qs}` : '';
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
|
|
99
|
-
* statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
|
|
100
|
-
* as its digits and a `Date` as its ISO text, which the server reads back by the entity.
|
|
101
|
-
*/
|
|
102
|
-
export function wireJson(value) {
|
|
103
|
-
return JSON.stringify(value, (_key, held) => {
|
|
104
|
-
if (typeof held === 'bigint') {
|
|
105
|
-
return String(held);
|
|
106
|
-
}
|
|
107
|
-
if (typeof held !== 'object' || held === null) {
|
|
108
|
-
return held;
|
|
109
|
-
}
|
|
110
|
-
if (SQL_FN in held) {
|
|
111
|
-
throw new UqlUsageError('raw SQL cannot travel over HTTP: what leaves the browser is JSON');
|
|
112
|
-
}
|
|
113
|
-
// A blob is a field value, so no type parameter reaches it: this is the only place it is caught.
|
|
114
|
-
if (held instanceof ArrayBuffer || ArrayBuffer.isView(held)) {
|
|
115
|
-
throw new UqlUsageError('binary cannot travel over HTTP: what leaves the browser is JSON');
|
|
116
|
-
}
|
|
117
|
-
return held;
|
|
118
|
-
});
|
|
119
|
-
}
|
|
File without changes
|