@orpc/nest 2.0.0-beta.48 → 2.0.0-beta.49
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 +4 -4
- package/dist/constants.js +2 -0
- package/dist/implement.d.ts +29 -0
- package/dist/implement.js +323 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/module.d.ts +54 -0
- package/dist/module.js +54 -0
- package/package.json +45 -47
- package/dist/constants.mjs +0 -1
- package/dist/implement.d.mts +0 -29
- package/dist/implement.mjs +0 -287
- package/dist/index.d.mts +0 -8
- package/dist/index.mjs +0 -6
- package/dist/module.d.mts +0 -47
- package/dist/module.mjs +0 -33
- /package/dist/{constants.d.mts → constants.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
|
|
6
6
|
</a>
|
|
7
7
|
<a href="https://www.npmjs.com/package/@orpc/nest">
|
|
8
|
-
<img alt="
|
|
8
|
+
<img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fnest?logo=npm" />
|
|
9
9
|
</a>
|
|
10
10
|
<a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
|
|
11
11
|
<img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
|
|
@@ -41,10 +41,11 @@ export const router = {
|
|
|
41
41
|
Then call them from a client that knows every input and output, without generating anything:
|
|
42
42
|
|
|
43
43
|
```ts
|
|
44
|
-
import type { RouterClient } from '@orpc/server'
|
|
45
|
-
import type { router } from './router'
|
|
46
44
|
import { createORPCClient } from '@orpc/client'
|
|
47
45
|
import { RPCLink } from '@orpc/client/fetch'
|
|
46
|
+
import type { RouterClient } from '@orpc/server'
|
|
47
|
+
|
|
48
|
+
import type { router } from './router'
|
|
48
49
|
|
|
49
50
|
const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
|
|
50
51
|
const client: RouterClient<typeof router> = createORPCClient(link)
|
|
@@ -208,7 +209,6 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
|
|
|
208
209
|
<tr>
|
|
209
210
|
<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
211
|
<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>
|
|
212
212
|
</tr>
|
|
213
213
|
</table>
|
|
214
214
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
|
|
2
|
+
import { HttpAdapterHost } from '@nestjs/core';
|
|
3
|
+
import type { RouterContract } from '@orpc/contract';
|
|
4
|
+
import type { ContractedRouter, DefaultInitialContext } from '@orpc/server';
|
|
5
|
+
import type { Promisable } from '@orpc/shared';
|
|
6
|
+
import type { Observable } from 'rxjs';
|
|
7
|
+
import type { ORPCModuleConfig } from './module.ts';
|
|
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): Observable<any>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Readable } from 'node:stream';
|
|
14
|
+
import * as NestCommon from '@nestjs/common';
|
|
15
|
+
import { applyDecorators, Delete, Get, Head, HttpCode, HttpException, Inject, Injectable, Optional, Options, Patch, Post, Put, StreamableFile, UseInterceptors, } from '@nestjs/common';
|
|
16
|
+
import { HttpAdapterHost } from '@nestjs/core';
|
|
17
|
+
import { getPathMeta, ProcedureContract } from '@orpc/contract';
|
|
18
|
+
import { DEFAULT_OPENAPI_METHOD, getDynamicPathParams, getOpenAPIMeta } from '@orpc/openapi';
|
|
19
|
+
import { OpenAPIHandlerCodecCore } from '@orpc/openapi/standard';
|
|
20
|
+
import { DEFAULT_SUCCESS_STATUS, getRouter, Procedure, unlazy } from '@orpc/server';
|
|
21
|
+
import { StandardHandler } from '@orpc/server/standard';
|
|
22
|
+
import { isAsyncIteratorObject, mergeHttpPath, NullProtoObj, stringifyJSON, toArray, value, } from '@orpc/shared';
|
|
23
|
+
import { flattenStandardHeader, generateContentDisposition, getRequiredStandardBodyHint, } from '@standard-server/core';
|
|
24
|
+
import { toEventStream, toStandardLazyRequest } from '@standard-server/node';
|
|
25
|
+
import { mergeMap } from 'rxjs';
|
|
26
|
+
import { ORPC_MODULE_CONFIG_SYMBOL } from './constants.js';
|
|
27
|
+
// Namespace access so NestJS < 11.2 (no QueryMethod export) loads without a SyntaxError
|
|
28
|
+
const QueryMethod = NestCommon.QueryMethod;
|
|
29
|
+
const MethodDecoratorMap = {
|
|
30
|
+
HEAD: Head,
|
|
31
|
+
GET: Get,
|
|
32
|
+
POST: Post,
|
|
33
|
+
PUT: Put,
|
|
34
|
+
PATCH: Patch,
|
|
35
|
+
DELETE: Delete,
|
|
36
|
+
OPTIONS: Options,
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Decorator that implements an oRPC contract (procedure or router contract)
|
|
40
|
+
* on a NestJS controller method. It registers the corresponding NestJS routes
|
|
41
|
+
* and handles request decoding and response encoding for you.
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* **Note**: Every procedure contract must define an `openapi.path` meta;
|
|
45
|
+
* use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
|
|
46
|
+
* **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
|
|
47
|
+
*
|
|
48
|
+
* @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
|
|
49
|
+
*/
|
|
50
|
+
export function Implement(contract) {
|
|
51
|
+
if (contract instanceof ProcedureContract) {
|
|
52
|
+
return (target, propertyKey, descriptor) => {
|
|
53
|
+
applyDecorators(toNestRouteDecorator(contract), UseInterceptors(ImplementInterceptor))(target, propertyKey, descriptor);
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return (target, propertyKey, descriptor) => {
|
|
57
|
+
// applied at the decorated method level so interceptor order follows decorator order,
|
|
58
|
+
// and synthesized methods inherit the full ordered list through the prototype chain
|
|
59
|
+
UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
|
|
60
|
+
implementRouterContract(contract, target, propertyKey, descriptor);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function toNestRouteDecorator(contract) {
|
|
64
|
+
const meta = getOpenAPIMeta(contract);
|
|
65
|
+
if (meta?.path === undefined) {
|
|
66
|
+
throw new TypeError(`
|
|
67
|
+
@Implement decorator requires contract to have a 'openapi.path' meta.
|
|
68
|
+
Please define one using '.meta(openapi({ path: '/example' }))'.
|
|
69
|
+
Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
|
|
70
|
+
`);
|
|
71
|
+
}
|
|
72
|
+
const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
|
|
73
|
+
const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
|
|
74
|
+
const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
75
|
+
if (method === 'QUERY') {
|
|
76
|
+
if (!QueryMethod) {
|
|
77
|
+
throw new TypeError(`
|
|
78
|
+
@Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
|
|
79
|
+
The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
|
|
80
|
+
`);
|
|
81
|
+
}
|
|
82
|
+
return applyDecorators(QueryMethod(path), HttpCode(successStatus));
|
|
83
|
+
}
|
|
84
|
+
return applyDecorators(MethodDecoratorMap[method](path), HttpCode(successStatus));
|
|
85
|
+
}
|
|
86
|
+
function implementRouterContract(contract, target, propertyKey, descriptor) {
|
|
87
|
+
for (const [key, childContract] of Object.entries(contract)) {
|
|
88
|
+
let methodName = `${propertyKey}_${key}`;
|
|
89
|
+
let i = 0;
|
|
90
|
+
while (methodName in target) {
|
|
91
|
+
methodName = `${propertyKey}_${key}_${i++}`;
|
|
92
|
+
}
|
|
93
|
+
target[methodName] = async function (...args) {
|
|
94
|
+
const router = await descriptor.value.apply(this, args);
|
|
95
|
+
return getRouter(router, [key]);
|
|
96
|
+
};
|
|
97
|
+
Object.setPrototypeOf(target[methodName], descriptor.value);
|
|
98
|
+
queueMicrotask(() => {
|
|
99
|
+
for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
|
|
100
|
+
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
|
|
101
|
+
}
|
|
102
|
+
for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
|
|
103
|
+
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
|
|
107
|
+
if (childContract instanceof ProcedureContract) {
|
|
108
|
+
const routeDecorator = toNestRouteDecorator(childContract);
|
|
109
|
+
// applied after the deferred metadata copies so route metadata cannot be overridden
|
|
110
|
+
queueMicrotask(() => {
|
|
111
|
+
routeDecorator(target, methodName, childDescriptor);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
implementRouterContract(childContract, target, methodName, childDescriptor);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
let ImplementInterceptor = class ImplementInterceptor {
|
|
120
|
+
config;
|
|
121
|
+
codec;
|
|
122
|
+
handler;
|
|
123
|
+
toNestStandardLazyRequest;
|
|
124
|
+
httpAdapterHost;
|
|
125
|
+
constructor(config, httpAdapterHost) {
|
|
126
|
+
// @Optional() does not allow set default value so we need to do it here
|
|
127
|
+
this.config = config ?? {};
|
|
128
|
+
this.httpAdapterHost = httpAdapterHost;
|
|
129
|
+
this.codec = new NestHandlerCodec(this.config);
|
|
130
|
+
this.handler = new StandardHandler(this.codec, this.config);
|
|
131
|
+
this.toNestStandardLazyRequest =
|
|
132
|
+
this.config.toNestStandardLazyRequest ??
|
|
133
|
+
((req, res) => {
|
|
134
|
+
const standardRequest = toStandardLazyRequest('raw' in req ? req.raw : req, 'raw' in res ? res.raw : res);
|
|
135
|
+
// if body already parsed by NestJS
|
|
136
|
+
if (req.body !== undefined) {
|
|
137
|
+
standardRequest.resolveBody = () => Promise.resolve(req.body);
|
|
138
|
+
}
|
|
139
|
+
standardRequest.params = req.params;
|
|
140
|
+
return standardRequest;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
intercept(ctx, next) {
|
|
144
|
+
return next.handle().pipe(mergeMap(async (impl) => {
|
|
145
|
+
const { default: procedure } = await unlazy(impl);
|
|
146
|
+
if (!(procedure instanceof Procedure)) {
|
|
147
|
+
throw new TypeError(`
|
|
148
|
+
The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
|
|
149
|
+
`);
|
|
150
|
+
}
|
|
151
|
+
const req = ctx.switchToHttp().getRequest();
|
|
152
|
+
const res = ctx.switchToHttp().getResponse();
|
|
153
|
+
const standardRequest = this.toNestStandardLazyRequest(req, res);
|
|
154
|
+
const context = await value(this.config.context ?? {}, ctx);
|
|
155
|
+
const result = await this.handler.handle(standardRequest, {
|
|
156
|
+
context: this.codec.withMatch(context, { procedure, params: standardRequest.params }),
|
|
157
|
+
});
|
|
158
|
+
if (!result.matched) {
|
|
159
|
+
throw new TypeError('oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug.');
|
|
160
|
+
}
|
|
161
|
+
const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
|
|
162
|
+
const httpAdapter = this.httpAdapterHost.httpAdapter;
|
|
163
|
+
httpAdapter.status(res, result.response.status);
|
|
164
|
+
for (const key of Object.keys(headers)) {
|
|
165
|
+
toArray(headers[key]).forEach((value, index) => {
|
|
166
|
+
if (index === 0) {
|
|
167
|
+
httpAdapter.setHeader(res, key, value);
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
httpAdapter.appendHeader(res, key, value);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (nestBody instanceof HttpException) {
|
|
175
|
+
throw nestBody;
|
|
176
|
+
}
|
|
177
|
+
return nestBody;
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
ImplementInterceptor = __decorate([
|
|
182
|
+
Injectable(),
|
|
183
|
+
__param(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
|
|
184
|
+
__param(0, Optional()),
|
|
185
|
+
__param(1, Inject(HttpAdapterHost)),
|
|
186
|
+
__metadata("design:paramtypes", [Object, HttpAdapterHost])
|
|
187
|
+
], ImplementInterceptor);
|
|
188
|
+
export { ImplementInterceptor };
|
|
189
|
+
/**
|
|
190
|
+
* Mirrors `toNodeHttpBody` from `@standard-server/node`, but returns a body NestJS can respond with.
|
|
191
|
+
*/
|
|
192
|
+
function toNestHttpBody(response, signal, options) {
|
|
193
|
+
const { status, body } = response;
|
|
194
|
+
const headers = { ...response.headers };
|
|
195
|
+
if (body instanceof ReadableStream) {
|
|
196
|
+
headers['standard-server'] ??= 'octet-stream';
|
|
197
|
+
headers['content-type'] ??= 'application/octet-stream';
|
|
198
|
+
return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
|
|
199
|
+
}
|
|
200
|
+
if (body instanceof Blob) {
|
|
201
|
+
headers['standard-server'] ??= 'file';
|
|
202
|
+
headers['content-type'] ??= body.type;
|
|
203
|
+
headers['content-disposition'] ??= generateContentDisposition(body instanceof File ? body.name : 'blob');
|
|
204
|
+
// BunS3 can use NaN for the size
|
|
205
|
+
if (Number.isFinite(body.size)) {
|
|
206
|
+
headers['content-length'] = body.size.toString();
|
|
207
|
+
}
|
|
208
|
+
return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
|
|
209
|
+
}
|
|
210
|
+
headers['standard-server'] = undefined;
|
|
211
|
+
headers['content-length'] = undefined;
|
|
212
|
+
if (body === undefined) {
|
|
213
|
+
headers['content-type'] = undefined;
|
|
214
|
+
return [undefined, headers];
|
|
215
|
+
}
|
|
216
|
+
if (body instanceof FormData) {
|
|
217
|
+
const response = new Response(body);
|
|
218
|
+
headers['content-type'] = response.headers.get('content-type');
|
|
219
|
+
return [toStreamableFile(Readable.fromWeb(response.body), headers, signal), headers];
|
|
220
|
+
}
|
|
221
|
+
if (body instanceof URLSearchParams) {
|
|
222
|
+
headers['content-type'] ??= 'application/x-www-form-urlencoded';
|
|
223
|
+
headers['standard-server'] = getRequiredStandardBodyHint('url-search-params', headers);
|
|
224
|
+
return [body.toString(), headers];
|
|
225
|
+
}
|
|
226
|
+
if (isAsyncIteratorObject(body)) {
|
|
227
|
+
headers['content-type'] ??= 'text/event-stream';
|
|
228
|
+
headers['standard-server'] = getRequiredStandardBodyHint('event-stream', headers);
|
|
229
|
+
return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
|
|
230
|
+
}
|
|
231
|
+
// Prefer throwing an HttpException for more native error handling in NestJS.
|
|
232
|
+
if (status >= 300 && typeof body === 'object' && body !== null && !Array.isArray(body)) {
|
|
233
|
+
if (headers['content-type'] !== undefined) {
|
|
234
|
+
headers['standard-server'] = getRequiredStandardBodyHint('json', headers);
|
|
235
|
+
}
|
|
236
|
+
return [new HttpException(body, status), headers];
|
|
237
|
+
}
|
|
238
|
+
headers['content-type'] ??= 'application/json';
|
|
239
|
+
headers['standard-server'] = getRequiredStandardBodyHint('json', headers);
|
|
240
|
+
return [
|
|
241
|
+
typeof body === 'string' || body === null || headers['standard-server'] !== undefined
|
|
242
|
+
? stringifyJSON(body)
|
|
243
|
+
: body,
|
|
244
|
+
headers,
|
|
245
|
+
];
|
|
246
|
+
}
|
|
247
|
+
class NestHandlerCodec extends OpenAPIHandlerCodecCore {
|
|
248
|
+
CONTEXT_SYMBOL = Symbol('ORPC_NEST_HANDLER_CODEC_CONTEXT');
|
|
249
|
+
withMatch(context, match) {
|
|
250
|
+
return { ...context, [this.CONTEXT_SYMBOL]: match };
|
|
251
|
+
}
|
|
252
|
+
resolveProcedure(request, options) {
|
|
253
|
+
const match = options.context[this.CONTEXT_SYMBOL];
|
|
254
|
+
if (!match) {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
const { procedure, params } = match;
|
|
258
|
+
return {
|
|
259
|
+
path: getPathMeta(procedure) ?? [],
|
|
260
|
+
procedure,
|
|
261
|
+
decodeInput: () => this.decodeInput({
|
|
262
|
+
procedure,
|
|
263
|
+
params: toORPCOpenAPIParams(procedure, params),
|
|
264
|
+
}, request),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Destroys the stream once the request is aborted, because Nest's Express adapter only pipes a StreamableFile
|
|
270
|
+
* and never destroys it on client disconnect, which would leave the underlying event iterator or stream uncanceled.
|
|
271
|
+
*/
|
|
272
|
+
function toStreamableFile(stream, headers, signal) {
|
|
273
|
+
const type = flattenStandardHeader(headers['content-type']);
|
|
274
|
+
headers['content-type'] = undefined;
|
|
275
|
+
if (signal?.aborted) {
|
|
276
|
+
stream.destroy();
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
signal?.addEventListener('abort', () => stream.destroy(), { once: true });
|
|
280
|
+
}
|
|
281
|
+
return new StreamableFile(stream, { type });
|
|
282
|
+
}
|
|
283
|
+
function flattenParamValue(value) {
|
|
284
|
+
return Array.isArray(value) ? value.join('/') : value;
|
|
285
|
+
}
|
|
286
|
+
function toORPCOpenAPIParams(contract, params) {
|
|
287
|
+
const meta = getOpenAPIMeta(contract);
|
|
288
|
+
if (!params || meta?.path === undefined || Object.keys(params).length === 0) {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
// NullProtoObj prevents prototype injection when a param is named like `__proto__`
|
|
292
|
+
const orpcParams = new NullProtoObj();
|
|
293
|
+
// express and node use `path` while fastify uses `*` for rest matching
|
|
294
|
+
const restKey = Object.hasOwn(params, '*') ? '*' : 'path';
|
|
295
|
+
for (const [key, value] of Object.entries(params)) {
|
|
296
|
+
if (key === restKey) {
|
|
297
|
+
const restParams = getDynamicPathParams(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path)?.filter((c) => c.allowsSlash);
|
|
298
|
+
if (restParams?.length) {
|
|
299
|
+
for (const c of restParams) {
|
|
300
|
+
orpcParams[c.parameterName] = flattenParamValue(value);
|
|
301
|
+
}
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
orpcParams[key] = flattenParamValue(value);
|
|
306
|
+
}
|
|
307
|
+
return orpcParams;
|
|
308
|
+
}
|
|
309
|
+
function toNestPattern(path) {
|
|
310
|
+
const params = getDynamicPathParams(path);
|
|
311
|
+
if (!params?.length) {
|
|
312
|
+
return path;
|
|
313
|
+
}
|
|
314
|
+
for (let i = params.length - 1; i >= 0; i--) {
|
|
315
|
+
const param = params[i];
|
|
316
|
+
const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
|
|
317
|
+
path =
|
|
318
|
+
path.slice(0, param.startIndex) +
|
|
319
|
+
pattern +
|
|
320
|
+
path.slice(param.startIndex + param.segment.length);
|
|
321
|
+
}
|
|
322
|
+
return path;
|
|
323
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/module.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
/**
|
|
41
|
+
* NestJS module that configures the `@orpc/nest` integration via `forRoot`
|
|
42
|
+
* or `forRootAsync`, providing options such as initial context, plugins,
|
|
43
|
+
* and interceptors to `@Implement` handlers.
|
|
44
|
+
*
|
|
45
|
+
* @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
|
|
46
|
+
*/
|
|
47
|
+
export declare class ORPCModule {
|
|
48
|
+
static forRoot(config: ORPCModuleConfig): DynamicModule;
|
|
49
|
+
static forRootAsync(options: {
|
|
50
|
+
imports?: any[] | undefined;
|
|
51
|
+
useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
|
|
52
|
+
inject?: any[] | undefined;
|
|
53
|
+
}): DynamicModule;
|
|
54
|
+
}
|
package/dist/module.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var ORPCModule_1;
|
|
8
|
+
import { Module } from '@nestjs/common';
|
|
9
|
+
import { ORPC_MODULE_CONFIG_SYMBOL } from './constants.js';
|
|
10
|
+
import { ImplementInterceptor } from './implement.js';
|
|
11
|
+
/**
|
|
12
|
+
* NestJS module that configures the `@orpc/nest` integration via `forRoot`
|
|
13
|
+
* or `forRootAsync`, providing options such as initial context, plugins,
|
|
14
|
+
* and interceptors to `@Implement` handlers.
|
|
15
|
+
*
|
|
16
|
+
* @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
|
|
17
|
+
*/
|
|
18
|
+
let ORPCModule = ORPCModule_1 = class ORPCModule {
|
|
19
|
+
static forRoot(config) {
|
|
20
|
+
return {
|
|
21
|
+
module: ORPCModule_1,
|
|
22
|
+
providers: [
|
|
23
|
+
{
|
|
24
|
+
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
25
|
+
useValue: config,
|
|
26
|
+
},
|
|
27
|
+
ImplementInterceptor,
|
|
28
|
+
],
|
|
29
|
+
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
30
|
+
global: true,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
static forRootAsync(options) {
|
|
34
|
+
return {
|
|
35
|
+
module: ORPCModule_1,
|
|
36
|
+
imports: options.imports,
|
|
37
|
+
providers: [
|
|
38
|
+
{
|
|
39
|
+
provide: ORPC_MODULE_CONFIG_SYMBOL,
|
|
40
|
+
useFactory: options.useFactory,
|
|
41
|
+
inject: options.inject,
|
|
42
|
+
},
|
|
43
|
+
ImplementInterceptor,
|
|
44
|
+
],
|
|
45
|
+
exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
|
|
46
|
+
global: true,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
ORPCModule = ORPCModule_1 = __decorate([
|
|
51
|
+
Module({})
|
|
52
|
+
// oxlint-disable-next-line typescript/no-extraneous-class
|
|
53
|
+
], ORPCModule);
|
|
54
|
+
export { ORPCModule };
|
package/package.json
CHANGED
|
@@ -1,41 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orpc/nest",
|
|
3
|
-
"
|
|
4
|
-
"version": "2.0.0-beta.48",
|
|
3
|
+
"version": "2.0.0-beta.49",
|
|
5
4
|
"description": "NestJS integration for oRPC: implement typesafe contracts in NestJS controllers",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
"
|
|
9
|
-
"
|
|
5
|
+
"keywords": [
|
|
6
|
+
"contract-first",
|
|
7
|
+
"nest",
|
|
8
|
+
"nestjs",
|
|
9
|
+
"openapi",
|
|
10
|
+
"orpc",
|
|
11
|
+
"rpc",
|
|
12
|
+
"typesafe",
|
|
13
|
+
"typescript"
|
|
10
14
|
],
|
|
11
15
|
"homepage": "https://orpc.dev",
|
|
16
|
+
"license": "MIT",
|
|
12
17
|
"repository": {
|
|
13
18
|
"type": "git",
|
|
14
19
|
"url": "git+https://github.com/middleapi/orpc.git",
|
|
15
20
|
"directory": "packages/nest"
|
|
16
21
|
},
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"nest",
|
|
21
|
-
"contract-first",
|
|
22
|
-
"rpc",
|
|
23
|
-
"openapi",
|
|
24
|
-
"typescript",
|
|
25
|
-
"typesafe"
|
|
22
|
+
"funding": [
|
|
23
|
+
"https://github.com/sponsors/dinwwwh",
|
|
24
|
+
"https://opencollective.com/middleapi"
|
|
26
25
|
],
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"type": "module",
|
|
27
30
|
"sideEffects": false,
|
|
28
31
|
"exports": {
|
|
29
32
|
"./package.json": "./package.json",
|
|
30
33
|
".": {
|
|
31
|
-
"types": "./dist/index.d.
|
|
32
|
-
"import": "./dist/index.
|
|
33
|
-
"default": "./dist/index.
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"default": "./dist/index.js"
|
|
34
37
|
}
|
|
35
38
|
},
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@orpc/client": "2.0.0-beta.49",
|
|
41
|
+
"@orpc/contract": "2.0.0-beta.49",
|
|
42
|
+
"@orpc/openapi": "2.0.0-beta.49",
|
|
43
|
+
"@orpc/server": "2.0.0-beta.49",
|
|
44
|
+
"@orpc/shared": "2.0.0-beta.49",
|
|
45
|
+
"@oxc-project/runtime": "^0.155.0",
|
|
46
|
+
"@standard-server/core": "~0.15.0",
|
|
47
|
+
"@standard-server/node": "~0.15.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@fastify/cookie": "^11.1.5",
|
|
51
|
+
"@nestjs/common": "^12.3.2",
|
|
52
|
+
"@nestjs/core": "^12.3.2",
|
|
53
|
+
"@nestjs/platform-express": "^12.3.2",
|
|
54
|
+
"@nestjs/platform-fastify": "^12.3.2",
|
|
55
|
+
"@nestjs/platform-node": "^12.3.2",
|
|
56
|
+
"@nestjs/testing": "^12.3.2",
|
|
57
|
+
"@types/express": "^5.0.6",
|
|
58
|
+
"express": "^5.3.0",
|
|
59
|
+
"fastify": "^5.12.8",
|
|
60
|
+
"rxjs": "^7.8.2"
|
|
61
|
+
},
|
|
39
62
|
"peerDependencies": {
|
|
40
63
|
"@nestjs/common": ">=11.1.27",
|
|
41
64
|
"@nestjs/core": ">=11.1.27",
|
|
@@ -55,30 +78,5 @@
|
|
|
55
78
|
"optional": true
|
|
56
79
|
}
|
|
57
80
|
},
|
|
58
|
-
"
|
|
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"
|
|
67
|
-
},
|
|
68
|
-
"devDependencies": {
|
|
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",
|
|
76
|
-
"@types/express": "^5.0.6",
|
|
77
|
-
"express": "^5.3.0",
|
|
78
|
-
"fastify": "^5.12.7",
|
|
79
|
-
"rxjs": "^7.8.2"
|
|
80
|
-
},
|
|
81
|
-
"scripts": {
|
|
82
|
-
"type:check": "tsc -b"
|
|
83
|
-
}
|
|
81
|
+
"scripts": {}
|
|
84
82
|
}
|
package/dist/constants.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export const ORPC_MODULE_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_NEST_MODULE_CONFIG");
|
package/dist/implement.d.mts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/implement.mjs
DELETED
|
@@ -1,287 +0,0 @@
|
|
|
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
DELETED
package/dist/index.mjs
DELETED
package/dist/module.d.mts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
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 };
|
|
File without changes
|