@revenexx/app-sdk 0.4.2 → 0.5.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 +29 -1
- package/dist/chunk-WJ7QJ3NU.js +41 -0
- package/dist/chunk-WJ7QJ3NU.js.map +1 -0
- package/dist/errors-DrxYD96C.d.cts +111 -0
- package/dist/errors-DrxYD96C.d.ts +111 -0
- package/dist/index.cjs +154 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +129 -15
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +39 -4
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +4 -12
- package/dist/router/index.d.ts +4 -12
- package/dist/router/index.js +24 -16
- package/dist/router/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/types-BMd8t8Pi.d.cts +0 -66
- package/dist/types-BMd8t8Pi.d.ts +0 -66
package/README.md
CHANGED
|
@@ -116,7 +116,8 @@ What you get:
|
|
|
116
116
|
- **A clean per-request context** — `c.params`, `c.query`, `c.body` (parsed),
|
|
117
117
|
`c.tenant`, `c.header(name)`, `c.log(msg)`, `c.json(data, status)`.
|
|
118
118
|
- **Error mapping** — throw `HttpError` / `notFound()` / `badRequest()` /
|
|
119
|
-
`forbidden()` / `conflict()` for explicit statuses;
|
|
119
|
+
`forbidden()` / `conflict()` for explicit statuses; database constraint
|
|
120
|
+
violations get the status they deserve (see below); data-client permission
|
|
120
121
|
errors become `403`; anything else is logged and answered as `500`.
|
|
121
122
|
- **A health route** — `GET /` answers with the App identity, status and the
|
|
122
123
|
registered routes (disable with `createApp({ health: false })`).
|
|
@@ -152,6 +153,33 @@ mountCrud(app, db.locales, {
|
|
|
152
153
|
Options: `only: ['list', 'get']` restricts the mounted routes; `defaultLimit` /
|
|
153
154
|
`maxLimit` tune pagination bounds (defaults 50 / 200).
|
|
154
155
|
|
|
156
|
+
### Constraint violations
|
|
157
|
+
|
|
158
|
+
A database constraint doing its job is not a server fault. The data adapters
|
|
159
|
+
map PostgREST's error to the status the condition deserves and answer with a
|
|
160
|
+
stable, generic message — the raw body (which names tables and constraints) is
|
|
161
|
+
logged through the function's `error()` and recorded on the trace, never
|
|
162
|
+
returned:
|
|
163
|
+
|
|
164
|
+
| condition | SQLSTATE | answer | message |
|
|
165
|
+
|---|---|---|---|
|
|
166
|
+
| duplicate value | `23505` / `23P01` | `409` | `a record with this value already exists` |
|
|
167
|
+
| referenced parent missing (write) | `23503` | `400` | `a referenced record does not exist` |
|
|
168
|
+
| dependent row blocks a delete | `23503` | `409` | `this record is still referenced by other records` |
|
|
169
|
+
| required value missing | `23502` | `400` | `a required value is missing` |
|
|
170
|
+
| check constraint | `23514` | `400` | `a value is not allowed here` |
|
|
171
|
+
| bad uuid/number/timestamp | `22xxx` (incl. `22P02`) | `400` | `a value in the request has the wrong format` |
|
|
172
|
+
| offset past the last row | `PGRST103` | `200` | empty page with the requested `limit`/`offset` and the true `total` |
|
|
173
|
+
|
|
174
|
+
Responses carry a stable `code` alongside the message
|
|
175
|
+
(`{"error":"…","code":"unique_violation"}`) so clients can branch without
|
|
176
|
+
parsing prose. Anything unmapped keeps PostgREST's status when it is a client
|
|
177
|
+
error and becomes `500` otherwise — with a generic message either way.
|
|
178
|
+
|
|
179
|
+
Catching these outside the router: `import { isHttpError } from '@revenexx/app-sdk'`.
|
|
180
|
+
Use `isHttpError(err)`, not `instanceof` — the package's two entrypoints are
|
|
181
|
+
separate bundles, so each carries its own copy of the class.
|
|
182
|
+
|
|
155
183
|
### Testing your App
|
|
156
184
|
|
|
157
185
|
Handlers are plain functions over a context object, so tests don't need any
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var HttpError = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
details;
|
|
5
|
+
code;
|
|
6
|
+
serverDetail;
|
|
7
|
+
/**
|
|
8
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
9
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
10
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
11
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
12
|
+
*/
|
|
13
|
+
__isHttpError = true;
|
|
14
|
+
constructor(status, message, details, options = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "HttpError";
|
|
17
|
+
this.status = status;
|
|
18
|
+
if (details !== void 0) this.details = details;
|
|
19
|
+
if (options.code !== void 0) this.code = options.code;
|
|
20
|
+
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function isHttpError(err) {
|
|
24
|
+
if (!err || typeof err !== "object") return false;
|
|
25
|
+
const e = err;
|
|
26
|
+
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
27
|
+
}
|
|
28
|
+
var notFound = (message = "not found") => new HttpError(404, message);
|
|
29
|
+
var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
|
|
30
|
+
var forbidden = (message = "forbidden") => new HttpError(403, message);
|
|
31
|
+
var conflict = (message = "conflict") => new HttpError(409, message);
|
|
32
|
+
|
|
33
|
+
export {
|
|
34
|
+
HttpError,
|
|
35
|
+
isHttpError,
|
|
36
|
+
notFound,
|
|
37
|
+
badRequest,
|
|
38
|
+
forbidden,
|
|
39
|
+
conflict
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=chunk-WJ7QJ3NU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\nexport const notFound = (message = 'not found'): HttpError => new HttpError(404, message);\nexport const badRequest = (message = 'bad request', details?: unknown): HttpError =>\n new HttpError(400, message, details);\nexport const forbidden = (message = 'forbidden'): HttpError => new HttpError(403, message);\nexport const conflict = (message = 'conflict'): HttpError => new HttpError(409, message);\n"],"mappings":";AA0BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAgB;AAAA,EAEzB,YAAY,QAAgB,SAAiB,SAAmB,UAA4B,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,QAAI,YAAY,OAAW,MAAK,UAAU;AAC1C,QAAI,QAAQ,SAAS,OAAW,MAAK,OAAO,QAAQ;AACpD,QAAI,QAAQ,iBAAiB,OAAW,MAAK,eAAe,QAAQ;AAAA,EACtE;AACF;AAGO,SAAS,YAAY,KAAgC;AAC1D,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI;AACV,SAAO,EAAE,kBAAkB,QAAS,EAAE,SAAS,eAAe,OAAO,EAAE,WAAW;AACpF;AAEO,IAAM,WAAW,CAAC,UAAU,gBAA2B,IAAI,UAAU,KAAK,OAAO;AACjF,IAAM,aAAa,CAAC,UAAU,eAAe,YAClD,IAAI,UAAU,KAAK,SAAS,OAAO;AAC9B,IAAM,YAAY,CAAC,UAAU,gBAA2B,IAAI,UAAU,KAAK,OAAO;AAClF,IAAM,WAAW,CAAC,UAAU,eAA0B,IAAI,UAAU,KAAK,OAAO;","names":[]}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared runtime types. The generated per-App client (emitted by
|
|
3
|
+
* @revenexx/app-sdk-cli) layers strongly-typed entity interfaces on top of
|
|
4
|
+
* these loose runtime shapes.
|
|
5
|
+
*/
|
|
6
|
+
type FilterOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'in' | 'is';
|
|
7
|
+
type Scalar = string | number | boolean | null;
|
|
8
|
+
/** A PostgREST filter: equality, an `in` list, or an explicit operator. */
|
|
9
|
+
type Filter = Scalar | Scalar[] | {
|
|
10
|
+
op: FilterOp;
|
|
11
|
+
value: unknown;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The query object is the one interface shared by every adapter: remote/runtime
|
|
15
|
+
* serialise it to a PostgREST querystring, mock applies it in memory — so App
|
|
16
|
+
* code is identical regardless of where the data lives.
|
|
17
|
+
*/
|
|
18
|
+
interface Query<T = Record<string, unknown>> {
|
|
19
|
+
where?: Partial<Record<keyof T & string, Filter>> & Record<string, Filter>;
|
|
20
|
+
select?: (keyof T & string)[] | string[];
|
|
21
|
+
order?: string;
|
|
22
|
+
limit?: number;
|
|
23
|
+
offset?: number;
|
|
24
|
+
}
|
|
25
|
+
type Op = 'list' | 'get' | 'create' | 'update' | 'delete';
|
|
26
|
+
interface ColumnDef {
|
|
27
|
+
type: string;
|
|
28
|
+
pk?: boolean;
|
|
29
|
+
notNull?: boolean;
|
|
30
|
+
default?: string | null;
|
|
31
|
+
check?: string;
|
|
32
|
+
}
|
|
33
|
+
/** A generated entity descriptor: maps an App entity to its real table + ops. */
|
|
34
|
+
interface Entity {
|
|
35
|
+
name: string;
|
|
36
|
+
table: string;
|
|
37
|
+
pk: string;
|
|
38
|
+
columns?: Record<string, ColumnDef>;
|
|
39
|
+
ops?: Op[] | Set<Op>;
|
|
40
|
+
}
|
|
41
|
+
type Row = Record<string, unknown>;
|
|
42
|
+
/** A page of rows plus the total count of matching rows (ignoring limit/offset). */
|
|
43
|
+
interface Page<T = Row> {
|
|
44
|
+
items: T[];
|
|
45
|
+
total: number;
|
|
46
|
+
limit?: number;
|
|
47
|
+
offset?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The data-plane contract. Implement this to add a new backend (e.g. GraphQL,
|
|
51
|
+
* a local SQLite file) and register it with `registerAdapter`.
|
|
52
|
+
*
|
|
53
|
+
* `page` is optional: adapters that can report a total (PostgREST `count=exact`,
|
|
54
|
+
* an in-memory store) implement it; others fall back to `list` only.
|
|
55
|
+
*/
|
|
56
|
+
interface Adapter {
|
|
57
|
+
readonly kind: string;
|
|
58
|
+
list(entity: Entity, query?: Query): Promise<Row[]>;
|
|
59
|
+
get(entity: Entity, id: string | number): Promise<Row | null>;
|
|
60
|
+
create(entity: Entity, data: Row): Promise<Row>;
|
|
61
|
+
update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
|
|
62
|
+
remove(entity: Entity, id: string | number): Promise<void>;
|
|
63
|
+
page?(entity: Entity, query?: Query): Promise<Page>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The one error representation every layer of the SDK agrees on.
|
|
68
|
+
*
|
|
69
|
+
* `HttpError` used to live in `./router/router.ts`. It moved here so the data
|
|
70
|
+
* adapters can raise it too: an adapter that knows a PostgREST failure is a
|
|
71
|
+
* duplicate key can say "409" without the router having to guess from a
|
|
72
|
+
* message string.
|
|
73
|
+
*
|
|
74
|
+
* Two fields exist purely to keep internal database detail out of responses:
|
|
75
|
+
* - `message` / `details` are the *client-facing* payload — always safe,
|
|
76
|
+
* never derived from a database error body.
|
|
77
|
+
* - `serverDetail` is the raw diagnosis. The router logs it and drops it; it
|
|
78
|
+
* is never serialised into a response.
|
|
79
|
+
*/
|
|
80
|
+
interface HttpErrorOptions {
|
|
81
|
+
/** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */
|
|
82
|
+
code?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Raw diagnosis for server-side logs and traces only — may contain table and
|
|
85
|
+
* constraint names. Never included in the HTTP response.
|
|
86
|
+
*/
|
|
87
|
+
serverDetail?: unknown;
|
|
88
|
+
}
|
|
89
|
+
/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */
|
|
90
|
+
declare class HttpError extends Error {
|
|
91
|
+
readonly status: number;
|
|
92
|
+
readonly details?: unknown;
|
|
93
|
+
readonly code?: string;
|
|
94
|
+
readonly serverDetail?: unknown;
|
|
95
|
+
/**
|
|
96
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
97
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
98
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
99
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
100
|
+
*/
|
|
101
|
+
readonly __isHttpError: true;
|
|
102
|
+
constructor(status: number, message: string, details?: unknown, options?: HttpErrorOptions);
|
|
103
|
+
}
|
|
104
|
+
/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */
|
|
105
|
+
declare function isHttpError(err: unknown): err is HttpError;
|
|
106
|
+
declare const notFound: (message?: string) => HttpError;
|
|
107
|
+
declare const badRequest: (message?: string, details?: unknown) => HttpError;
|
|
108
|
+
declare const forbidden: (message?: string) => HttpError;
|
|
109
|
+
declare const conflict: (message?: string) => HttpError;
|
|
110
|
+
|
|
111
|
+
export { type Adapter as A, type ColumnDef as C, type Entity as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type FilterOp as a, type HttpErrorOptions as b, badRequest as c, conflict as d, forbidden as f, isHttpError as i, notFound as n };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared runtime types. The generated per-App client (emitted by
|
|
3
|
+
* @revenexx/app-sdk-cli) layers strongly-typed entity interfaces on top of
|
|
4
|
+
* these loose runtime shapes.
|
|
5
|
+
*/
|
|
6
|
+
type FilterOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'in' | 'is';
|
|
7
|
+
type Scalar = string | number | boolean | null;
|
|
8
|
+
/** A PostgREST filter: equality, an `in` list, or an explicit operator. */
|
|
9
|
+
type Filter = Scalar | Scalar[] | {
|
|
10
|
+
op: FilterOp;
|
|
11
|
+
value: unknown;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The query object is the one interface shared by every adapter: remote/runtime
|
|
15
|
+
* serialise it to a PostgREST querystring, mock applies it in memory — so App
|
|
16
|
+
* code is identical regardless of where the data lives.
|
|
17
|
+
*/
|
|
18
|
+
interface Query<T = Record<string, unknown>> {
|
|
19
|
+
where?: Partial<Record<keyof T & string, Filter>> & Record<string, Filter>;
|
|
20
|
+
select?: (keyof T & string)[] | string[];
|
|
21
|
+
order?: string;
|
|
22
|
+
limit?: number;
|
|
23
|
+
offset?: number;
|
|
24
|
+
}
|
|
25
|
+
type Op = 'list' | 'get' | 'create' | 'update' | 'delete';
|
|
26
|
+
interface ColumnDef {
|
|
27
|
+
type: string;
|
|
28
|
+
pk?: boolean;
|
|
29
|
+
notNull?: boolean;
|
|
30
|
+
default?: string | null;
|
|
31
|
+
check?: string;
|
|
32
|
+
}
|
|
33
|
+
/** A generated entity descriptor: maps an App entity to its real table + ops. */
|
|
34
|
+
interface Entity {
|
|
35
|
+
name: string;
|
|
36
|
+
table: string;
|
|
37
|
+
pk: string;
|
|
38
|
+
columns?: Record<string, ColumnDef>;
|
|
39
|
+
ops?: Op[] | Set<Op>;
|
|
40
|
+
}
|
|
41
|
+
type Row = Record<string, unknown>;
|
|
42
|
+
/** A page of rows plus the total count of matching rows (ignoring limit/offset). */
|
|
43
|
+
interface Page<T = Row> {
|
|
44
|
+
items: T[];
|
|
45
|
+
total: number;
|
|
46
|
+
limit?: number;
|
|
47
|
+
offset?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The data-plane contract. Implement this to add a new backend (e.g. GraphQL,
|
|
51
|
+
* a local SQLite file) and register it with `registerAdapter`.
|
|
52
|
+
*
|
|
53
|
+
* `page` is optional: adapters that can report a total (PostgREST `count=exact`,
|
|
54
|
+
* an in-memory store) implement it; others fall back to `list` only.
|
|
55
|
+
*/
|
|
56
|
+
interface Adapter {
|
|
57
|
+
readonly kind: string;
|
|
58
|
+
list(entity: Entity, query?: Query): Promise<Row[]>;
|
|
59
|
+
get(entity: Entity, id: string | number): Promise<Row | null>;
|
|
60
|
+
create(entity: Entity, data: Row): Promise<Row>;
|
|
61
|
+
update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
|
|
62
|
+
remove(entity: Entity, id: string | number): Promise<void>;
|
|
63
|
+
page?(entity: Entity, query?: Query): Promise<Page>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The one error representation every layer of the SDK agrees on.
|
|
68
|
+
*
|
|
69
|
+
* `HttpError` used to live in `./router/router.ts`. It moved here so the data
|
|
70
|
+
* adapters can raise it too: an adapter that knows a PostgREST failure is a
|
|
71
|
+
* duplicate key can say "409" without the router having to guess from a
|
|
72
|
+
* message string.
|
|
73
|
+
*
|
|
74
|
+
* Two fields exist purely to keep internal database detail out of responses:
|
|
75
|
+
* - `message` / `details` are the *client-facing* payload — always safe,
|
|
76
|
+
* never derived from a database error body.
|
|
77
|
+
* - `serverDetail` is the raw diagnosis. The router logs it and drops it; it
|
|
78
|
+
* is never serialised into a response.
|
|
79
|
+
*/
|
|
80
|
+
interface HttpErrorOptions {
|
|
81
|
+
/** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */
|
|
82
|
+
code?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Raw diagnosis for server-side logs and traces only — may contain table and
|
|
85
|
+
* constraint names. Never included in the HTTP response.
|
|
86
|
+
*/
|
|
87
|
+
serverDetail?: unknown;
|
|
88
|
+
}
|
|
89
|
+
/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */
|
|
90
|
+
declare class HttpError extends Error {
|
|
91
|
+
readonly status: number;
|
|
92
|
+
readonly details?: unknown;
|
|
93
|
+
readonly code?: string;
|
|
94
|
+
readonly serverDetail?: unknown;
|
|
95
|
+
/**
|
|
96
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
97
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
98
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
99
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
100
|
+
*/
|
|
101
|
+
readonly __isHttpError: true;
|
|
102
|
+
constructor(status: number, message: string, details?: unknown, options?: HttpErrorOptions);
|
|
103
|
+
}
|
|
104
|
+
/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */
|
|
105
|
+
declare function isHttpError(err: unknown): err is HttpError;
|
|
106
|
+
declare const notFound: (message?: string) => HttpError;
|
|
107
|
+
declare const badRequest: (message?: string, details?: unknown) => HttpError;
|
|
108
|
+
declare const forbidden: (message?: string) => HttpError;
|
|
109
|
+
declare const conflict: (message?: string) => HttpError;
|
|
110
|
+
|
|
111
|
+
export { type Adapter as A, type ColumnDef as C, type Entity as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type FilterOp as a, type HttpErrorOptions as b, badRequest as c, conflict as d, forbidden as f, isHttpError as i, notFound as n };
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
23
|
DEFAULT_DATA_ENDPOINT: () => DEFAULT_DATA_ENDPOINT,
|
|
24
|
+
HttpError: () => HttpError,
|
|
24
25
|
adapterKinds: () => adapterKinds,
|
|
25
26
|
applyDefaults: () => applyDefaults,
|
|
26
27
|
createAdapter: () => createAdapter,
|
|
@@ -28,6 +29,7 @@ __export(src_exports, {
|
|
|
28
29
|
createMockAdapter: () => createMockAdapter,
|
|
29
30
|
createRemoteAdapter: () => createRemoteAdapter,
|
|
30
31
|
createRuntimeAdapter: () => createRuntimeAdapter,
|
|
32
|
+
isHttpError: () => isHttpError,
|
|
31
33
|
matches: () => matches,
|
|
32
34
|
opsFromAccess: () => opsFromAccess,
|
|
33
35
|
registerAdapter: () => registerAdapter,
|
|
@@ -183,6 +185,116 @@ function createMockAdapter(seed = {}) {
|
|
|
183
185
|
};
|
|
184
186
|
}
|
|
185
187
|
|
|
188
|
+
// src/errors.ts
|
|
189
|
+
var HttpError = class extends Error {
|
|
190
|
+
status;
|
|
191
|
+
details;
|
|
192
|
+
code;
|
|
193
|
+
serverDetail;
|
|
194
|
+
/**
|
|
195
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
196
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
197
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
198
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
199
|
+
*/
|
|
200
|
+
__isHttpError = true;
|
|
201
|
+
constructor(status, message, details, options = {}) {
|
|
202
|
+
super(message);
|
|
203
|
+
this.name = "HttpError";
|
|
204
|
+
this.status = status;
|
|
205
|
+
if (details !== void 0) this.details = details;
|
|
206
|
+
if (options.code !== void 0) this.code = options.code;
|
|
207
|
+
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
function isHttpError(err) {
|
|
211
|
+
if (!err || typeof err !== "object") return false;
|
|
212
|
+
const e = err;
|
|
213
|
+
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/adapters/postgrest-error.ts
|
|
217
|
+
function parseBody(body) {
|
|
218
|
+
if (!body) return {};
|
|
219
|
+
try {
|
|
220
|
+
const parsed = JSON.parse(body);
|
|
221
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
222
|
+
} catch {
|
|
223
|
+
return {};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
var BY_SQLSTATE = {
|
|
227
|
+
"23505": { status: 409, code: "unique_violation", message: "a record with this value already exists" },
|
|
228
|
+
"23P01": { status: 409, code: "exclusion_violation", message: "a record conflicts with an existing one" },
|
|
229
|
+
"23502": { status: 400, code: "not_null_violation", message: "a required value is missing" },
|
|
230
|
+
"23514": { status: 400, code: "check_violation", message: "a value is not allowed here" },
|
|
231
|
+
"22P02": { status: 400, code: "invalid_value", message: "a value in the request has the wrong format" }
|
|
232
|
+
};
|
|
233
|
+
var CLIENT_STATUS = {
|
|
234
|
+
400: "the request could not be processed",
|
|
235
|
+
401: "unauthenticated",
|
|
236
|
+
403: "forbidden",
|
|
237
|
+
404: "not found",
|
|
238
|
+
405: "method not allowed",
|
|
239
|
+
406: "the requested representation is not available",
|
|
240
|
+
409: "the request conflicts with the current state of the data",
|
|
241
|
+
413: "the request is too large",
|
|
242
|
+
415: "unsupported media type",
|
|
243
|
+
422: "the request could not be processed",
|
|
244
|
+
429: "too many requests"
|
|
245
|
+
};
|
|
246
|
+
function foreignKey(pg, method) {
|
|
247
|
+
const blocked = {
|
|
248
|
+
status: 409,
|
|
249
|
+
code: "foreign_key_violation",
|
|
250
|
+
message: "this record is still referenced by other records"
|
|
251
|
+
};
|
|
252
|
+
const missing = {
|
|
253
|
+
status: 400,
|
|
254
|
+
code: "foreign_key_violation",
|
|
255
|
+
message: "a referenced record does not exist"
|
|
256
|
+
};
|
|
257
|
+
const text = `${pg.details ?? ""} ${pg.message ?? ""}`;
|
|
258
|
+
if (/is still referenced from/i.test(text)) return blocked;
|
|
259
|
+
if (/is not present in table/i.test(text)) return missing;
|
|
260
|
+
return method.toUpperCase() === "DELETE" ? blocked : missing;
|
|
261
|
+
}
|
|
262
|
+
function classify(status, pg, method) {
|
|
263
|
+
const sqlstate = typeof pg.code === "string" ? pg.code : "";
|
|
264
|
+
if (sqlstate === "23503") return foreignKey(pg, method);
|
|
265
|
+
const known = BY_SQLSTATE[sqlstate];
|
|
266
|
+
if (known) return known;
|
|
267
|
+
if (/^22/.test(sqlstate)) {
|
|
268
|
+
return { status: 400, code: "invalid_value", message: "a value in the request has the wrong format" };
|
|
269
|
+
}
|
|
270
|
+
const generic = CLIENT_STATUS[status];
|
|
271
|
+
if (generic) return { status, code: "bad_request", message: generic };
|
|
272
|
+
return { status: 500, code: "data_error", message: "the data service could not complete the request" };
|
|
273
|
+
}
|
|
274
|
+
function postgrestError(status, body, context) {
|
|
275
|
+
const pg = parseBody(body);
|
|
276
|
+
const mapped = classify(status, pg, context.method);
|
|
277
|
+
return new HttpError(mapped.status, mapped.message, void 0, {
|
|
278
|
+
code: mapped.code,
|
|
279
|
+
serverDetail: {
|
|
280
|
+
source: "postgrest",
|
|
281
|
+
status,
|
|
282
|
+
method: context.method,
|
|
283
|
+
...context.table ? { table: context.table } : {},
|
|
284
|
+
sqlstate: pg.code ?? null,
|
|
285
|
+
message: pg.message ?? (body || null),
|
|
286
|
+
details: pg.details ?? null,
|
|
287
|
+
hint: pg.hint ?? null
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
function rangeNotSatisfiable(status, body) {
|
|
292
|
+
if (status !== 416) return null;
|
|
293
|
+
const pg = parseBody(body);
|
|
294
|
+
const m = /there are only (\d+) rows/i.exec(`${pg.details ?? ""} ${pg.message ?? ""}`);
|
|
295
|
+
return { total: m ? Number.parseInt(m[1], 10) : 0 };
|
|
296
|
+
}
|
|
297
|
+
|
|
186
298
|
// src/adapters/remote.ts
|
|
187
299
|
function createRemoteAdapter(config) {
|
|
188
300
|
const f = config.fetchImpl ?? globalThis.fetch;
|
|
@@ -198,54 +310,79 @@ function createRemoteAdapter(config) {
|
|
|
198
310
|
if (config.market) h["X-Revenexx-Market"] = config.market;
|
|
199
311
|
return h;
|
|
200
312
|
};
|
|
201
|
-
async function
|
|
313
|
+
async function send(method, path, opts = {}) {
|
|
202
314
|
const res = await f(`${base}${path}`, {
|
|
203
315
|
method,
|
|
204
316
|
headers: headers(opts.prefer ? { Prefer: opts.prefer } : {}),
|
|
205
317
|
body: opts.body != null ? JSON.stringify(opts.body) : void 0
|
|
206
318
|
});
|
|
207
319
|
const text = await res.text();
|
|
208
|
-
|
|
320
|
+
const range = res.headers?.get?.("content-range") ?? "";
|
|
321
|
+
const total = Number.parseInt(range.split("/")[1] ?? "", 10);
|
|
322
|
+
return { status: res.status, ok: res.ok, text, total: Number.isFinite(total) ? total : null };
|
|
323
|
+
}
|
|
324
|
+
async function req(method, path, opts = {}) {
|
|
325
|
+
const { ok, status, text } = await send(method, path, opts);
|
|
326
|
+
if (!ok) throw postgrestError(status, text, { method, table: opts.table });
|
|
209
327
|
return text ? JSON.parse(text) : null;
|
|
210
328
|
}
|
|
211
329
|
return {
|
|
212
330
|
kind: "remote",
|
|
213
331
|
async list(entity, query = {}) {
|
|
214
332
|
const qs = toParams(query).toString();
|
|
215
|
-
|
|
333
|
+
const { ok, status, text } = await send("GET", `/${entity.table}${qs ? `?${qs}` : ""}`, {
|
|
334
|
+
table: entity.table
|
|
335
|
+
});
|
|
336
|
+
if (!ok) {
|
|
337
|
+
if (rangeNotSatisfiable(status, text)) return [];
|
|
338
|
+
throw postgrestError(status, text, { method: "GET", table: entity.table });
|
|
339
|
+
}
|
|
340
|
+
return (text ? JSON.parse(text) : []) ?? [];
|
|
216
341
|
},
|
|
217
342
|
async get(entity, id) {
|
|
218
|
-
const rows = await req("GET", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&limit=1
|
|
343
|
+
const rows = await req("GET", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&limit=1`, {
|
|
344
|
+
table: entity.table
|
|
345
|
+
});
|
|
219
346
|
return rows?.[0] ?? null;
|
|
220
347
|
},
|
|
221
348
|
async create(entity, data) {
|
|
222
|
-
const rows = await req("POST", `/${entity.table}`, {
|
|
349
|
+
const rows = await req("POST", `/${entity.table}`, {
|
|
350
|
+
body: data,
|
|
351
|
+
prefer: "return=representation",
|
|
352
|
+
table: entity.table
|
|
353
|
+
});
|
|
223
354
|
return Array.isArray(rows) ? rows[0] : rows;
|
|
224
355
|
},
|
|
225
356
|
async update(entity, id, patch) {
|
|
226
357
|
const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
227
358
|
body: patch,
|
|
228
|
-
prefer: "return=representation"
|
|
359
|
+
prefer: "return=representation",
|
|
360
|
+
table: entity.table
|
|
229
361
|
});
|
|
230
362
|
return Array.isArray(rows) ? rows[0] : rows;
|
|
231
363
|
},
|
|
232
364
|
async remove(entity, id) {
|
|
233
|
-
await req("DELETE", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}
|
|
365
|
+
await req("DELETE", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
366
|
+
table: entity.table
|
|
367
|
+
});
|
|
234
368
|
},
|
|
235
369
|
async page(entity, query = {}) {
|
|
236
370
|
const qs = toParams(query).toString();
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
371
|
+
const { ok, status, text, total } = await send("GET", `/${entity.table}${qs ? `?${qs}` : ""}`, {
|
|
372
|
+
prefer: "count=exact",
|
|
373
|
+
table: entity.table
|
|
240
374
|
});
|
|
241
|
-
|
|
242
|
-
|
|
375
|
+
if (!ok) {
|
|
376
|
+
const overflow = rangeNotSatisfiable(status, text);
|
|
377
|
+
if (overflow) {
|
|
378
|
+
return { items: [], total: total ?? overflow.total, limit: query.limit, offset: query.offset };
|
|
379
|
+
}
|
|
380
|
+
throw postgrestError(status, text, { method: "GET", table: entity.table });
|
|
381
|
+
}
|
|
243
382
|
const items = text ? JSON.parse(text) : [];
|
|
244
|
-
const range = res.headers.get("content-range") ?? "";
|
|
245
|
-
const total = Number.parseInt(range.split("/")[1] ?? "", 10);
|
|
246
383
|
return {
|
|
247
384
|
items,
|
|
248
|
-
total:
|
|
385
|
+
total: total ?? items.length,
|
|
249
386
|
limit: query.limit,
|
|
250
387
|
offset: query.offset
|
|
251
388
|
};
|
|
@@ -336,6 +473,7 @@ function createClient(config) {
|
|
|
336
473
|
// Annotate the CommonJS export names for ESM import in node:
|
|
337
474
|
0 && (module.exports = {
|
|
338
475
|
DEFAULT_DATA_ENDPOINT,
|
|
476
|
+
HttpError,
|
|
339
477
|
adapterKinds,
|
|
340
478
|
applyDefaults,
|
|
341
479
|
createAdapter,
|
|
@@ -343,6 +481,7 @@ function createClient(config) {
|
|
|
343
481
|
createMockAdapter,
|
|
344
482
|
createRemoteAdapter,
|
|
345
483
|
createRuntimeAdapter,
|
|
484
|
+
isHttpError,
|
|
346
485
|
matches,
|
|
347
486
|
opsFromAccess,
|
|
348
487
|
registerAdapter,
|