@orpc/nest 2.0.0-beta.46 → 2.0.0-beta.48
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 +6 -4
- package/dist/constants.d.mts +1 -0
- package/dist/constants.mjs +1 -0
- package/dist/implement.d.mts +29 -0
- package/dist/implement.mjs +287 -0
- package/dist/index.d.mts +7 -84
- package/dist/index.mjs +5 -329
- package/dist/module.d.mts +47 -0
- package/dist/module.mjs +33 -0
- package/package.json +20 -14
- package/dist/index.d.ts +0 -85
package/README.md
CHANGED
|
@@ -156,10 +156,11 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
|
|
|
156
156
|
<td align="center"><a href="https://github.com/christ12938?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="christ12938"><img src="https://avatars.githubusercontent.com/u/25758598?v=4" width="167" alt="christ12938"/><br />christ12938</a></td>
|
|
157
157
|
<td align="center"><a href="https://github.com/Ryanjso?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Ryan Soderberg"><img src="https://avatars.githubusercontent.com/u/39172778?u=5ed913c31d57e7221b75784abcad48c7ebddde27&v=4" width="167" alt="Ryan Soderberg"/><br />Ryan Soderberg</a></td>
|
|
158
158
|
<td align="center"><a href="https://github.com/itigoore01?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="shota"><img src="https://avatars.githubusercontent.com/u/11831107?u=c976a6dc7e055eb026304c46c99100ed22b0c8e0&v=4" width="167" alt="shota"/><br />shota</a></td>
|
|
159
|
+
<td align="center"><a href="https://github.com/Nic13Gamer?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Nicholas"><img src="https://avatars.githubusercontent.com/u/54724556?u=56a7ab430ce7a80d648ab6eba051d454a818ed0b&v=4" width="167" alt="Nicholas"/><br />Nicholas</a></td>
|
|
159
160
|
<td align="center"><a href="https://github.com/ellis-driscoll?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Ellis Driscoll"><img src="https://avatars.githubusercontent.com/u/70685966?u=c5f95bc33b5991d9744abe00052542e4a2ed3cb9&v=4" width="167" alt="Ellis Driscoll"/><br />Ellis Driscoll</a></td>
|
|
160
|
-
<td align="center"><a href="https://github.com/hoangbn?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Hoang Nguyen"><img src="https://avatars.githubusercontent.com/u/38968280?u=c90084c6de65c56facabab7ba13a72a49ddbc3e4&v=4" width="167" alt="Hoang Nguyen"/><br />Hoang Nguyen</a></td>
|
|
161
161
|
</tr>
|
|
162
162
|
<tr>
|
|
163
|
+
<td align="center"><a href="https://github.com/hoangbn?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Hoang Nguyen"><img src="https://avatars.githubusercontent.com/u/38968280?u=c90084c6de65c56facabab7ba13a72a49ddbc3e4&v=4" width="167" alt="Hoang Nguyen"/><br />Hoang Nguyen</a></td>
|
|
163
164
|
<td align="center"><a href="https://opencollective.com/guest-ac41de3b?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Orestis Ioannou"><img src="https://images.opencollective.com/guest-ac41de3b/avatar/460.png" width="167" alt="Orestis Ioannou"/><br />Orestis Ioannou</a></td>
|
|
164
165
|
<td align="center"><a href="https://automatio.ai/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Stefan Smiljkovic"><img src="https://avatars.githubusercontent.com/u/1984909?u=b7bf5bc40ed49df3c22f69d2da7b8d78709c49ed&v=4" width="167" alt="Stefan Smiljkovic"/><br />Stefan Smiljkovic</a></td>
|
|
165
166
|
</tr>
|
|
@@ -190,10 +191,9 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
|
|
|
190
191
|
<td align="center"><a href="https://kellychan.im/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
|
|
191
192
|
<td align="center"><a href="https://guyariely.com/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
|
|
192
193
|
<td align="center"><a href="https://paulsenon.com/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
|
|
193
|
-
<td align="center"><a href="https://
|
|
194
|
+
<td align="center"><a href="https://piscis.dev/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&v=4" width="139" alt="Alex"/><br />Alex</a></td>
|
|
194
195
|
</tr>
|
|
195
196
|
<tr>
|
|
196
|
-
<td align="center"><a href="https://piscis.dev/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&v=4" width="139" alt="Alex"/><br />Alex</a></td>
|
|
197
197
|
<td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
|
|
198
198
|
</tr>
|
|
199
199
|
</table>
|
|
@@ -206,7 +206,9 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
|
|
|
206
206
|
|
|
207
207
|
<table>
|
|
208
208
|
<tr>
|
|
209
|
-
<td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude
|
|
209
|
+
<td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
|
|
210
|
+
<td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
|
|
211
|
+
<td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
|
|
210
212
|
</tr>
|
|
211
213
|
</table>
|
|
212
214
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const ORPC_MODULE_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_NEST_MODULE_CONFIG");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
|
|
2
|
+
import type { RouterContract } from "@orpc/contract";
|
|
3
|
+
import type { ContractedRouter, DefaultInitialContext } from "@orpc/server";
|
|
4
|
+
import type { Promisable } from "@orpc/shared";
|
|
5
|
+
import type { Observable } from "rxjs";
|
|
6
|
+
import type { ORPCModuleConfig } from "./module.mjs";
|
|
7
|
+
import { HttpAdapterHost } from "@nestjs/core";
|
|
8
|
+
/**
|
|
9
|
+
* Decorator that implements an oRPC contract (procedure or router contract)
|
|
10
|
+
* on a NestJS controller method. It registers the corresponding NestJS routes
|
|
11
|
+
* and handles request decoding and response encoding for you.
|
|
12
|
+
*
|
|
13
|
+
* @remarks
|
|
14
|
+
* **Note**: Every procedure contract must define an `openapi.path` meta;
|
|
15
|
+
* use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
|
|
16
|
+
* **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
|
|
17
|
+
*
|
|
18
|
+
* @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
|
|
19
|
+
*/
|
|
20
|
+
export declare function Implement<T extends RouterContract>(contract: T): <U extends Promisable<ContractedRouter<T, DefaultInitialContext>>>(target: Record<PropertyKey, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => U>) => void;
|
|
21
|
+
export declare class ImplementInterceptor implements NestInterceptor {
|
|
22
|
+
private readonly config;
|
|
23
|
+
private readonly codec;
|
|
24
|
+
private readonly handler;
|
|
25
|
+
private readonly toNestStandardLazyRequest;
|
|
26
|
+
private readonly httpAdapterHost;
|
|
27
|
+
constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
|
|
28
|
+
intercept(ctx: ExecutionContext, next: CallHandler<any>): Observable<any>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { Readable } from "node:stream";
|
|
2
|
+
import * as NestCommon from "@nestjs/common";
|
|
3
|
+
import { applyDecorators, Delete, Get, Head, HttpCode, HttpException, Inject, Injectable, Optional, Options, Patch, Post, Put, StreamableFile, UseInterceptors } from "@nestjs/common";
|
|
4
|
+
import { HttpAdapterHost } from "@nestjs/core";
|
|
5
|
+
import { getPathMeta, ProcedureContract } from "@orpc/contract";
|
|
6
|
+
import { DEFAULT_OPENAPI_METHOD, getDynamicPathParams, getOpenAPIMeta } from "@orpc/openapi";
|
|
7
|
+
import { OpenAPIHandlerCodecCore } from "@orpc/openapi/standard";
|
|
8
|
+
import { DEFAULT_SUCCESS_STATUS, getRouter, Procedure, unlazy } from "@orpc/server";
|
|
9
|
+
import { StandardHandler } from "@orpc/server/standard";
|
|
10
|
+
import { isAsyncIteratorObject, mergeHttpPath, NullProtoObj, stringifyJSON, toArray, value } from "@orpc/shared";
|
|
11
|
+
import { flattenStandardHeader, generateContentDisposition, getRequiredStandardBodyHint } from "@standard-server/core";
|
|
12
|
+
import { toEventStream, toStandardLazyRequest } from "@standard-server/node";
|
|
13
|
+
import { mergeMap } from "rxjs";
|
|
14
|
+
import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.mjs";
|
|
15
|
+
import _decorateParam from "@oxc-project/runtime/helpers/decorateParam";
|
|
16
|
+
import _decorate from "@oxc-project/runtime/helpers/decorate";
|
|
17
|
+
|
|
18
|
+
const QueryMethod = NestCommon.QueryMethod;
|
|
19
|
+
const MethodDecoratorMap = {
|
|
20
|
+
HEAD: Head,
|
|
21
|
+
GET: Get,
|
|
22
|
+
POST: Post,
|
|
23
|
+
PUT: Put,
|
|
24
|
+
PATCH: Patch,
|
|
25
|
+
DELETE: Delete,
|
|
26
|
+
OPTIONS: Options
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export function Implement(contract) {
|
|
30
|
+
if (contract instanceof ProcedureContract) {
|
|
31
|
+
return (target, propertyKey, descriptor) => {
|
|
32
|
+
applyDecorators(toNestRouteDecorator(contract), UseInterceptors(ImplementInterceptor))(target, propertyKey, descriptor);
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
return (target, propertyKey, descriptor) => {
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
|
|
39
|
+
implementRouterContract(contract, target, propertyKey, descriptor);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function toNestRouteDecorator(contract) {
|
|
43
|
+
const meta = getOpenAPIMeta(contract);
|
|
44
|
+
if (meta?.path === undefined) {
|
|
45
|
+
throw new TypeError(`
|
|
46
|
+
@Implement decorator requires contract to have a 'openapi.path' meta.
|
|
47
|
+
Please define one using '.meta(openapi({ path: '/example' }))'.
|
|
48
|
+
Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
|
|
49
|
+
`);
|
|
50
|
+
}
|
|
51
|
+
const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
|
|
52
|
+
const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
|
|
53
|
+
const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
54
|
+
if (method === "QUERY") {
|
|
55
|
+
if (!QueryMethod) {
|
|
56
|
+
throw new TypeError(`
|
|
57
|
+
@Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
|
|
58
|
+
The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
|
|
59
|
+
`);
|
|
60
|
+
}
|
|
61
|
+
return applyDecorators(QueryMethod(path), HttpCode(successStatus));
|
|
62
|
+
}
|
|
63
|
+
return applyDecorators(MethodDecoratorMap[method](path), HttpCode(successStatus));
|
|
64
|
+
}
|
|
65
|
+
function implementRouterContract(contract, target, propertyKey, descriptor) {
|
|
66
|
+
for (const [key, childContract] of Object.entries(contract)) {
|
|
67
|
+
let methodName = `${propertyKey}_${key}`;
|
|
68
|
+
let i = 0;
|
|
69
|
+
while (methodName in target) {
|
|
70
|
+
methodName = `${propertyKey}_${key}_${i++}`;
|
|
71
|
+
}
|
|
72
|
+
target[methodName] = async function(...args) {
|
|
73
|
+
const router = await descriptor.value.apply(this, args);
|
|
74
|
+
return getRouter(router, [key]);
|
|
75
|
+
};
|
|
76
|
+
Object.setPrototypeOf(target[methodName], descriptor.value);
|
|
77
|
+
queueMicrotask(() => {
|
|
78
|
+
for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
|
|
79
|
+
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
|
|
80
|
+
}
|
|
81
|
+
for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
|
|
82
|
+
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
|
|
86
|
+
if (childContract instanceof ProcedureContract) {
|
|
87
|
+
const routeDecorator = toNestRouteDecorator(childContract);
|
|
88
|
+
|
|
89
|
+
queueMicrotask(() => {
|
|
90
|
+
routeDecorator(target, methodName, childDescriptor);
|
|
91
|
+
});
|
|
92
|
+
} else {
|
|
93
|
+
implementRouterContract(childContract, target, methodName, childDescriptor);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let ImplementInterceptor = class ImplementInterceptor {
|
|
98
|
+
config;
|
|
99
|
+
codec;
|
|
100
|
+
handler;
|
|
101
|
+
toNestStandardLazyRequest;
|
|
102
|
+
httpAdapterHost;
|
|
103
|
+
constructor(config, httpAdapterHost) {
|
|
104
|
+
// @Optional() does not allow set default value so we need to do it here
|
|
105
|
+
this.config = config ?? {};
|
|
106
|
+
this.httpAdapterHost = httpAdapterHost;
|
|
107
|
+
this.codec = new NestHandlerCodec(this.config);
|
|
108
|
+
this.handler = new StandardHandler(this.codec, this.config);
|
|
109
|
+
this.toNestStandardLazyRequest = this.config.toNestStandardLazyRequest ?? ((req, res) => {
|
|
110
|
+
const standardRequest = toStandardLazyRequest("raw" in req ? req.raw : req, "raw" in res ? res.raw : res);
|
|
111
|
+
|
|
112
|
+
if (req.body !== undefined) {
|
|
113
|
+
standardRequest.resolveBody = () => Promise.resolve(req.body);
|
|
114
|
+
}
|
|
115
|
+
standardRequest.params = req.params;
|
|
116
|
+
return standardRequest;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
intercept(ctx, next) {
|
|
120
|
+
return next.handle().pipe(mergeMap(async (impl) => {
|
|
121
|
+
const { default: procedure } = await unlazy(impl);
|
|
122
|
+
if (!(procedure instanceof Procedure)) {
|
|
123
|
+
throw new TypeError(`
|
|
124
|
+
The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
|
|
125
|
+
`);
|
|
126
|
+
}
|
|
127
|
+
const req = ctx.switchToHttp().getRequest();
|
|
128
|
+
const res = ctx.switchToHttp().getResponse();
|
|
129
|
+
const standardRequest = this.toNestStandardLazyRequest(req, res);
|
|
130
|
+
const context = await value(this.config.context ?? {}, ctx);
|
|
131
|
+
const result = await this.handler.handle(standardRequest, { context: this.codec.withMatch(context, {
|
|
132
|
+
procedure,
|
|
133
|
+
params: standardRequest.params
|
|
134
|
+
}) });
|
|
135
|
+
if (!result.matched) {
|
|
136
|
+
throw new TypeError("oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug.");
|
|
137
|
+
}
|
|
138
|
+
const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
|
|
139
|
+
const httpAdapter = this.httpAdapterHost.httpAdapter;
|
|
140
|
+
httpAdapter.status(res, result.response.status);
|
|
141
|
+
for (const key of Object.keys(headers)) {
|
|
142
|
+
toArray(headers[key]).forEach((value, index) => {
|
|
143
|
+
if (index === 0) {
|
|
144
|
+
httpAdapter.setHeader(res, key, value);
|
|
145
|
+
} else {
|
|
146
|
+
httpAdapter.appendHeader(res, key, value);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (nestBody instanceof HttpException) {
|
|
151
|
+
throw nestBody;
|
|
152
|
+
}
|
|
153
|
+
return nestBody;
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
ImplementInterceptor = _decorate([
|
|
158
|
+
Injectable(),
|
|
159
|
+
_decorateParam(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
|
|
160
|
+
_decorateParam(0, Optional()),
|
|
161
|
+
_decorateParam(1, Inject(HttpAdapterHost))
|
|
162
|
+
], ImplementInterceptor);
|
|
163
|
+
export { ImplementInterceptor };
|
|
164
|
+
|
|
165
|
+
function toNestHttpBody(response, signal, options) {
|
|
166
|
+
const { status, body } = response;
|
|
167
|
+
const headers = { ...response.headers };
|
|
168
|
+
if (body instanceof ReadableStream) {
|
|
169
|
+
headers["standard-server"] ??= "octet-stream";
|
|
170
|
+
headers["content-type"] ??= "application/octet-stream";
|
|
171
|
+
return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
|
|
172
|
+
}
|
|
173
|
+
if (body instanceof Blob) {
|
|
174
|
+
headers["standard-server"] ??= "file";
|
|
175
|
+
headers["content-type"] ??= body.type;
|
|
176
|
+
headers["content-disposition"] ??= generateContentDisposition(body instanceof File ? body.name : "blob");
|
|
177
|
+
|
|
178
|
+
if (Number.isFinite(body.size)) {
|
|
179
|
+
headers["content-length"] = body.size.toString();
|
|
180
|
+
}
|
|
181
|
+
return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
|
|
182
|
+
}
|
|
183
|
+
headers["standard-server"] = undefined;
|
|
184
|
+
headers["content-length"] = undefined;
|
|
185
|
+
if (body === undefined) {
|
|
186
|
+
headers["content-type"] = undefined;
|
|
187
|
+
return [undefined, headers];
|
|
188
|
+
}
|
|
189
|
+
if (body instanceof FormData) {
|
|
190
|
+
const response = new Response(body);
|
|
191
|
+
headers["content-type"] = response.headers.get("content-type");
|
|
192
|
+
return [toStreamableFile(Readable.fromWeb(response.body), headers, signal), headers];
|
|
193
|
+
}
|
|
194
|
+
if (body instanceof URLSearchParams) {
|
|
195
|
+
headers["content-type"] ??= "application/x-www-form-urlencoded";
|
|
196
|
+
headers["standard-server"] = getRequiredStandardBodyHint("url-search-params", headers);
|
|
197
|
+
return [body.toString(), headers];
|
|
198
|
+
}
|
|
199
|
+
if (isAsyncIteratorObject(body)) {
|
|
200
|
+
headers["content-type"] ??= "text/event-stream";
|
|
201
|
+
headers["standard-server"] = getRequiredStandardBodyHint("event-stream", headers);
|
|
202
|
+
return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (status >= 300 && typeof body === "object" && body !== null && !Array.isArray(body)) {
|
|
206
|
+
if (headers["content-type"] !== undefined) {
|
|
207
|
+
headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
|
|
208
|
+
}
|
|
209
|
+
return [new HttpException(body, status), headers];
|
|
210
|
+
}
|
|
211
|
+
headers["content-type"] ??= "application/json";
|
|
212
|
+
headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
|
|
213
|
+
return [typeof body === "string" || body === null || headers["standard-server"] !== undefined ? stringifyJSON(body) : body, headers];
|
|
214
|
+
}
|
|
215
|
+
class NestHandlerCodec extends OpenAPIHandlerCodecCore {
|
|
216
|
+
CONTEXT_SYMBOL = Symbol("ORPC_NEST_HANDLER_CODEC_CONTEXT");
|
|
217
|
+
withMatch(context, match) {
|
|
218
|
+
return {
|
|
219
|
+
...context,
|
|
220
|
+
[this.CONTEXT_SYMBOL]: match
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
resolveProcedure(request, options) {
|
|
224
|
+
const match = options.context[this.CONTEXT_SYMBOL];
|
|
225
|
+
if (!match) {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
const { procedure, params } = match;
|
|
229
|
+
return {
|
|
230
|
+
path: getPathMeta(procedure) ?? [],
|
|
231
|
+
procedure,
|
|
232
|
+
decodeInput: () => this.decodeInput({
|
|
233
|
+
procedure,
|
|
234
|
+
params: toORPCOpenAPIParams(procedure, params)
|
|
235
|
+
}, request)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function toStreamableFile(stream, headers, signal) {
|
|
241
|
+
const type = flattenStandardHeader(headers["content-type"]);
|
|
242
|
+
headers["content-type"] = undefined;
|
|
243
|
+
if (signal?.aborted) {
|
|
244
|
+
stream.destroy();
|
|
245
|
+
} else {
|
|
246
|
+
signal?.addEventListener("abort", () => stream.destroy(), { once: true });
|
|
247
|
+
}
|
|
248
|
+
return new StreamableFile(stream, { type });
|
|
249
|
+
}
|
|
250
|
+
function flattenParamValue(value) {
|
|
251
|
+
return Array.isArray(value) ? value.join("/") : value;
|
|
252
|
+
}
|
|
253
|
+
function toORPCOpenAPIParams(contract, params) {
|
|
254
|
+
const meta = getOpenAPIMeta(contract);
|
|
255
|
+
if (!params || meta?.path === undefined || Object.keys(params).length === 0) {
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const orpcParams = new NullProtoObj();
|
|
260
|
+
|
|
261
|
+
const restKey = Object.hasOwn(params, "*") ? "*" : "path";
|
|
262
|
+
for (const [key, value] of Object.entries(params)) {
|
|
263
|
+
if (key === restKey) {
|
|
264
|
+
const restParams = getDynamicPathParams(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path)?.filter((c) => c.allowsSlash);
|
|
265
|
+
if (restParams?.length) {
|
|
266
|
+
for (const c of restParams) {
|
|
267
|
+
orpcParams[c.parameterName] = flattenParamValue(value);
|
|
268
|
+
}
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
orpcParams[key] = flattenParamValue(value);
|
|
273
|
+
}
|
|
274
|
+
return orpcParams;
|
|
275
|
+
}
|
|
276
|
+
function toNestPattern(path) {
|
|
277
|
+
const params = getDynamicPathParams(path);
|
|
278
|
+
if (!params?.length) {
|
|
279
|
+
return path;
|
|
280
|
+
}
|
|
281
|
+
for (let i = params.length - 1; i >= 0; i--) {
|
|
282
|
+
const param = params[i];
|
|
283
|
+
const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
|
|
284
|
+
path = path.slice(0, param.startIndex) + pattern + path.slice(param.startIndex + param.segment.length);
|
|
285
|
+
}
|
|
286
|
+
return path;
|
|
287
|
+
}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,85 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { Value, Promisable } from '@orpc/shared';
|
|
5
|
-
import { Observable } from 'rxjs';
|
|
6
|
-
import { OpenAPIHandlerCodecCoreOptions } from '@orpc/openapi/standard';
|
|
7
|
-
import { StandardHandlerOptions } from '@orpc/server/standard';
|
|
8
|
-
import { StandardLazyRequest } from '@standard-server/core';
|
|
9
|
-
import { ToEventStreamOptions } from '@standard-server/node';
|
|
10
|
-
import { HttpAdapterHost } from '@nestjs/core';
|
|
11
|
-
|
|
12
|
-
declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
|
|
1
|
+
export * from "./constants.mjs";
|
|
2
|
+
export * from "./implement.mjs";
|
|
3
|
+
export {
|
|
13
4
|
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
*
|
|
18
|
-
*/
|
|
19
|
-
interface NestStandardLazyRequest extends StandardLazyRequest {
|
|
20
|
-
/**
|
|
21
|
-
* Route parameters extracted from the request path.
|
|
22
|
-
*/
|
|
23
|
-
params?: Record<string, string | string[]> | undefined;
|
|
24
|
-
}
|
|
25
|
-
type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
|
|
26
|
-
context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
|
|
27
|
-
} : {
|
|
28
|
-
context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
|
|
29
|
-
}) & {
|
|
30
|
-
/**
|
|
31
|
-
* Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
|
|
32
|
-
* You might need to define this if you are not using express or fastify adapters.
|
|
33
|
-
*/
|
|
34
|
-
toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
|
|
35
|
-
/**
|
|
36
|
-
* Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
|
|
37
|
-
*/
|
|
38
|
-
toNestResponse?: {
|
|
39
|
-
/**
|
|
40
|
-
* Options for the event stream, like keep-alive settings, initial comment, etc.
|
|
41
|
-
*/
|
|
42
|
-
eventStream?: ToEventStreamOptions | undefined;
|
|
43
|
-
} | undefined;
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* NestJS module that configures the `@orpc/nest` integration via `forRoot`
|
|
47
|
-
* or `forRootAsync`, providing options such as initial context, plugins,
|
|
48
|
-
* and interceptors to `@Implement` handlers.
|
|
49
|
-
*
|
|
50
|
-
* @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
|
|
51
|
-
*/
|
|
52
|
-
declare class ORPCModule {
|
|
53
|
-
static forRoot(config: ORPCModuleConfig): DynamicModule;
|
|
54
|
-
static forRootAsync(options: {
|
|
55
|
-
imports?: any[] | undefined;
|
|
56
|
-
useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
|
|
57
|
-
inject?: any[] | undefined;
|
|
58
|
-
}): DynamicModule;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Decorator that implements an oRPC contract (procedure or router contract)
|
|
63
|
-
* on a NestJS controller method. It registers the corresponding NestJS routes
|
|
64
|
-
* and handles request decoding and response encoding for you.
|
|
65
|
-
*
|
|
66
|
-
* @remarks
|
|
67
|
-
* **Note**: Every procedure contract must define an `openapi.path` meta;
|
|
68
|
-
* use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
|
|
69
|
-
* **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
|
|
70
|
-
*
|
|
71
|
-
* @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
|
|
72
|
-
*/
|
|
73
|
-
declare function Implement<T extends RouterContract>(contract: T): <U extends Promisable<ContractedRouter<T, DefaultInitialContext>>>(target: Record<PropertyKey, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => U>) => void;
|
|
74
|
-
declare class ImplementInterceptor implements NestInterceptor {
|
|
75
|
-
private readonly config;
|
|
76
|
-
private readonly codec;
|
|
77
|
-
private readonly handler;
|
|
78
|
-
private readonly toNestStandardLazyRequest;
|
|
79
|
-
private readonly httpAdapterHost;
|
|
80
|
-
constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
|
|
81
|
-
intercept(ctx: ExecutionContext, next: CallHandler<any>): Observable<any>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
|
|
85
|
-
export type { NestStandardLazyRequest, ORPCModuleConfig };
|
|
5
|
+
* @alias Implement
|
|
6
|
+
*/
|
|
7
|
+
Implement as Impl } from "./implement.mjs";
|
|
8
|
+
export * from "./module.mjs";
|
package/dist/index.mjs
CHANGED
|
@@ -1,330 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { HttpAdapterHost } from '@nestjs/core';
|
|
5
|
-
import { ProcedureContract, getPathMeta } from '@orpc/contract';
|
|
6
|
-
import { getOpenAPIMeta, DEFAULT_OPENAPI_METHOD, getDynamicPathParams } from '@orpc/openapi';
|
|
7
|
-
import { OpenAPIHandlerCodecCore } from '@orpc/openapi/standard';
|
|
8
|
-
import { unlazy, Procedure, DEFAULT_SUCCESS_STATUS, getRouter } from '@orpc/server';
|
|
9
|
-
import { StandardHandler } from '@orpc/server/standard';
|
|
10
|
-
import { value, isAsyncIteratorObject, stringifyJSON, mergeHttpPath, NullProtoObj } from '@orpc/shared';
|
|
11
|
-
import { flattenStandardHeader, generateContentDisposition } from '@standard-server/core';
|
|
12
|
-
import { toStandardLazyRequest, toEventStream } from '@standard-server/node';
|
|
13
|
-
import { mergeMap } from 'rxjs';
|
|
1
|
+
export * from "./constants.mjs";
|
|
2
|
+
export * from "./implement.mjs";
|
|
3
|
+
export {
|
|
14
4
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
18
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
19
|
-
if (decorator = decorators[i])
|
|
20
|
-
result = (decorator(result)) || result;
|
|
21
|
-
return result;
|
|
22
|
-
};
|
|
23
|
-
const ORPC_MODULE_CONFIG_SYMBOL = Symbol.for("ORPC_NEST_MODULE_CONFIG");
|
|
24
|
-
let ORPCModule = class {
|
|
25
|
-
static forRoot(config) {
|
|
26
|
-
return {
|
|
27
|
-
module: ORPCModule,
|
|
28
|
-
providers: [
|
|
29
|
-
{
|
|
30
|
-
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
31
|
-
useValue: config
|
|
32
|
-
},
|
|
33
|
-
ImplementInterceptor
|
|
34
|
-
],
|
|
35
|
-
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
36
|
-
global: true
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
static forRootAsync(options) {
|
|
40
|
-
return {
|
|
41
|
-
module: ORPCModule,
|
|
42
|
-
imports: options.imports,
|
|
43
|
-
providers: [
|
|
44
|
-
{
|
|
45
|
-
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
46
|
-
useFactory: options.useFactory,
|
|
47
|
-
inject: options.inject
|
|
48
|
-
},
|
|
49
|
-
ImplementInterceptor
|
|
50
|
-
],
|
|
51
|
-
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
52
|
-
global: true
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
ORPCModule = __decorateClass$1([
|
|
57
|
-
Module({})
|
|
58
|
-
], ORPCModule);
|
|
59
|
-
|
|
60
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
61
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
62
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
63
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
64
|
-
if (decorator = decorators[i])
|
|
65
|
-
result = (decorator(result)) || result;
|
|
66
|
-
return result;
|
|
67
|
-
};
|
|
68
|
-
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
69
|
-
const QueryMethod = NestCommon.QueryMethod;
|
|
70
|
-
const MethodDecoratorMap = {
|
|
71
|
-
HEAD: Head,
|
|
72
|
-
GET: Get,
|
|
73
|
-
POST: Post,
|
|
74
|
-
PUT: Put,
|
|
75
|
-
PATCH: Patch,
|
|
76
|
-
DELETE: Delete,
|
|
77
|
-
OPTIONS: Options
|
|
78
|
-
};
|
|
79
|
-
function Implement(contract) {
|
|
80
|
-
if (contract instanceof ProcedureContract) {
|
|
81
|
-
return (target, propertyKey, descriptor) => {
|
|
82
|
-
applyDecorators(
|
|
83
|
-
toNestRouteDecorator(contract),
|
|
84
|
-
UseInterceptors(ImplementInterceptor)
|
|
85
|
-
)(target, propertyKey, descriptor);
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
return (target, propertyKey, descriptor) => {
|
|
89
|
-
UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
|
|
90
|
-
implementRouterContract(contract, target, propertyKey, descriptor);
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
function toNestRouteDecorator(contract) {
|
|
94
|
-
const meta = getOpenAPIMeta(contract);
|
|
95
|
-
if (meta?.path === void 0) {
|
|
96
|
-
throw new TypeError(`
|
|
97
|
-
@Implement decorator requires contract to have a 'openapi.path' meta.
|
|
98
|
-
Please define one using '.meta(openapi({ path: '/example' }))'.
|
|
99
|
-
Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
|
|
100
|
-
`);
|
|
101
|
-
}
|
|
102
|
-
const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
|
|
103
|
-
const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
|
|
104
|
-
const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
105
|
-
if (method === "QUERY") {
|
|
106
|
-
if (!QueryMethod) {
|
|
107
|
-
throw new TypeError(`
|
|
108
|
-
@Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
|
|
109
|
-
The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
|
|
110
|
-
`);
|
|
111
|
-
}
|
|
112
|
-
return applyDecorators(
|
|
113
|
-
QueryMethod(path),
|
|
114
|
-
HttpCode(successStatus)
|
|
115
|
-
);
|
|
116
|
-
}
|
|
117
|
-
return applyDecorators(
|
|
118
|
-
MethodDecoratorMap[method](path),
|
|
119
|
-
HttpCode(successStatus)
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
function implementRouterContract(contract, target, propertyKey, descriptor) {
|
|
123
|
-
for (const [key, childContract] of Object.entries(contract)) {
|
|
124
|
-
let methodName = `${propertyKey}_${key}`;
|
|
125
|
-
let i = 0;
|
|
126
|
-
while (methodName in target) {
|
|
127
|
-
methodName = `${propertyKey}_${key}_${i++}`;
|
|
128
|
-
}
|
|
129
|
-
target[methodName] = async function(...args) {
|
|
130
|
-
const router = await descriptor.value.apply(this, args);
|
|
131
|
-
return getRouter(router, [key]);
|
|
132
|
-
};
|
|
133
|
-
Object.setPrototypeOf(target[methodName], descriptor.value);
|
|
134
|
-
queueMicrotask(() => {
|
|
135
|
-
for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
|
|
136
|
-
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
|
|
137
|
-
}
|
|
138
|
-
for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
|
|
139
|
-
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
|
|
140
|
-
}
|
|
141
|
-
});
|
|
142
|
-
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
|
|
143
|
-
if (childContract instanceof ProcedureContract) {
|
|
144
|
-
const routeDecorator = toNestRouteDecorator(childContract);
|
|
145
|
-
queueMicrotask(() => {
|
|
146
|
-
routeDecorator(target, methodName, childDescriptor);
|
|
147
|
-
});
|
|
148
|
-
} else {
|
|
149
|
-
implementRouterContract(childContract, target, methodName, childDescriptor);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
let ImplementInterceptor = class {
|
|
154
|
-
config;
|
|
155
|
-
codec;
|
|
156
|
-
handler;
|
|
157
|
-
toNestStandardLazyRequest;
|
|
158
|
-
httpAdapterHost;
|
|
159
|
-
constructor(config, httpAdapterHost) {
|
|
160
|
-
this.config = config ?? {};
|
|
161
|
-
this.httpAdapterHost = httpAdapterHost;
|
|
162
|
-
this.codec = new NestHandlerCodec(this.config);
|
|
163
|
-
this.handler = new StandardHandler(this.codec, this.config);
|
|
164
|
-
this.toNestStandardLazyRequest = this.config.toNestStandardLazyRequest ?? ((req, res) => {
|
|
165
|
-
const standardRequest = toStandardLazyRequest(
|
|
166
|
-
"raw" in req ? req.raw : req,
|
|
167
|
-
"raw" in res ? res.raw : res
|
|
168
|
-
);
|
|
169
|
-
if (req.body !== void 0) {
|
|
170
|
-
standardRequest.resolveBody = () => Promise.resolve(req.body);
|
|
171
|
-
}
|
|
172
|
-
standardRequest.params = req.params;
|
|
173
|
-
return standardRequest;
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
intercept(ctx, next) {
|
|
177
|
-
return next.handle().pipe(
|
|
178
|
-
mergeMap(async (impl) => {
|
|
179
|
-
const { default: procedure } = await unlazy(impl);
|
|
180
|
-
if (!(procedure instanceof Procedure)) {
|
|
181
|
-
throw new TypeError(`
|
|
182
|
-
The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
|
|
183
|
-
`);
|
|
184
|
-
}
|
|
185
|
-
const req = ctx.switchToHttp().getRequest();
|
|
186
|
-
const res = ctx.switchToHttp().getResponse();
|
|
187
|
-
const standardRequest = this.toNestStandardLazyRequest(req, res);
|
|
188
|
-
const context = await value(this.config.context ?? {}, ctx);
|
|
189
|
-
const result = await this.handler.handle(standardRequest, {
|
|
190
|
-
context: this.codec.withMatch(context, { procedure, params: standardRequest.params })
|
|
191
|
-
});
|
|
192
|
-
if (!result.matched) {
|
|
193
|
-
throw new TypeError(
|
|
194
|
-
"oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug."
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
const httpAdapter = this.httpAdapterHost.httpAdapter;
|
|
198
|
-
httpAdapter.status(res, result.response.status);
|
|
199
|
-
for (const key of Object.keys(result.response.headers)) {
|
|
200
|
-
const value2 = result.response.headers[key];
|
|
201
|
-
if (typeof value2 === "string") {
|
|
202
|
-
httpAdapter.setHeader(res, key, value2);
|
|
203
|
-
} else {
|
|
204
|
-
value2?.forEach((value3, index) => {
|
|
205
|
-
if (index === 0) {
|
|
206
|
-
httpAdapter.setHeader(res, key, value3);
|
|
207
|
-
} else {
|
|
208
|
-
httpAdapter.appendHeader(res, key, value3);
|
|
209
|
-
}
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
const body = result.response.body;
|
|
214
|
-
if (body instanceof ReadableStream) {
|
|
215
|
-
httpAdapter.setHeader(res, "standard-server", "octet-stream");
|
|
216
|
-
return toStreamableFile(Readable.fromWeb(body), standardRequest.signal, {
|
|
217
|
-
type: flattenStandardHeader(result.response.headers["content-type"]) ?? "application/octet-stream"
|
|
218
|
-
});
|
|
219
|
-
}
|
|
220
|
-
if (isAsyncIteratorObject(body)) {
|
|
221
|
-
return toStreamableFile(toEventStream(body, this.config.toNestResponse?.eventStream), standardRequest.signal, {
|
|
222
|
-
type: "text/event-stream"
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
if (body instanceof Blob) {
|
|
226
|
-
httpAdapter.setHeader(res, "standard-server", "file");
|
|
227
|
-
return toStreamableFile(Readable.fromWeb(body.stream()), standardRequest.signal, {
|
|
228
|
-
type: body.type,
|
|
229
|
-
disposition: flattenStandardHeader(result.response.headers["content-disposition"]) ?? generateContentDisposition(body instanceof File ? body.name : "blob"),
|
|
230
|
-
// BunS3 can use NaN for the size
|
|
231
|
-
length: Number.isFinite(body.size) ? body.size : void 0
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
if (body instanceof FormData) {
|
|
235
|
-
const response = new Response(body);
|
|
236
|
-
return toStreamableFile(Readable.fromWeb(response.body), standardRequest.signal, {
|
|
237
|
-
type: response.headers.get("content-type")
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
if (body instanceof URLSearchParams) {
|
|
241
|
-
httpAdapter.setHeader(res, "content-type", "application/x-www-form-urlencoded");
|
|
242
|
-
return body.toString();
|
|
243
|
-
}
|
|
244
|
-
if (body === void 0) {
|
|
245
|
-
return body;
|
|
246
|
-
}
|
|
247
|
-
if (result.response.status >= 300 && typeof body === "object" && body !== null && !Array.isArray(body)) {
|
|
248
|
-
throw new HttpException(body, result.response.status);
|
|
249
|
-
}
|
|
250
|
-
httpAdapter.setHeader(res, "content-type", "application/json");
|
|
251
|
-
return typeof body === "string" || body === null ? stringifyJSON(body) : body;
|
|
252
|
-
})
|
|
253
|
-
);
|
|
254
|
-
}
|
|
255
|
-
};
|
|
256
|
-
ImplementInterceptor = __decorateClass([
|
|
257
|
-
Injectable(),
|
|
258
|
-
__decorateParam(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
|
|
259
|
-
__decorateParam(0, Optional()),
|
|
260
|
-
__decorateParam(1, Inject(HttpAdapterHost))
|
|
261
|
-
], ImplementInterceptor);
|
|
262
|
-
class NestHandlerCodec extends OpenAPIHandlerCodecCore {
|
|
263
|
-
CONTEXT_SYMBOL = Symbol("ORPC_NEST_HANDLER_CODEC_CONTEXT");
|
|
264
|
-
withMatch(context, match) {
|
|
265
|
-
return { ...context, [this.CONTEXT_SYMBOL]: match };
|
|
266
|
-
}
|
|
267
|
-
resolveProcedure(request, options) {
|
|
268
|
-
const match = options.context[this.CONTEXT_SYMBOL];
|
|
269
|
-
if (!match) {
|
|
270
|
-
return void 0;
|
|
271
|
-
}
|
|
272
|
-
const { procedure, params } = match;
|
|
273
|
-
return {
|
|
274
|
-
path: getPathMeta(procedure) ?? [],
|
|
275
|
-
procedure,
|
|
276
|
-
decodeInput: () => this.decodeInput({
|
|
277
|
-
procedure,
|
|
278
|
-
params: toORPCOpenAPIParams(procedure, params)
|
|
279
|
-
}, request)
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
function toStreamableFile(stream, signal, options) {
|
|
284
|
-
if (signal?.aborted) {
|
|
285
|
-
stream.destroy();
|
|
286
|
-
} else {
|
|
287
|
-
signal?.addEventListener("abort", () => stream.destroy(), { once: true });
|
|
288
|
-
}
|
|
289
|
-
return new StreamableFile(stream, options);
|
|
290
|
-
}
|
|
291
|
-
function flattenParamValue(value2) {
|
|
292
|
-
return Array.isArray(value2) ? value2.join("/") : value2;
|
|
293
|
-
}
|
|
294
|
-
function toORPCOpenAPIParams(contract, params) {
|
|
295
|
-
const meta = getOpenAPIMeta(contract);
|
|
296
|
-
if (!params || meta?.path === void 0 || Object.keys(params).length === 0) {
|
|
297
|
-
return void 0;
|
|
298
|
-
}
|
|
299
|
-
const orpcParams = new NullProtoObj();
|
|
300
|
-
const restKey = Object.hasOwn(params, "*") ? "*" : "path";
|
|
301
|
-
for (const [key, value2] of Object.entries(params)) {
|
|
302
|
-
if (key === restKey) {
|
|
303
|
-
const restParams = getDynamicPathParams(
|
|
304
|
-
meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path
|
|
305
|
-
)?.filter((c) => c.allowsSlash);
|
|
306
|
-
if (restParams?.length) {
|
|
307
|
-
for (const c of restParams) {
|
|
308
|
-
orpcParams[c.parameterName] = flattenParamValue(value2);
|
|
309
|
-
}
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
orpcParams[key] = flattenParamValue(value2);
|
|
314
|
-
}
|
|
315
|
-
return orpcParams;
|
|
316
|
-
}
|
|
317
|
-
function toNestPattern(path) {
|
|
318
|
-
const params = getDynamicPathParams(path);
|
|
319
|
-
if (!params?.length) {
|
|
320
|
-
return path;
|
|
321
|
-
}
|
|
322
|
-
for (let i = params.length - 1; i >= 0; i--) {
|
|
323
|
-
const param = params[i];
|
|
324
|
-
const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
|
|
325
|
-
path = path.slice(0, param.startIndex) + pattern + path.slice(param.startIndex + param.segment.length);
|
|
326
|
-
}
|
|
327
|
-
return path;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
|
|
5
|
+
Implement as Impl } from "./implement.mjs";
|
|
6
|
+
export * from "./module.mjs";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { DynamicModule, ExecutionContext } from "@nestjs/common";
|
|
2
|
+
import type { OpenAPIHandlerCodecCoreOptions } from "@orpc/openapi/standard";
|
|
3
|
+
import type { DefaultInitialContext } from "@orpc/server";
|
|
4
|
+
import type { StandardHandlerOptions } from "@orpc/server/standard";
|
|
5
|
+
import type { Promisable, Value } from "@orpc/shared";
|
|
6
|
+
import type { StandardLazyRequest } from "@standard-server/core";
|
|
7
|
+
import type { ToEventStreamOptions } from "@standard-server/node";
|
|
8
|
+
/**
|
|
9
|
+
* A standard lazy request extended with NestJS route parameters,
|
|
10
|
+
* used as the request representation inside the `@orpc/nest` integration.
|
|
11
|
+
*
|
|
12
|
+
* @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
|
|
13
|
+
*/
|
|
14
|
+
export interface NestStandardLazyRequest extends StandardLazyRequest {
|
|
15
|
+
/**
|
|
16
|
+
* Route parameters extracted from the request path.
|
|
17
|
+
*/
|
|
18
|
+
params?: Record<string, string | string[]> | undefined;
|
|
19
|
+
}
|
|
20
|
+
export type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
|
|
21
|
+
context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
|
|
22
|
+
} : {
|
|
23
|
+
context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
|
|
24
|
+
}) & {
|
|
25
|
+
/**
|
|
26
|
+
* Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
|
|
27
|
+
* You might need to define this if you are not using the express, fastify or node adapters.
|
|
28
|
+
*/
|
|
29
|
+
toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
|
|
32
|
+
*/
|
|
33
|
+
toNestResponse?: {
|
|
34
|
+
/**
|
|
35
|
+
* Options for the event stream, like keep-alive settings, initial comment, etc.
|
|
36
|
+
*/
|
|
37
|
+
eventStream?: ToEventStreamOptions | undefined;
|
|
38
|
+
} | undefined;
|
|
39
|
+
};
|
|
40
|
+
export declare class ORPCModule {
|
|
41
|
+
static forRoot(config: ORPCModuleConfig): DynamicModule;
|
|
42
|
+
static forRootAsync(options: {
|
|
43
|
+
imports?: any[] | undefined;
|
|
44
|
+
useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
|
|
45
|
+
inject?: any[] | undefined;
|
|
46
|
+
}): DynamicModule;
|
|
47
|
+
}
|
package/dist/module.mjs
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Module } from "@nestjs/common";
|
|
2
|
+
import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.mjs";
|
|
3
|
+
import { ImplementInterceptor } from "./implement.mjs";
|
|
4
|
+
import _decorate from "@oxc-project/runtime/helpers/decorate";
|
|
5
|
+
var _ORPCModule;
|
|
6
|
+
let ORPCModule = _ORPCModule = class ORPCModule {
|
|
7
|
+
static forRoot(config) {
|
|
8
|
+
return {
|
|
9
|
+
module: _ORPCModule,
|
|
10
|
+
providers: [{
|
|
11
|
+
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
12
|
+
useValue: config
|
|
13
|
+
}, ImplementInterceptor],
|
|
14
|
+
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
15
|
+
global: true
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
static forRootAsync(options) {
|
|
19
|
+
return {
|
|
20
|
+
module: _ORPCModule,
|
|
21
|
+
imports: options.imports,
|
|
22
|
+
providers: [{
|
|
23
|
+
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
24
|
+
useFactory: options.useFactory,
|
|
25
|
+
inject: options.inject
|
|
26
|
+
}, ImplementInterceptor],
|
|
27
|
+
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
28
|
+
global: true
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
ORPCModule = _ORPCModule = _decorate([Module({})], ORPCModule);
|
|
33
|
+
export { ORPCModule };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orpc/nest",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.0.0-beta.
|
|
4
|
+
"version": "2.0.0-beta.48",
|
|
5
5
|
"description": "NestJS integration for oRPC: implement typesafe contracts in NestJS controllers",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"funding": [
|
|
@@ -39,11 +39,15 @@
|
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"@nestjs/common": ">=11.1.27",
|
|
41
41
|
"@nestjs/core": ">=11.1.27",
|
|
42
|
+
"@nestjs/platform-node": ">=12.3.0",
|
|
42
43
|
"express": ">=5.2.1",
|
|
43
44
|
"fastify": ">=5.8.5",
|
|
44
45
|
"rxjs": ">=7.8.2"
|
|
45
46
|
},
|
|
46
47
|
"peerDependenciesMeta": {
|
|
48
|
+
"@nestjs/platform-node": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
47
51
|
"express": {
|
|
48
52
|
"optional": true
|
|
49
53
|
},
|
|
@@ -52,21 +56,23 @@
|
|
|
52
56
|
}
|
|
53
57
|
},
|
|
54
58
|
"dependencies": {
|
|
55
|
-
"@orpc/client": "2.0.0-beta.
|
|
56
|
-
"@orpc/contract": "2.0.0-beta.
|
|
57
|
-
"@orpc/openapi": "2.0.0-beta.
|
|
58
|
-
"@orpc/server": "2.0.0-beta.
|
|
59
|
-
"@orpc/shared": "2.0.0-beta.
|
|
60
|
-
"@
|
|
61
|
-
"@standard-server/
|
|
59
|
+
"@orpc/client": "2.0.0-beta.48",
|
|
60
|
+
"@orpc/contract": "2.0.0-beta.48",
|
|
61
|
+
"@orpc/openapi": "2.0.0-beta.48",
|
|
62
|
+
"@orpc/server": "2.0.0-beta.48",
|
|
63
|
+
"@orpc/shared": "2.0.0-beta.48",
|
|
64
|
+
"@oxc-project/runtime": "^0.155.0",
|
|
65
|
+
"@standard-server/core": "~0.14.0",
|
|
66
|
+
"@standard-server/node": "~0.14.0"
|
|
62
67
|
},
|
|
63
68
|
"devDependencies": {
|
|
64
|
-
"@fastify/cookie": "^11.1.
|
|
65
|
-
"@nestjs/common": "^12.
|
|
66
|
-
"@nestjs/core": "^12.
|
|
67
|
-
"@nestjs/platform-express": "^12.
|
|
68
|
-
"@nestjs/platform-fastify": "^12.
|
|
69
|
-
"@nestjs/
|
|
69
|
+
"@fastify/cookie": "^11.1.5",
|
|
70
|
+
"@nestjs/common": "^12.3.2",
|
|
71
|
+
"@nestjs/core": "^12.3.2",
|
|
72
|
+
"@nestjs/platform-express": "^12.3.2",
|
|
73
|
+
"@nestjs/platform-fastify": "^12.3.2",
|
|
74
|
+
"@nestjs/platform-node": "^12.3.2",
|
|
75
|
+
"@nestjs/testing": "^12.3.2",
|
|
70
76
|
"@types/express": "^5.0.6",
|
|
71
77
|
"express": "^5.3.0",
|
|
72
78
|
"fastify": "^5.12.7",
|
package/dist/index.d.ts
DELETED
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import { ExecutionContext, DynamicModule, NestInterceptor, CallHandler } from '@nestjs/common';
|
|
2
|
-
import { RouterContract } from '@orpc/contract';
|
|
3
|
-
import { DefaultInitialContext, ContractedRouter } from '@orpc/server';
|
|
4
|
-
import { Value, Promisable } from '@orpc/shared';
|
|
5
|
-
import { Observable } from 'rxjs';
|
|
6
|
-
import { OpenAPIHandlerCodecCoreOptions } from '@orpc/openapi/standard';
|
|
7
|
-
import { StandardHandlerOptions } from '@orpc/server/standard';
|
|
8
|
-
import { StandardLazyRequest } from '@standard-server/core';
|
|
9
|
-
import { ToEventStreamOptions } from '@standard-server/node';
|
|
10
|
-
import { HttpAdapterHost } from '@nestjs/core';
|
|
11
|
-
|
|
12
|
-
declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
|
|
13
|
-
/**
|
|
14
|
-
* A standard lazy request extended with NestJS route parameters,
|
|
15
|
-
* used as the request representation inside the `@orpc/nest` integration.
|
|
16
|
-
*
|
|
17
|
-
* @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
|
|
18
|
-
*/
|
|
19
|
-
interface NestStandardLazyRequest extends StandardLazyRequest {
|
|
20
|
-
/**
|
|
21
|
-
* Route parameters extracted from the request path.
|
|
22
|
-
*/
|
|
23
|
-
params?: Record<string, string | string[]> | undefined;
|
|
24
|
-
}
|
|
25
|
-
type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
|
|
26
|
-
context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
|
|
27
|
-
} : {
|
|
28
|
-
context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
|
|
29
|
-
}) & {
|
|
30
|
-
/**
|
|
31
|
-
* Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
|
|
32
|
-
* You might need to define this if you are not using express or fastify adapters.
|
|
33
|
-
*/
|
|
34
|
-
toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
|
|
35
|
-
/**
|
|
36
|
-
* Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
|
|
37
|
-
*/
|
|
38
|
-
toNestResponse?: {
|
|
39
|
-
/**
|
|
40
|
-
* Options for the event stream, like keep-alive settings, initial comment, etc.
|
|
41
|
-
*/
|
|
42
|
-
eventStream?: ToEventStreamOptions | undefined;
|
|
43
|
-
} | undefined;
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* NestJS module that configures the `@orpc/nest` integration via `forRoot`
|
|
47
|
-
* or `forRootAsync`, providing options such as initial context, plugins,
|
|
48
|
-
* and interceptors to `@Implement` handlers.
|
|
49
|
-
*
|
|
50
|
-
* @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
|
|
51
|
-
*/
|
|
52
|
-
declare class ORPCModule {
|
|
53
|
-
static forRoot(config: ORPCModuleConfig): DynamicModule;
|
|
54
|
-
static forRootAsync(options: {
|
|
55
|
-
imports?: any[] | undefined;
|
|
56
|
-
useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
|
|
57
|
-
inject?: any[] | undefined;
|
|
58
|
-
}): DynamicModule;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Decorator that implements an oRPC contract (procedure or router contract)
|
|
63
|
-
* on a NestJS controller method. It registers the corresponding NestJS routes
|
|
64
|
-
* and handles request decoding and response encoding for you.
|
|
65
|
-
*
|
|
66
|
-
* @remarks
|
|
67
|
-
* **Note**: Every procedure contract must define an `openapi.path` meta;
|
|
68
|
-
* use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
|
|
69
|
-
* **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
|
|
70
|
-
*
|
|
71
|
-
* @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
|
|
72
|
-
*/
|
|
73
|
-
declare function Implement<T extends RouterContract>(contract: T): <U extends Promisable<ContractedRouter<T, DefaultInitialContext>>>(target: Record<PropertyKey, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => U>) => void;
|
|
74
|
-
declare class ImplementInterceptor implements NestInterceptor {
|
|
75
|
-
private readonly config;
|
|
76
|
-
private readonly codec;
|
|
77
|
-
private readonly handler;
|
|
78
|
-
private readonly toNestStandardLazyRequest;
|
|
79
|
-
private readonly httpAdapterHost;
|
|
80
|
-
constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
|
|
81
|
-
intercept(ctx: ExecutionContext, next: CallHandler<any>): Observable<any>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
|
|
85
|
-
export type { NestStandardLazyRequest, ORPCModuleConfig };
|