@softistx/riva-rest 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/bff/index.d.ts +15 -0
- package/dist/bff/index.d.ts.map +1 -0
- package/dist/bff/index.js +21 -0
- package/dist/bff/index.js.map +10 -0
- package/dist/chunks/index-9628zgfc.js +8 -0
- package/dist/chunks/index-9628zgfc.js.map +10 -0
- package/dist/chunks/index-ytrzmcp0.js +28 -0
- package/dist/chunks/index-ytrzmcp0.js.map +10 -0
- package/dist/entities/index.d.ts +27 -0
- package/dist/entities/index.d.ts.map +1 -0
- package/dist/entities/index.js +38 -0
- package/dist/entities/index.js.map +10 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/http-transport.d.ts +13 -0
- package/dist/http-transport.d.ts.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +148 -0
- package/dist/index.js.map +14 -0
- package/dist/operation.d.ts +16 -0
- package/dist/operation.d.ts.map +1 -0
- package/dist/query.d.ts +44 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/server/index.d.ts +18 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +45 -0
- package/dist/server/index.js.map +10 -0
- package/dist/transport.d.ts +38 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/types.d.ts +42 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/wire.d.ts +5 -0
- package/dist/wire.d.ts.map +1 -0
- package/docs/README.md +19 -0
- package/docs/guide/bff.md +92 -0
- package/docs/guide/cache.md +44 -0
- package/docs/guide/errors.md +33 -0
- package/docs/guide/free-fetcher.md +47 -0
- package/docs/guide/openapi.md +45 -0
- package/docs/guide/transport.md +49 -0
- package/docs/troubleshooting.md +184 -0
- package/package.json +85 -5
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/query.ts", "../src/errors.ts", "../src/operation.ts", "../src/http-transport.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { OperationsShape } from '@softistx/openapi-httpyz';\nimport {\n\ttype CachePolicy,\n\tmutation as coreMutation,\n\tquery as coreQuery,\n\ttype FetchContext,\n\ttype Mutation,\n\ttype MutationOptions,\n\ttype Query,\n\ttype QueryOptions,\n\tRivaError,\n} from '@softistx/riva';\nimport { toRivaError } from './errors';\nimport { operationOf } from './operation';\nimport {\n\ttype RestContext,\n\ttype Route,\n\trestContext,\n\ttransportOf,\n} from './transport';\nimport type {\n\tClientOf,\n\tDataOf,\n\tDecodedOf,\n\tInputOf,\n\tMutationRoute,\n\tQueryRoute,\n} from './types';\n\n/** The core's query options, minus what the route gives. */\nexport type RestQueryOptions<Vars, Data> = Omit<\n\tQueryOptions<Vars, Data>,\n\t'id' | 'fetch' | 'derive'\n> & {\n\t/** Replaces the id derived from the route (to define one route twice with different options). */\n\tid?: string;\n};\n\nexport type RestMutationOptions<Vars, Data> = Omit<\n\tMutationOptions<Vars, Data>,\n\t'id' | 'run'\n> & {\n\t/** Replaces the id derived from the route. */\n\tid?: string;\n};\n\n/** A query over a function you write, for an API with no schema. */\nexport type FreeQueryOptions<Vars, Data> = Omit<\n\tQueryOptions<Vars, Data>,\n\t'fetch' | 'derive'\n> & {\n\t/** The cache key's base: required, since a function has no name to derive one from. */\n\tid: string;\n\t/** Fetches the data. Errors it throws from httpyz are mapped to riva's. */\n\tfetch: (vars: Vars, ctx: RestContext) => Promise<Data>;\n};\n\nexport type FreeMutationOptions<Vars, Data> = Omit<\n\tMutationOptions<Vars, Data>,\n\t'run'\n> & {\n\tid: string;\n\trun: (vars: Vars, ctx: RestContext) => Promise<Data>;\n};\n\nconst callOf =\n\t(route: Route) =>\n\tasync (vars: unknown, ctx: FetchContext): Promise<unknown> =>\n\t\ttransportOf(ctx.client).call(route, vars, { signal: ctx.signal });\n\nconst guarded =\n\t<Vars, Data>(fn: (vars: Vars, ctx: RestContext) => Promise<Data>) =>\n\tasync (vars: Vars, ctx: FetchContext): Promise<Data> => {\n\t\ttry {\n\t\t\treturn await fn(vars, restContext(ctx));\n\t\t} catch (error) {\n\t\t\tthrow toRivaError(error, ctx.signal);\n\t\t}\n\t};\n\nconst isFree = (a: unknown): a is { id: string } =>\n\ttypeof a === 'object' && a !== null && !('operations' in a);\n\nfunction freeId(opts: { id?: unknown }, name: string): void {\n\tif (typeof opts?.id !== 'string' || !opts.id)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: ${name}() needs an id; a function has no name to derive one from.`,\n\t\t);\n}\n\n/**\n * A query definition. Two forms:\n *\n * - `query(api, 'get /invoices/{id}', opts?)`: from an OpenAPI client\n * (`createOpenApiClient`); the variables are the operation's input and the\n * data its 2xx reply, both typed from the spec, and the id is the route.\n * Throws a `RivaError` (`RIVA_DEFINITION`) for a route the client's spec does not have.\n * - `query({ id, fetch })`: a free fetcher for an API with no schema, typed\n * by the generics or the fetcher's own types.\n */\nexport function query<\n\tOps extends OperationsShape<Ops>,\n\tApi extends ClientOf<Ops, boolean>,\n\tR extends QueryRoute<Ops>,\n>(\n\tapi: Api & ClientOf<Ops, boolean>,\n\troute: R,\n\topts?: RestQueryOptions<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>,\n): Query<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>;\nexport function query<Vars = void, Data = unknown>(\n\topts: FreeQueryOptions<Vars, Data>,\n): Query<Vars, Data>;\nexport function query(\n\tfirst: unknown,\n\troute?: string,\n\topts: { id?: string } = {},\n): unknown {\n\tif (isFree(first)) {\n\t\tfreeId(first, 'query');\n\t\tconst { fetch, ...rest } = first as unknown as FreeQueryOptions<\n\t\t\tunknown,\n\t\t\tunknown\n\t\t>;\n\t\treturn coreQuery({ ...rest, fetch: guarded(fetch) });\n\t}\n\tconst op = operationOf(first as never, route as never, 'query');\n\treturn coreQuery({\n\t\t...(opts as object),\n\t\tid: opts.id ?? op.id,\n\t\tfetch: callOf(op),\n\t} as QueryOptions<unknown, unknown>);\n}\n\n/**\n * A mutation definition, in the same two forms as `query`:\n * `mutation(api, 'post /invoices', opts?)` or `mutation({ id, run })`.\n */\nexport function mutation<\n\tOps extends OperationsShape<Ops>,\n\tApi extends ClientOf<Ops, boolean>,\n\tR extends MutationRoute<Ops>,\n>(\n\tapi: Api & ClientOf<Ops, boolean>,\n\troute: R,\n\topts?: RestMutationOptions<\n\t\tInputOf<Ops, R>,\n\t\tDataOf<Ops, R, DecodedOf<Ops, Api>>\n\t>,\n): Mutation<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>;\nexport function mutation<Vars = void, Data = unknown>(\n\topts: FreeMutationOptions<Vars, Data>,\n): Mutation<Vars, Data>;\nexport function mutation(\n\tfirst: unknown,\n\troute?: string,\n\topts: { id?: string } = {},\n): unknown {\n\tif (isFree(first)) {\n\t\tfreeId(first, 'mutation');\n\t\tconst { run, ...rest } = first as unknown as FreeMutationOptions<\n\t\t\tunknown,\n\t\t\tunknown\n\t\t>;\n\t\treturn coreMutation({ ...rest, run: guarded(run) });\n\t}\n\tconst op = operationOf(first as never, route as never, 'mutation');\n\treturn coreMutation({\n\t\t...(opts as object),\n\t\tid: opts.id ?? op.id,\n\t\trun: callOf(op),\n\t} as MutationOptions<unknown, unknown>);\n}\n\nexport type { CachePolicy };\n",
|
|
6
|
+
"import {\n\tRivaAbortError,\n\tRivaHttpError,\n\tRivaNetworkError,\n\tRivaRequestError,\n} from '@softistx/riva';\n\n// The httpyz errors are read by name, not by `instanceof`, so a second copy of\n// the package (or none imported here) still maps, and this entry never imports\n// httpyz at runtime.\ntype Failure = Error & {\n\tstatus?: number;\n\tmethod?: unknown;\n\tpath?: unknown;\n\tfailure?: { kind?: string; status?: number };\n};\n\nconst isErrorNamed = (e: unknown, name: string): e is Failure =>\n\te instanceof Error && e.name === name;\n\n// Name alone is not enough: zod has a `ValidationError`, the platform a\n// `TimeoutError`. httpyz's `ClientError`s carry the call they belong to.\nconst isNamed = (e: unknown, name: string): e is Failure =>\n\tisErrorNamed(e, name) &&\n\ttypeof e.method === 'string' &&\n\ttypeof e.path === 'string';\n\n/**\n * Maps what `@softistx/httpyz` throws to riva's errors, so the core's retry\n * policy and `instanceof` checks work:\n *\n * - the caller's abort: `RivaAbortError`;\n * - `UndeclaredStatusError` and `ReplyStatusError`: `RivaHttpError`, retryable\n * for 5xx, 408 and 429;\n * - `NetworkError` and `TimeoutError`: `RivaNetworkError`, retryable;\n * - `ValidationError`: a non-retryable `RivaRequestError`, `RIVA_VALIDATION`\n * for a request the spec refused (never sent) and `RIVA_INVALID_RESPONSE`\n * for a reply the spec does not describe.\n *\n * Each keeps the httpyz error as its `cause`; anything else is returned as it\n * is.\n */\nexport function toRivaError(error: unknown, signal?: AbortSignal): unknown {\n\tif (error instanceof RivaAbortError) return error;\n\tif (\n\t\tsignal?.aborted ||\n\t\t(error instanceof Error && error.name === 'AbortError')\n\t)\n\t\treturn new RivaAbortError();\n\tif (error instanceof RivaHttpError || error instanceof RivaNetworkError)\n\t\treturn error;\n\tif (\n\t\t(isNamed(error, 'UndeclaredStatusError') ||\n\t\t\tisErrorNamed(error, 'ReplyStatusError')) &&\n\t\ttypeof error.status === 'number'\n\t)\n\t\treturn new RivaHttpError(error.status, error.message, { cause: error });\n\tif (isNamed(error, 'NetworkError') || isNamed(error, 'TimeoutError'))\n\t\treturn new RivaNetworkError(error.message, { cause: error });\n\tif (\n\t\tisNamed(error, 'ValidationError') &&\n\t\t(error.failure?.kind === 'request' || error.failure?.kind === 'response')\n\t)\n\t\treturn new RivaRequestError(\n\t\t\terror.failure?.kind === 'request'\n\t\t\t\t? 'RIVA_VALIDATION'\n\t\t\t\t: 'RIVA_INVALID_RESPONSE',\n\t\t\terror.message,\n\t\t\t{ retryable: false, cause: error },\n\t\t);\n\treturn error;\n}\n",
|
|
7
|
+
"import type { OperationsShape } from '@softistx/openapi-httpyz';\nimport { RivaError } from '@softistx/riva';\nimport type { Route } from './transport';\nimport type { RouteOf, SpecOf } from './types';\nimport { SAFE } from './wire';\n\n/** What a route is read into: the transport's `Route`, and the definition's id (`'get /invoices/{id}'`). */\nexport interface Operation extends Route {\n\treadonly id: string;\n}\n\n/**\n * Reads a route once, against the client's own operation table. Throws a\n * `RivaError` (`RIVA_DEFINITION`) for a route that is not `'<method> <path>'`, that the spec has\n * no operation for, or whose method does not fit the definition: a query is\n * a read (GET, HEAD, OPTIONS, QUERY, or a POST that only reads), a mutation\n * is not a GET, HEAD or OPTIONS.\n */\nexport function operationOf<Ops extends OperationsShape<Ops>>(\n\tspec: SpecOf<Ops>,\n\troute: RouteOf<Ops>,\n\tkind: 'query' | 'mutation',\n): Operation {\n\tif (typeof route !== 'string')\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: ${String(route)} is not a route; write it as '<method> <path>' (get /invoices/{id}).`,\n\t\t);\n\tconst at = route.indexOf(' ');\n\tconst method = at > 0 ? route.slice(0, at) : '';\n\tconst path = at > 0 ? route.slice(at + 1) : '';\n\tif (!method || !path.startsWith('/'))\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: \"${route}\" is not a route; write it as '<method> <path>' (get /invoices/{id}).`,\n\t\t);\n\tconst table = (spec?.operations ?? {}) as unknown as Record<\n\t\tstring,\n\t\t{ method: string; path: string; parameters?: unknown[]; body?: unknown }\n\t>;\n\tconst found = Object.entries(table).find(\n\t\t([, o]) => o.method === method && o.path === path,\n\t);\n\tif (!found)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: the OpenAPI client has no operation at ${method.toUpperCase()} ${path}; check the path as the spec writes it.`,\n\t\t);\n\tif (kind === 'query' && ['put', 'patch', 'delete'].includes(method))\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: ${method.toUpperCase()} ${path} changes data; define it with mutation(), not query().`,\n\t\t);\n\tif (kind === 'mutation' && SAFE.has(method))\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-rest: ${method.toUpperCase()} ${path} only reads; define it with query(), not mutation().`,\n\t\t);\n\tconst [operationId, entry] = found;\n\treturn {\n\t\tid: `${method} ${path}`,\n\t\tmethod,\n\t\tpath,\n\t\toperationId,\n\t\thasInput: (entry.parameters?.length ?? 0) > 0 || entry.body !== undefined,\n\t};\n}\n",
|
|
8
|
+
"import type { HttpClient } from '@softistx/httpyz';\nimport type { OpenApiClient } from '@softistx/openapi-httpyz';\nimport { RivaHttpError, RivaRequestError } from '@softistx/riva';\nimport { toRivaError } from './errors';\nimport type { RestTransport } from './transport';\n\ntype Reply = { status: number; data?: unknown };\ntype ByOperation = (id: string, ...args: unknown[]) => Promise<Reply>;\n\n// A transport that cannot run the call is a wiring mistake: retrying repeats it.\nconst unwired = (message: string) =>\n\tnew RivaRequestError('RIVA_REST_UNWIRED', message, { retryable: false });\n\n/**\n * The transport over an httpyz client and, for OpenAPI definitions, the\n * client `createOpenApiClient(http, operations)` made over it. A call goes\n * through `api.<method>(path, input, { signal })`, so the spec's validation,\n * decoding and the client's middleware, auth, retries and timeouts all apply.\n * The data of the 2xx reply is returned; a declared reply of another status\n * throws `RivaHttpError`; httpyz's errors are mapped by `toRivaError`.\n */\nexport function httpyzTransport(\n\thttp: HttpClient,\n\t// biome-ignore lint/suspicious/noExplicitAny: any spec's client\n\tapi?: OpenApiClient<any, any, any>,\n): RestTransport {\n\treturn {\n\t\thttp,\n\t\tasync call(route, input, { signal }) {\n\t\t\tif (!api)\n\t\t\t\tthrow unwired(\n\t\t\t\t\t'This REST transport has no OpenAPI client: build it with httpyzTransport(http, api) to run OpenAPI definitions.',\n\t\t\t\t);\n\t\t\tconst op = (api as unknown as { op?: ByOperation }).op;\n\t\t\tconst known = (api.operations as unknown as Record<string, unknown>)?.[\n\t\t\t\troute.operationId\n\t\t\t];\n\t\t\tif (typeof op !== 'function' || !known)\n\t\t\t\tthrow unwired(\n\t\t\t\t\t`riva-rest: the OpenAPI client has no ${route.method.toUpperCase()} ${route.path}.`,\n\t\t\t\t);\n\t\t\ttry {\n\t\t\t\tconst reply = await (route.hasInput\n\t\t\t\t\t? op.call(api, route.operationId, input ?? {}, { signal })\n\t\t\t\t\t: op.call(api, route.operationId, { signal }));\n\t\t\t\tif (reply.status < 200 || reply.status >= 300)\n\t\t\t\t\tthrow new RivaHttpError(\n\t\t\t\t\t\treply.status,\n\t\t\t\t\t\t`${route.method.toUpperCase()} ${route.path}: HTTP ${reply.status}`,\n\t\t\t\t\t\t{ cause: reply },\n\t\t\t\t\t);\n\t\t\t\treturn reply.data;\n\t\t\t} catch (error) {\n\t\t\t\tthrow toRivaError(error, signal);\n\t\t\t}\n\t\t},\n\t};\n}\n",
|
|
9
|
+
"import { mutation, query } from './query';\n\nexport { toRivaError } from './errors';\nexport { httpyzTransport } from './http-transport';\nexport { type Operation, operationOf } from './operation';\nexport {\n\ttype FreeMutationOptions,\n\ttype FreeQueryOptions,\n\tmutation,\n\tquery,\n\ttype RestMutationOptions,\n\ttype RestQueryOptions,\n} from './query';\nexport {\n\tprovideRest,\n\ttype RestContext,\n\ttype RestTransport,\n\ttype Route,\n} from './transport';\nexport type {\n\tClientOf,\n\tDataOf,\n\tDecodedOf,\n\tInputOf,\n\tMutationRoute,\n\tQueryRoute,\n\tRouteOf,\n\tSpecOf,\n} from './types';\n\n/** `rest.query(api, 'get /invoices/{id}')`, beside the named exports. */\nexport const rest = { query, mutation } as const;\n"
|
|
10
|
+
],
|
|
11
|
+
"mappings": ";;;;;;;;;;AACA;AAAA,cAEC;AAAA,WACA;AAAA,eAMA;AAAA;;;ACVD;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,IAAM,eAAe,CAAC,GAAY,SACjC,aAA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,OAAO,OAAO,cAAc,CAAC;AAAA,QAChC,MAAM,QACL,wCAAwC,MAAM,OAAO,YAAY,KAAK,MAAM,OAC7E;AAAA,MACD,IAAI;AAAA,QACH,MAAM,QAAQ,OAAO,MAAM,WACxB,GAAG,KAAK,KAAK,MAAM,aAAa,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,IACvD,GAAG,KAAK,KAAK,MAAM,aAAa,EAAE,OAAO,CAAC;AAAA,QAC7C,IAAI,MAAM,SAAS,OAAO,MAAM,UAAU;AAAA,UACzC,MAAM,IAAI,eACT,MAAM,QACN,GAAG,MAAM,OAAO,YAAY,KAAK,MAAM,cAAc,MAAM,UAC3D,EAAE,OAAO,MAAM,CAChB;AAAA,QACD,OAAO,MAAM;AAAA,QACZ,OAAO,OAAO;AAAA,QACf,MAAM,YAAY,OAAO,MAAM;AAAA;AAAA;AAAA,EAGlC;AAAA;;;ACzBM,IAAM,OAAO,EAAE,OAAO,SAAS;",
|
|
12
|
+
"debugId": "4C7DB21650D38CAF64756E2164756E21",
|
|
13
|
+
"names": []
|
|
14
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { OperationsShape } from '@softistx/openapi-httpyz';
|
|
2
|
+
import type { Route } from './transport';
|
|
3
|
+
import type { RouteOf, SpecOf } from './types';
|
|
4
|
+
/** What a route is read into: the transport's `Route`, and the definition's id (`'get /invoices/{id}'`). */
|
|
5
|
+
export interface Operation extends Route {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Reads a route once, against the client's own operation table. Throws a
|
|
10
|
+
* `RivaError` (`RIVA_DEFINITION`) for a route that is not `'<method> <path>'`, that the spec has
|
|
11
|
+
* no operation for, or whose method does not fit the definition: a query is
|
|
12
|
+
* a read (GET, HEAD, OPTIONS, QUERY, or a POST that only reads), a mutation
|
|
13
|
+
* is not a GET, HEAD or OPTIONS.
|
|
14
|
+
*/
|
|
15
|
+
export declare function operationOf<Ops extends OperationsShape<Ops>>(spec: SpecOf<Ops>, route: RouteOf<Ops>, kind: 'query' | 'mutation'): Operation;
|
|
16
|
+
//# sourceMappingURL=operation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operation.d.ts","sourceRoot":"","sources":["../src/operation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAEhE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAG/C,4GAA4G;AAC5G,MAAM,WAAW,SAAU,SAAQ,KAAK;IACvC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC,EAC3D,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,EACjB,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,EACnB,IAAI,EAAE,OAAO,GAAG,UAAU,GACxB,SAAS,CA4CX"}
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { OperationsShape } from '@softistx/openapi-httpyz';
|
|
2
|
+
import { type CachePolicy, type Mutation, type MutationOptions, type Query, type QueryOptions } from '@softistx/riva';
|
|
3
|
+
import { type RestContext } from './transport';
|
|
4
|
+
import type { ClientOf, DataOf, DecodedOf, InputOf, MutationRoute, QueryRoute } from './types';
|
|
5
|
+
/** The core's query options, minus what the route gives. */
|
|
6
|
+
export type RestQueryOptions<Vars, Data> = Omit<QueryOptions<Vars, Data>, 'id' | 'fetch' | 'derive'> & {
|
|
7
|
+
/** Replaces the id derived from the route (to define one route twice with different options). */
|
|
8
|
+
id?: string;
|
|
9
|
+
};
|
|
10
|
+
export type RestMutationOptions<Vars, Data> = Omit<MutationOptions<Vars, Data>, 'id' | 'run'> & {
|
|
11
|
+
/** Replaces the id derived from the route. */
|
|
12
|
+
id?: string;
|
|
13
|
+
};
|
|
14
|
+
/** A query over a function you write, for an API with no schema. */
|
|
15
|
+
export type FreeQueryOptions<Vars, Data> = Omit<QueryOptions<Vars, Data>, 'fetch' | 'derive'> & {
|
|
16
|
+
/** The cache key's base: required, since a function has no name to derive one from. */
|
|
17
|
+
id: string;
|
|
18
|
+
/** Fetches the data. Errors it throws from httpyz are mapped to riva's. */
|
|
19
|
+
fetch: (vars: Vars, ctx: RestContext) => Promise<Data>;
|
|
20
|
+
};
|
|
21
|
+
export type FreeMutationOptions<Vars, Data> = Omit<MutationOptions<Vars, Data>, 'run'> & {
|
|
22
|
+
id: string;
|
|
23
|
+
run: (vars: Vars, ctx: RestContext) => Promise<Data>;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* A query definition. Two forms:
|
|
27
|
+
*
|
|
28
|
+
* - `query(api, 'get /invoices/{id}', opts?)`: from an OpenAPI client
|
|
29
|
+
* (`createOpenApiClient`); the variables are the operation's input and the
|
|
30
|
+
* data its 2xx reply, both typed from the spec, and the id is the route.
|
|
31
|
+
* Throws a `RivaError` (`RIVA_DEFINITION`) for a route the client's spec does not have.
|
|
32
|
+
* - `query({ id, fetch })`: a free fetcher for an API with no schema, typed
|
|
33
|
+
* by the generics or the fetcher's own types.
|
|
34
|
+
*/
|
|
35
|
+
export declare function query<Ops extends OperationsShape<Ops>, Api extends ClientOf<Ops, boolean>, R extends QueryRoute<Ops>>(api: Api & ClientOf<Ops, boolean>, route: R, opts?: RestQueryOptions<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>): Query<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>;
|
|
36
|
+
export declare function query<Vars = void, Data = unknown>(opts: FreeQueryOptions<Vars, Data>): Query<Vars, Data>;
|
|
37
|
+
/**
|
|
38
|
+
* A mutation definition, in the same two forms as `query`:
|
|
39
|
+
* `mutation(api, 'post /invoices', opts?)` or `mutation({ id, run })`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function mutation<Ops extends OperationsShape<Ops>, Api extends ClientOf<Ops, boolean>, R extends MutationRoute<Ops>>(api: Api & ClientOf<Ops, boolean>, route: R, opts?: RestMutationOptions<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>): Mutation<InputOf<Ops, R>, DataOf<Ops, R, DecodedOf<Ops, Api>>>;
|
|
42
|
+
export declare function mutation<Vars = void, Data = unknown>(opts: FreeMutationOptions<Vars, Data>): Mutation<Vars, Data>;
|
|
43
|
+
export type { CachePolicy };
|
|
44
|
+
//# sourceMappingURL=query.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EACN,KAAK,WAAW,EAIhB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,KAAK,EACV,KAAK,YAAY,EAEjB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EACN,KAAK,WAAW,EAIhB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,QAAQ,EACR,MAAM,EACN,SAAS,EACT,OAAO,EACP,aAAa,EACb,UAAU,EACV,MAAM,SAAS,CAAC;AAEjB,4DAA4D;AAC5D,MAAM,MAAM,gBAAgB,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,CAC9C,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,EACxB,IAAI,GAAG,OAAO,GAAG,QAAQ,CACzB,GAAG;IACH,iGAAiG;IACjG,EAAE,CAAC,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,mBAAmB,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,CACjD,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,EAC3B,IAAI,GAAG,KAAK,CACZ,G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CAAC,CAAC,CAAC,CAAC;AAC/D,wBAAgB,KAAK,CAAC,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,OAAO,EAChD,IAAI,EAAE,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAChC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAsBrB;;;GAGG;AACH,wBAAgB,QAAQ,CACvB,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC,EAChC,GAAG,SAAS,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,EAClC,CAAC,SAAS,aAAa,CAAC,GAAG,CAAC,EAE5B,GAAG,EAAE,GAAG,GAAG,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,EACjC,KAAK,EAAE,CAAC,EACR,IAAI,CAAC,EAAE,mBAAmB,CACzB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EACf,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CACnC,GACC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAClE,wBAAgB,QAAQ,CAAC,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,OAAO,EACnD,IAAI,EAAE,mBAAmB,CAAC,IAAI,EAAE,IAAI,CAAC,GACnC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAsBxB,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DataOperation, DataSource } from '@softistx/riva';
|
|
2
|
+
import { PREFIX } from '../wire';
|
|
3
|
+
/** What `operations` reads of an OpenAPI client: its operation table. */
|
|
4
|
+
export interface OperationsOf {
|
|
5
|
+
readonly operations: object;
|
|
6
|
+
}
|
|
7
|
+
/** The id the browser names an operation by: `rest:<operationId>`. */
|
|
8
|
+
export { PREFIX };
|
|
9
|
+
/**
|
|
10
|
+
* The server side of `bffTransport`: runs the operations of an OpenAPI client
|
|
11
|
+
* (`createOpenApiClient`) through the request client's REST transport
|
|
12
|
+
* (`provideRest`), under the id `rest:<operationId>`. Only the spec's
|
|
13
|
+
* operations are known; the browser sends an id and its input, never a URL. A
|
|
14
|
+
* GET, HEAD or OPTIONS is a query, any other method a mutation.
|
|
15
|
+
*/
|
|
16
|
+
export declare function operations(api: OperationsOf): DataSource;
|
|
17
|
+
export type { DataOperation, DataSource };
|
|
18
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEhE,OAAO,EAAE,MAAM,EAAQ,MAAM,SAAS,CAAC;AAEvC,yEAAyE;AACzE,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AASD,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,CAAC;AAElB;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,YAAY,GAAG,UAAU,CA+BxD;AAED,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,CAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
transportOf
|
|
3
|
+
} from "../chunks/index-ytrzmcp0.js";
|
|
4
|
+
import {
|
|
5
|
+
SAFE,
|
|
6
|
+
PREFIX2
|
|
7
|
+
} from "../chunks/index-9628zgfc.js";
|
|
8
|
+
|
|
9
|
+
// src/server/index.ts
|
|
10
|
+
function operations(api) {
|
|
11
|
+
const table = api?.operations ?? {};
|
|
12
|
+
const made = new Map;
|
|
13
|
+
return {
|
|
14
|
+
find(id) {
|
|
15
|
+
if (!id.startsWith(PREFIX2))
|
|
16
|
+
return;
|
|
17
|
+
const operationId = id.slice(PREFIX2.length);
|
|
18
|
+
const entry = Object.hasOwn(table, operationId) ? table[operationId] : undefined;
|
|
19
|
+
if (!entry || typeof entry.method !== "string")
|
|
20
|
+
return;
|
|
21
|
+
let op = made.get(id);
|
|
22
|
+
if (!op) {
|
|
23
|
+
const route = {
|
|
24
|
+
method: entry.method,
|
|
25
|
+
path: entry.path,
|
|
26
|
+
operationId,
|
|
27
|
+
hasInput: (entry.parameters?.length ?? 0) > 0 || entry.body !== undefined
|
|
28
|
+
};
|
|
29
|
+
op = {
|
|
30
|
+
kind: SAFE.has(entry.method) ? "query" : "mutation",
|
|
31
|
+
run: async (client, variables, signal) => transportOf(client).call(route, variables, { signal })
|
|
32
|
+
};
|
|
33
|
+
made.set(id, op);
|
|
34
|
+
}
|
|
35
|
+
return op;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export {
|
|
40
|
+
PREFIX2 as PREFIX,
|
|
41
|
+
operations
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
//# debugId=5712A6DFA5F1414D64756E2164756E21
|
|
45
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/server/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { DataOperation, DataSource } from '@softistx/riva';\nimport { type Route, transportOf } from '../transport';\nimport { PREFIX, SAFE } from '../wire';\n\n/** What `operations` reads of an OpenAPI client: its operation table. */\nexport interface OperationsOf {\n\treadonly operations: object;\n}\n\ninterface Entry {\n\tmethod: string;\n\tpath: string;\n\tparameters?: readonly unknown[];\n\tbody?: unknown;\n}\n\n/** The id the browser names an operation by: `rest:<operationId>`. */\nexport { PREFIX };\n\n/**\n * The server side of `bffTransport`: runs the operations of an OpenAPI client\n * (`createOpenApiClient`) through the request client's REST transport\n * (`provideRest`), under the id `rest:<operationId>`. Only the spec's\n * operations are known; the browser sends an id and its input, never a URL. A\n * GET, HEAD or OPTIONS is a query, any other method a mutation.\n */\nexport function operations(api: OperationsOf): DataSource {\n\tconst table = (api?.operations ?? {}) as Record<string, Entry>;\n\tconst made = new Map<string, DataOperation>();\n\treturn {\n\t\tfind(id) {\n\t\t\tif (!id.startsWith(PREFIX)) return undefined;\n\t\t\tconst operationId = id.slice(PREFIX.length);\n\t\t\t// An own key only: `__proto__` or `toString` are not operations.\n\t\t\tconst entry = Object.hasOwn(table, operationId)\n\t\t\t\t? table[operationId]\n\t\t\t\t: undefined;\n\t\t\tif (!entry || typeof entry.method !== 'string') return undefined;\n\t\t\tlet op = made.get(id);\n\t\t\tif (!op) {\n\t\t\t\tconst route: Route = {\n\t\t\t\t\tmethod: entry.method,\n\t\t\t\t\tpath: entry.path,\n\t\t\t\t\toperationId,\n\t\t\t\t\thasInput:\n\t\t\t\t\t\t(entry.parameters?.length ?? 0) > 0 || entry.body !== undefined,\n\t\t\t\t};\n\t\t\t\top = {\n\t\t\t\t\tkind: SAFE.has(entry.method) ? 'query' : 'mutation',\n\t\t\t\t\trun: async (client, variables, signal) =>\n\t\t\t\t\t\ttransportOf(client).call(route, variables, { signal }),\n\t\t\t\t};\n\t\t\t\tmade.set(id, op);\n\t\t\t}\n\t\t\treturn op;\n\t\t},\n\t};\n}\n\nexport type { DataOperation, DataSource };\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;;;;;;;;AA0BO,SAAS,UAAU,CAAC,KAA+B;AAAA,EACzD,MAAM,QAAS,KAAK,cAAc,CAAC;AAAA,EACnC,MAAM,OAAO,IAAI;AAAA,EACjB,OAAO;AAAA,IACN,IAAI,CAAC,IAAI;AAAA,MACR,IAAI,CAAC,GAAG,WAAW,OAAM;AAAA,QAAG;AAAA,MAC5B,MAAM,cAAc,GAAG,MAAM,QAAO,MAAM;AAAA,MAE1C,MAAM,QAAQ,OAAO,OAAO,OAAO,WAAW,IAC3C,MAAM,eACN;AAAA,MACH,IAAI,CAAC,SAAS,OAAO,MAAM,WAAW;AAAA,QAAU;AAAA,MAChD,IAAI,KAAK,KAAK,IAAI,EAAE;AAAA,MACpB,IAAI,CAAC,IAAI;AAAA,QACR,MAAM,QAAe;AAAA,UACpB,QAAQ,MAAM;AAAA,UACd,MAAM,MAAM;AAAA,UACZ;AAAA,UACA,WACE,MAAM,YAAY,UAAU,KAAK,KAAK,MAAM,SAAS;AAAA,QACxD;AAAA,QACA,KAAK;AAAA,UACJ,MAAM,KAAK,IAAI,MAAM,MAAM,IAAI,UAAU;AAAA,UACzC,KAAK,OAAO,QAAQ,WAAW,WAC9B,YAAY,MAAM,EAAE,KAAK,OAAO,WAAW,EAAE,OAAO,CAAC;AAAA,QACvD;AAAA,QACA,KAAK,IAAI,IAAI,EAAE;AAAA,MAChB;AAAA,MACA,OAAO;AAAA;AAAA,EAET;AAAA;",
|
|
8
|
+
"debugId": "5712A6DFA5F1414D64756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { HttpClient } from '@softistx/httpyz';
|
|
2
|
+
import { type FetchContext, type RivaClient } from '@softistx/riva';
|
|
3
|
+
/** Which operation to call, as found in the client's table when the definition was made. */
|
|
4
|
+
export interface Route {
|
|
5
|
+
/** The method, lowercase. */
|
|
6
|
+
readonly method: string;
|
|
7
|
+
/** The path as the spec writes it. */
|
|
8
|
+
readonly path: string;
|
|
9
|
+
/** The operation's `operationId`, the key of the client's table. */
|
|
10
|
+
readonly operationId: string;
|
|
11
|
+
/** Whether the operation takes an input (parameters or a body). */
|
|
12
|
+
readonly hasInput: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs one OpenAPI operation. `@softistx/riva-rest` ships `httpyzTransport`;
|
|
16
|
+
* any object of this shape works (a transport that posts to a BFF route, a
|
|
17
|
+
* test double). It resolves with the data of the 2xx reply and throws
|
|
18
|
+
* `RivaError`s.
|
|
19
|
+
*/
|
|
20
|
+
export interface RestTransport {
|
|
21
|
+
/** The httpyz client, handed to free fetchers; absent on a transport that has none. */
|
|
22
|
+
readonly http?: HttpClient;
|
|
23
|
+
call(route: Route, input: unknown, options: {
|
|
24
|
+
signal: AbortSignal;
|
|
25
|
+
}): Promise<unknown>;
|
|
26
|
+
}
|
|
27
|
+
/** Gives `client` the transport its REST definitions fetch through. */
|
|
28
|
+
export declare function provideRest(client: RivaClient, transport: RestTransport): void;
|
|
29
|
+
/** The transport `provideRest` gave `client`; throws `RivaScopeError` when none. */
|
|
30
|
+
export declare function transportOf(client: RivaClient): RestTransport;
|
|
31
|
+
/** What a free fetcher receives: the core's context, and the client's httpyz instance. */
|
|
32
|
+
export interface RestContext extends FetchContext {
|
|
33
|
+
/** The httpyz client of the transport; reading it with none provided throws `RivaScopeError`. */
|
|
34
|
+
readonly http: HttpClient;
|
|
35
|
+
}
|
|
36
|
+
/** The core's context, with `http` read from the client's transport when the fetcher asks for it. */
|
|
37
|
+
export declare const restContext: (ctx: FetchContext) => RestContext;
|
|
38
|
+
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,UAAU,EAEf,MAAM,gBAAgB,CAAC;AAExB,4FAA4F;AAC5F,MAAM,WAAW,KAAK;IACrB,6BAA6B;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sCAAsC;IACtC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,mEAAmE;IACnE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC7B,uFAAuF;IACvF,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;IAC3B,IAAI,CACH,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QAAE,MAAM,EAAE,WAAW,CAAA;KAAE,GAC9B,OAAO,CAAC,OAAO,CAAC,CAAC;CACpB;AAKD,uEAAuE;AACvE,wBAAgB,WAAW,CAC1B,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,aAAa,GACtB,IAAI,CAEN;AAED,oFAAoF;AACpF,wBAAgB,WAAW,CAAC,MAAM,EAAE,UAAU,GAAG,aAAa,CAO7D;AAED,0FAA0F;AAC1F,MAAM,WAAW,WAAY,SAAQ,YAAY;IAChD,iGAAiG;IACjG,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;CAC1B;AAED,qGAAqG;AACrG,eAAO,MAAM,WAAW,QAAS,YAAY,KAAG,WAW9B,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ClientMembers, OperationReply, OperationsShape, OperationTable, RoutesOf } from '@softistx/openapi-httpyz';
|
|
2
|
+
/** What a route is read against at runtime: the client's operation table (`api.operations`). */
|
|
3
|
+
export interface SpecOf<Ops extends OperationsShape<Ops>> {
|
|
4
|
+
readonly operations: OperationTable<Ops>;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Whether the client decodes its replies (`decode: true`, the default): read
|
|
8
|
+
* off its `op`, since a type parameter cannot be inferred through the
|
|
9
|
+
* conditional that picks the decoded or the JSON reply. A client whose two
|
|
10
|
+
* replies agree is read as decoded, which changes nothing.
|
|
11
|
+
*/
|
|
12
|
+
export type DecodedOf<Ops extends OperationsShape<Ops>, Api extends ClientOf<Ops, boolean>> = [ReturnType<Api['op']>] extends [ReturnType<ClientOf<Ops, true>['op']>] ? true : false;
|
|
13
|
+
/**
|
|
14
|
+
* What the definitions take of an OpenAPI client (`createOpenApiClient(...)`):
|
|
15
|
+
* its operations, and through `op` whether it decodes its replies, which
|
|
16
|
+
* types the data.
|
|
17
|
+
*/
|
|
18
|
+
export type ClientOf<Ops extends OperationsShape<Ops>, Decoded extends boolean = true> = Pick<ClientMembers<Ops, RoutesOf<Ops>, Decoded>, 'operations' | 'op'>;
|
|
19
|
+
/** Every `'method /path/{param}'` the spec has an operation for. */
|
|
20
|
+
export type RouteOf<Ops extends OperationsShape<Ops>> = keyof RoutesOf<Ops> & string;
|
|
21
|
+
/** The routes `query()` accepts: not a `put`, `patch` or `delete`. */
|
|
22
|
+
export type QueryRoute<Ops extends OperationsShape<Ops>> = Exclude<RouteOf<Ops>, `${'put' | 'patch' | 'delete'} ${string}`>;
|
|
23
|
+
/** The routes `mutation()` accepts: not a `get`, `head` or `options`. */
|
|
24
|
+
export type MutationRoute<Ops extends OperationsShape<Ops>> = Exclude<RouteOf<Ops>, `${'get' | 'head' | 'options'} ${string}`>;
|
|
25
|
+
type KeyOf<Ops extends OperationsShape<Ops>, R extends RouteOf<Ops>> = RoutesOf<Ops>[R] & keyof Ops;
|
|
26
|
+
/**
|
|
27
|
+
* The variables of an operation: its input (`param`, `query`, `json`, …) as
|
|
28
|
+
* the spec types it, `void` for an operation that takes none, and optional
|
|
29
|
+
* when the spec requires nothing in it.
|
|
30
|
+
*/
|
|
31
|
+
export type InputOf<Ops extends OperationsShape<Ops>, R extends RouteOf<Ops>> = Ops[KeyOf<Ops, R>]['args'] extends infer A ? A extends readonly [] ? void : A extends readonly [infer I] ? I : A extends readonly [(infer I)?] ? I | undefined : never : never;
|
|
32
|
+
/**
|
|
33
|
+
* The data of the operation's success replies (2xx), as the client returns
|
|
34
|
+
* it: decoded (`decode: true`, the default) or as JSON carries it.
|
|
35
|
+
*/
|
|
36
|
+
export type DataOf<Ops extends OperationsShape<Ops>, R extends RouteOf<Ops>, Decoded extends boolean = true> = Success<OperationReply<Ops, KeyOf<Ops, R>, Decoded>>;
|
|
37
|
+
type Success<Reply> = Reply extends {
|
|
38
|
+
status: infer S extends number;
|
|
39
|
+
data: infer D;
|
|
40
|
+
} ? `${S}` extends `2${string}` ? D : never : never;
|
|
41
|
+
export {};
|
|
42
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,aAAa,EACb,cAAc,EACd,eAAe,EACf,cAAc,EACd,QAAQ,EACR,MAAM,0BAA0B,CAAC;AAElC,gGAAgG;AAChG,MAAM,WAAW,MAAM,CAAC,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC;IACvD,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC;CACzC;AAED;;;;;GAKG;AACH,MAAM,MAAM,SAAS,CACpB,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC,EAChC,GAAG,SAAS,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,IAC/B,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GACxE,IAAI,GACJ,KAAK,CAAC;AAET;;;;GAIG;AACH,MAAM,MAAM,QAAQ,CACnB,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC,EAChC,OAAO,SAAS,OAAO,GAAG,IAAI,IAC3B,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC,CAAC;AAE1E,oEAAoE;AACpE,MAAM,MAAM,OAAO,CAAC,GAAG,SAAS,eAAe,CAAC,GAAG,CAAC,IAAI,MAAM,QAAQ,CAAC,GAAG,CAAC,GAC1E,MAAM,CAAC;AAER,sEAAsE;AACtE,MAA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AAC,CAAC,CAAC;AAEzD,KAAK,OAAO,CAAC,KAAK,IAAI,KAAK,SAAS;IACnC,MAAM,EAAE,MAAM,CAAC,SAAS,MAAM,CAAC;IAC/B,IAAI,EAAE,MAAM,CAAC,CAAC;CACd,GACE,GAAG,CAAC,EAAE,SAAS,IAAI,MAAM,EAAE,GAC1B,CAAC,GACD,KAAK,GACN,KAAK,CAAC"}
|
package/dist/wire.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** HTTP methods that only read: their operations are queries, the others mutations. */
|
|
2
|
+
export declare const SAFE: ReadonlySet<string>;
|
|
3
|
+
/** The id the browser names an operation by: `rest:<operationId>`. */
|
|
4
|
+
export declare const PREFIX = "rest:";
|
|
5
|
+
//# sourceMappingURL=wire.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,eAAO,MAAM,IAAI,EAAE,WAAW,CAAC,MAAM,CAAuC,CAAC;AAE7E,sEAAsE;AACtE,eAAO,MAAM,MAAM,UAAU,CAAC"}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# riva-rest docs
|
|
2
|
+
|
|
3
|
+
The package's [README](../README.md) is the short path. These pages go deeper.
|
|
4
|
+
|
|
5
|
+
## Guides
|
|
6
|
+
|
|
7
|
+
| Page | Read it when |
|
|
8
|
+
|---|---|
|
|
9
|
+
| [Transport](./guide/transport.md) | You wire a client to the API, per request on a server. |
|
|
10
|
+
| [OpenAPI mode](./guide/openapi.md) | You have a spec and want typed `query` and `mutation` from it. |
|
|
11
|
+
| [Free fetcher](./guide/free-fetcher.md) | The API has no schema and you write the function. |
|
|
12
|
+
| [Errors](./guide/errors.md) | You branch on a failure or map httpyz errors. |
|
|
13
|
+
| [BFF mode](./guide/bff.md) | The browser must never reach the API. |
|
|
14
|
+
| [Cache](./guide/cache.md) | Several queries show the same resource and must stay in step. |
|
|
15
|
+
|
|
16
|
+
## Also
|
|
17
|
+
|
|
18
|
+
- [Troubleshooting](./troubleshooting.md): every error message and `RivaError` code this package throws, with the fix.
|
|
19
|
+
- [The core guides](../../riva/docs/README.md).
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# BFF mode
|
|
2
|
+
|
|
3
|
+
Entry points: `@softistx/riva-rest/server` (server) and `@softistx/riva-rest/bff` (browser).
|
|
4
|
+
|
|
5
|
+
## What it is for
|
|
6
|
+
|
|
7
|
+
Run the REST calls on the server and keep the browser away from the API: the browser posts `{ id, variables }` to a `dataRoute` (`@softistx/riva-react-router`'s `/_data`), the server runs the operation through the request client's transport (with its session and base URL) and sends the data back.
|
|
8
|
+
|
|
9
|
+
## Server
|
|
10
|
+
|
|
11
|
+
The middleware gives each request client its transport, and the `/_data` route serves the spec's operations.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// app/api.ts: shared by the definitions and the route
|
|
15
|
+
import { createHttpClient } from '@softistx/httpyz';
|
|
16
|
+
import { createOpenApiClient } from '@softistx/openapi-httpyz';
|
|
17
|
+
import { operations } from './generated/openapi/operations';
|
|
18
|
+
|
|
19
|
+
export const BASE_URL = 'https://api.example.com';
|
|
20
|
+
export const api = createOpenApiClient(createHttpClient({ baseUrl: BASE_URL }), operations);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// app/root.tsx: the request client's transport
|
|
25
|
+
import { createHttpClient } from '@softistx/httpyz';
|
|
26
|
+
import { createOpenApiClient } from '@softistx/openapi-httpyz';
|
|
27
|
+
import { rivaMiddleware } from '@softistx/riva-react-router/server';
|
|
28
|
+
import { httpyzTransport, provideRest } from '@softistx/riva-rest';
|
|
29
|
+
import { BASE_URL } from './api';
|
|
30
|
+
import { operations } from './generated/openapi/operations';
|
|
31
|
+
|
|
32
|
+
export const middleware = [
|
|
33
|
+
rivaMiddleware({
|
|
34
|
+
// the caller port of the request: here its session cookie goes to the API
|
|
35
|
+
setup: (client, { request }) => {
|
|
36
|
+
const http = createHttpClient({
|
|
37
|
+
baseUrl: BASE_URL,
|
|
38
|
+
headers: { cookie: request.headers.get('cookie') ?? '' },
|
|
39
|
+
});
|
|
40
|
+
provideRest(client, httpyzTransport(http, createOpenApiClient(http, operations)));
|
|
41
|
+
},
|
|
42
|
+
}),
|
|
43
|
+
];
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
// app/routes/_data.ts
|
|
48
|
+
import { dataRoute } from '@softistx/riva-react-router/server';
|
|
49
|
+
import { operations } from '@softistx/riva-rest/server';
|
|
50
|
+
import { api } from '../api';
|
|
51
|
+
|
|
52
|
+
const route = dataRoute({ sources: [operations(api)] });
|
|
53
|
+
export const action = route.action;
|
|
54
|
+
export const loader = route.loader; // 405
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Browser
|
|
58
|
+
|
|
59
|
+
The same definitions, another transport, provided in the router provider's `setup`.
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
import { RivaRouterProvider } from '@softistx/riva-react-router';
|
|
63
|
+
import { provideRest } from '@softistx/riva-rest';
|
|
64
|
+
import { bffTransport } from '@softistx/riva-rest/bff';
|
|
65
|
+
import { Outlet } from 'react-router';
|
|
66
|
+
|
|
67
|
+
export default function Root() {
|
|
68
|
+
return (
|
|
69
|
+
<RivaRouterProvider setup={(client) => provideRest(client, bffTransport())}>
|
|
70
|
+
<Outlet />
|
|
71
|
+
</RivaRouterProvider>
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Options
|
|
77
|
+
|
|
78
|
+
`bffTransport(options?)`:
|
|
79
|
+
|
|
80
|
+
| Option | Default | Meaning |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| `url` | `/_data` | The data route. |
|
|
83
|
+
| `fetch` | global `fetch` | A fetch of your own. |
|
|
84
|
+
| `headers` | none | A function returning `HeadersInit`, called at each request (a CSRF token). |
|
|
85
|
+
|
|
86
|
+
Same-origin cookies go with each call. `operations(api)` takes the OpenAPI client; a GET, HEAD or OPTIONS is a query, any other method a mutation.
|
|
87
|
+
|
|
88
|
+
## Traps
|
|
89
|
+
|
|
90
|
+
- **Ids are `rest:<operationId>`**: the spec's `operationId` (`rest:getInvoice`), not the route. An id the spec lacks is a 404 (`RIVA_DATA_UNKNOWN`). The browser never sends a URL or a method.
|
|
91
|
+
- **Free fetchers are server-only**: reading `http` from a free fetcher's context with `bffTransport` throws `RivaScopeError`. Run them in a loader, or describe the call in the spec. `operations()` does not serve them.
|
|
92
|
+
- Errors come back as the core's classes (`postData` of `@softistx/riva/data` maps them): `RivaRequestError` with the route's `code` and `status` (retried for 5xx, 408, 429), `RivaNetworkError`, `RivaAbortError`, `RIVA_INVALID_RESPONSE`.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Cache
|
|
2
|
+
|
|
3
|
+
Entry point: `@softistx/riva-rest/entities`.
|
|
4
|
+
|
|
5
|
+
## What it is for
|
|
6
|
+
|
|
7
|
+
By default an entry is keyed by request: the route and its input. To share resources between queries, opt in to entities: each object you recognise is stored once, and a refetch or a mutation result updates every query that shows it.
|
|
8
|
+
|
|
9
|
+
## Use it
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { query, mutation } from '@softistx/riva-rest';
|
|
13
|
+
import { restEntities } from '@softistx/riva-rest/entities';
|
|
14
|
+
import { api } from './api';
|
|
15
|
+
|
|
16
|
+
// One policy for the client's queries and mutations.
|
|
17
|
+
export const cache = restEntities({
|
|
18
|
+
Invoice: { is: (o) => 'number' in o, key: (o) => o['id'] as string },
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export const invoice = query(api, 'get /invoices/{id}', { cache });
|
|
22
|
+
export const invoices = query(api, 'get /invoices', { cache });
|
|
23
|
+
export const createInvoice = mutation(api, 'post /invoices', { cache });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Options
|
|
27
|
+
|
|
28
|
+
`restEntities(types, options?)`:
|
|
29
|
+
|
|
30
|
+
| Argument | Default | Meaning |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| `types` | required | `{ Type: { is(obj), key(obj) } }`: `is` says whether an object of a response is that type (REST has no `__typename`), `key` gives its id. |
|
|
33
|
+
| `options.identify` | the types' rule | The core's `identify`, to replace the identity rule altogether. |
|
|
34
|
+
|
|
35
|
+
Recognised objects get a `__typename`; the core's `readEntity('Invoice:7')`, `writeEntity` and `invalidateEntity` work on them.
|
|
36
|
+
|
|
37
|
+
## Traps
|
|
38
|
+
|
|
39
|
+
- **Share the `restEntities()` result itself**, not its arguments: two calls throw `RIVA_CACHE` on one client, even with the same `types`.
|
|
40
|
+
- **`is` must tell the types apart**: the first type that matches wins, so `'id' in o` for two resources tags both as the first one.
|
|
41
|
+
- **The injected `__typename` shows up in the data.** Send it back to the API (an edit form's value as a request body) and request validation fails on the unknown field: drop it first.
|
|
42
|
+
- **REST and GraphQL policies cannot share one client's store** in v1: a client holds one set of identity rules.
|
|
43
|
+
|
|
44
|
+
Fixes: [troubleshooting](../troubleshooting.md).
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Errors
|
|
2
|
+
|
|
3
|
+
## What it is for
|
|
4
|
+
|
|
5
|
+
The transport and the free fetcher throw riva's errors, defined once in the core so `instanceof` holds, and the core's retry policy applies.
|
|
6
|
+
|
|
7
|
+
| httpyz | riva | `code` | retried |
|
|
8
|
+
|---|---|---|---|
|
|
9
|
+
| a status the spec declares, not 2xx | `RivaHttpError` (the reply is its `cause`) | `HTTP_404` | 5xx, 408, 429 |
|
|
10
|
+
| `UndeclaredStatusError`, `ReplyStatusError` | `RivaHttpError` | `HTTP_<status>` | 5xx, 408, 429 |
|
|
11
|
+
| `NetworkError`, `TimeoutError` | `RivaNetworkError` | `RIVA_NETWORK` | yes |
|
|
12
|
+
| `ValidationError` on the request | `RivaRequestError` | `RIVA_VALIDATION` | no |
|
|
13
|
+
| `ValidationError` on the reply | `RivaRequestError` | `RIVA_INVALID_RESPONSE` | no |
|
|
14
|
+
| the caller's abort | `RivaAbortError` | `RIVA_ABORT` | no |
|
|
15
|
+
| a transport with no OpenAPI client, or one that lacks the operation | `RivaRequestError` | `RIVA_REST_UNWIRED` | no |
|
|
16
|
+
|
|
17
|
+
## Branch on it
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { RivaHttpError } from '@softistx/riva';
|
|
21
|
+
|
|
22
|
+
const state = client.get(invoice, { param: { id: '7' } });
|
|
23
|
+
if (state.error instanceof RivaHttpError && state.error.status === 404) {
|
|
24
|
+
// not found
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Traps
|
|
29
|
+
|
|
30
|
+
- Only httpyz's own errors are mapped (they carry the `method` and `path` of their call): a `ValidationError` or a `TimeoutError` from another library passes through unchanged.
|
|
31
|
+
- `toRivaError(error, signal?)` is exported for your own transports; pass the signal so an abort becomes a `RivaAbortError`.
|
|
32
|
+
|
|
33
|
+
Fixes: [troubleshooting](../troubleshooting.md).
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Free fetcher
|
|
2
|
+
|
|
3
|
+
## What it is for
|
|
4
|
+
|
|
5
|
+
For an API with no schema, write the function: its types are the definition's types.
|
|
6
|
+
|
|
7
|
+
## Define and run
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { mutation, query } from '@softistx/riva-rest';
|
|
11
|
+
|
|
12
|
+
type Todo = { id: string; title: string; done: boolean };
|
|
13
|
+
|
|
14
|
+
export const todos = query({
|
|
15
|
+
id: 'todos',
|
|
16
|
+
fetch: async (vars: { done?: boolean }, { http, signal }) => {
|
|
17
|
+
const reply = await http.get('/todos', { query: vars, signal });
|
|
18
|
+
return reply.data as Todo[];
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const renameTodo = mutation({
|
|
23
|
+
id: 'renameTodo',
|
|
24
|
+
run: async (vars: { id: string; title: string }, { http, signal }) =>
|
|
25
|
+
(await http.patch('/todos/{id}', { param: { id: vars.id }, json: { title: vars.title }, signal })).data as Todo,
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Options
|
|
30
|
+
|
|
31
|
+
`FreeQueryOptions` and `FreeMutationOptions` are the core's query and mutation options, with the fetcher:
|
|
32
|
+
|
|
33
|
+
| Option | Default | Meaning |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| `id` | required | A function has no name to derive a key from. |
|
|
36
|
+
| `fetch(vars, ctx)` (query) | required | Returns the data. |
|
|
37
|
+
| `run(vars, ctx)` (mutation) | required | Sends the change, returns the data. |
|
|
38
|
+
| the others | core defaults | `staleTime`, `gcTime`, `retry`, `cache`, `optimistic`, `invalidates`… |
|
|
39
|
+
|
|
40
|
+
The context is the core's (`signal`, `client`) plus `http`, the httpyz client of the transport.
|
|
41
|
+
|
|
42
|
+
## Traps
|
|
43
|
+
|
|
44
|
+
- `http` is read lazily: a fetcher that never touches it (a plain `fetch`) needs no transport.
|
|
45
|
+
- Without `id`, the definition throws `riva-rest: query() needs an id`.
|
|
46
|
+
- What the fetcher throws from httpyz is mapped to riva's errors ([errors](./errors.md)).
|
|
47
|
+
- Free fetchers are server-only under [BFF mode](./bff.md): `http` does not exist in the browser.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# OpenAPI mode
|
|
2
|
+
|
|
3
|
+
## What it is for
|
|
4
|
+
|
|
5
|
+
`query(api, 'method path', options?)` and `mutation(api, 'method path', options?)` build definitions typed from the spec. The route is the one the spec writes (`'get /invoices/{id}'`), checked at compile time and when the definition is created. The variables are the operation's input (`param`, `query`, `json`, …), the data is its 2xx reply, both from the spec.
|
|
6
|
+
|
|
7
|
+
## Define and run
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { mutation, query } from '@softistx/riva-rest';
|
|
11
|
+
import { api } from './api';
|
|
12
|
+
|
|
13
|
+
export const invoice = query(api, 'get /invoices/{id}', { staleTime: '30s' });
|
|
14
|
+
export const invoices = query(api, 'get /invoices');
|
|
15
|
+
export const createInvoice = mutation(api, 'post /invoices', { invalidates: [invoices] });
|
|
16
|
+
|
|
17
|
+
await invoice.ensure(client, { param: { id: '7' } }); // Invoice
|
|
18
|
+
await createInvoice.run(client, { json: { number: 'F-8', total: 120 } });
|
|
19
|
+
client.get(invoices); // an operation whose input is all optional takes no variables
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Options
|
|
23
|
+
|
|
24
|
+
| Option | Default | Meaning |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `id` | the route (`get /invoices/{id}`) | Override to define one route twice with different options. |
|
|
27
|
+
| `staleTime`, `gcTime` | core defaults | Freshness and retention. |
|
|
28
|
+
| `retry` | 3 in a browser, 0 on the server | A count, or `(failures, error) => boolean`. |
|
|
29
|
+
| `retryDelay` | `min(1000 * 2 ** failures, 30000)` | `(failures) => ms`. |
|
|
30
|
+
| `refetchOnFocus`, `refetchOnReconnect`, `refetchEvery` | core defaults | Query refetch triggers. |
|
|
31
|
+
| `cache` | none | A core policy, such as `restEntities()` ([cache](./cache.md)). |
|
|
32
|
+
| `optimistic`, `updates`, `invalidates` | none | Mutation options, as the [core](../../../riva/docs/guide/mutations.md). |
|
|
33
|
+
|
|
34
|
+
## Cancel
|
|
35
|
+
|
|
36
|
+
`ensure(client, vars, { signal })`: the signal reaches the request, and an abort is a `RivaAbortError`.
|
|
37
|
+
|
|
38
|
+
`rest.query` and `rest.mutation` are the same functions, for the `rest.query(api, 'get /invoices/{id}')` spelling.
|
|
39
|
+
|
|
40
|
+
## Traps
|
|
41
|
+
|
|
42
|
+
- **The id is the route**; the cache key is the id plus the stable-serialized input, never hand-written.
|
|
43
|
+
- **The data is typed as the client returns it**: decoded for `decode: true` (the default), as JSON carries it for `decode: false`.
|
|
44
|
+
- **Routes are narrowed by kind**: `query()` takes every route but `put`, `patch` and `delete` (`QueryRoute`); `mutation()` every one but `get`, `head` and `options` (`MutationRoute`). The wrong one is a compile error and a `RivaError` (`RIVA_DEFINITION`) at definition time. A `POST` that only reads (a search) is a query.
|
|
45
|
+
- A route the spec lacks, or written wrongly, throws when the definition is created ([troubleshooting](../troubleshooting.md)).
|