trpc-uwebsockets 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Roman Volovoy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # trpc-uwebsockets
2
+
3
+ [uWebSockets.js](https://github.com/uNetworking/uWebSockets.js) adapter for [tRPC](https://trpc.io/)
4
+
5
+ # Installation
6
+
7
+ ```bash
8
+ yarn install trpc-uwebsockets
9
+ ```
10
+
11
+ or
12
+
13
+ ```bash
14
+ yarn add trpc-uwebsockets
15
+ ```
16
+
17
+ # Usage
18
+
19
+ Import needed packages
20
+
21
+ ```typescript
22
+ import { App } from 'uWebSockets.js';
23
+ import * as trpc from '@trpc/server';
24
+ ```
25
+
26
+ Define tRPC context and router
27
+
28
+ ```typescript
29
+ type Context = {
30
+ user: {
31
+ name: string;
32
+ } | null;
33
+ };
34
+
35
+ const createContext: any = (opts: UWebSocketsContextOptions): Context => {
36
+ const getUser = () => {
37
+ if (opts.req.headers.authorization === 'meow') {
38
+ return {
39
+ name: 'KATT',
40
+ };
41
+ }
42
+ return null;
43
+ };
44
+
45
+ return {
46
+ user: getUser(),
47
+ };
48
+ };
49
+
50
+ const router = trpc.router<Context>().query('hello', {
51
+ input: z
52
+ .object({
53
+ who: z.string().nullish(),
54
+ })
55
+ .nullish(),
56
+ resolve({ input, ctx }) {
57
+ return {
58
+ text: `hello ${input?.who ?? ctx.user?.name ?? 'world'}`,
59
+ };
60
+ },
61
+ });
62
+ ```
63
+
64
+ Initialize uWebsockets server and attach tTRP router
65
+
66
+ ```typescript
67
+ const app = App();
68
+
69
+ createUWebSocketsHandler(app, '/trpc', {
70
+ router,
71
+ createContext,
72
+ });
73
+
74
+ app.listen('0.0.0.0', 8000, () => {
75
+ console.log('server listening on http://localhost:8000');
76
+ });
77
+ ```
78
+
79
+ # Testing
80
+
81
+ ```bash
82
+ yarn t
83
+ ```
84
+
85
+ or
86
+
87
+ ```bash
88
+ yarn test:watch
89
+ ```
package/dist/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import { resolveHTTPResponse, } from '@trpc/server';
2
+ import { readPostBody } from './utils';
3
+ export * from './types';
4
+ /**
5
+ *
6
+ * @param uWsApp uWebsockets server instance
7
+ * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
8
+ * @param opts router and createContext functions
9
+ */
10
+ export function createUWebSocketsHandler(uWsApp, pathPrefix, opts) {
11
+ const prefixTrimLength = pathPrefix.length + 1; // remove /* from url
12
+ const handler = async (res, req) => {
13
+ const method = req.getMethod().toUpperCase();
14
+ if (method !== 'GET' && method !== 'POST') {
15
+ // handle only get and post requests, while the rest
16
+ // will not be captured and propagated further
17
+ req.setYield(true);
18
+ return;
19
+ }
20
+ const path = req.getUrl().substring(prefixTrimLength);
21
+ const query = new URLSearchParams(decodeURIComponent(req.getQuery()));
22
+ const headers = {};
23
+ req.forEach((key, value) => {
24
+ headers[key] = value;
25
+ });
26
+ // new request object needs to be created, because socket
27
+ // can only be accessed synchronously, after await it cannot be accessed
28
+ const requestObj = {
29
+ headers,
30
+ method,
31
+ query,
32
+ path,
33
+ };
34
+ const bodyResult = await readPostBody(method, res);
35
+ // req is no longer available!
36
+ const createContext = async function _() {
37
+ //res could be proxied here
38
+ return await opts.createContext?.({
39
+ // res,
40
+ req: requestObj,
41
+ });
42
+ };
43
+ const fakeReqObject = {
44
+ method,
45
+ headers,
46
+ query,
47
+ body: bodyResult.ok ? bodyResult.data : undefined,
48
+ };
49
+ // TODO batching, onError options need implementation.
50
+ // responseMeta is not applicable?
51
+ const result = await resolveHTTPResponse({
52
+ path,
53
+ createContext,
54
+ router: opts.router,
55
+ req: fakeReqObject,
56
+ error: bodyResult.ok ? null : bodyResult.error,
57
+ });
58
+ if ('status' in result) {
59
+ res.writeStatus(result.status.toString()); //temp
60
+ }
61
+ else {
62
+ // assume something went bad, should never happen?
63
+ // there is no way to know from res object that something was send to the socket
64
+ // can proxy it to detect res calls during createContext and resolve
65
+ // then will need to exit from here
66
+ res.cork(() => {
67
+ res.writeStatus('500 INTERNAL SERVER ERROR');
68
+ res.end();
69
+ });
70
+ return;
71
+ }
72
+ for (const [key, value] of Object.entries(result.headers ?? {})) {
73
+ if (typeof value === 'undefined') {
74
+ continue;
75
+ }
76
+ // FIX not sure why it could be an array. This code path is not tested
77
+ if (Array.isArray(value))
78
+ value.forEach((header) => {
79
+ res.writeHeader(key, header);
80
+ });
81
+ else
82
+ res.writeHeader(key, value);
83
+ }
84
+ res.cork(() => {
85
+ if (result.body)
86
+ res.write(result.body);
87
+ res.end();
88
+ });
89
+ };
90
+ uWsApp.any(pathPrefix + '/*', handler);
91
+ }
92
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.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C,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;gBAC/B,CAAC,CAAC,CAAC;;gBACA,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;SAClC;QAED,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE;YACZ,IAAI,MAAM,CAAC,IAAI;gBAAE,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACxC,GAAG,CAAC,GAAG,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,CAAC,GAAG,CAAC,UAAU,GAAG,IAAI,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/dist/utils.js ADDED
@@ -0,0 +1,47 @@
1
+ import { TRPCError } from '@trpc/server';
2
+ export function readPostBody(method, res) {
3
+ return new Promise((resolve) => {
4
+ if (method == 'GET') {
5
+ // no body in get request
6
+ resolve({
7
+ ok: true,
8
+ data: undefined,
9
+ });
10
+ }
11
+ let buffer;
12
+ res.onData((ab, isLast) => {
13
+ const chunk = Buffer.from(ab);
14
+ if (isLast) {
15
+ if (buffer) {
16
+ // large request, with multiple chunks
17
+ resolve({
18
+ ok: true,
19
+ data: buffer.toString(), // do i need utf8?
20
+ });
21
+ }
22
+ else {
23
+ // only a single chunk was recieved
24
+ resolve({
25
+ ok: true,
26
+ data: chunk.toString(),
27
+ });
28
+ }
29
+ }
30
+ else {
31
+ if (buffer) {
32
+ buffer = Buffer.concat([buffer, chunk]);
33
+ }
34
+ else {
35
+ buffer = Buffer.concat([chunk]);
36
+ }
37
+ }
38
+ });
39
+ res.onAborted(() => {
40
+ resolve({
41
+ ok: false,
42
+ error: new TRPCError({ code: 'CLIENT_CLOSED_REQUEST' }),
43
+ });
44
+ });
45
+ });
46
+ }
47
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,MAAM,UAAU,YAAY,CAAC,MAAc,EAAE,GAAiB;IAC5D,OAAO,IAAI,OAAO,CAEhB,CAAC,OAAO,EAAE,EAAE;QACZ,IAAI,MAAM,IAAI,KAAK,EAAE;YACnB,yBAAyB;YACzB,OAAO,CAAC;gBACN,EAAE,EAAE,IAAI;gBACR,IAAI,EAAE,SAAS;aAChB,CAAC,CAAC;SACJ;QAED,IAAI,MAAc,CAAC;QACnB,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE;YACxB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAE9B,IAAI,MAAM,EAAE;gBACV,IAAI,MAAM,EAAE;oBACV,sCAAsC;oBACtC,OAAO,CAAC;wBACN,EAAE,EAAE,IAAI;wBACR,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,kBAAkB;qBAC5C,CAAC,CAAC;iBACJ;qBAAM;oBACL,mCAAmC;oBACnC,OAAO,CAAC;wBACN,EAAE,EAAE,IAAI;wBACR,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE;qBACvB,CAAC,CAAC;iBACJ;aACF;iBAAM;gBACL,IAAI,MAAM,EAAE;oBACV,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;iBACzC;qBAAM;oBACL,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;iBACjC;aACF;QACH,CAAC,CAAC,CAAC;QAEH,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;YACjB,OAAO,CAAC;gBACN,EAAE,EAAE,KAAK;gBACT,KAAK,EAAE,IAAI,SAAS,CAAC,EAAE,IAAI,EAAE,uBAAuB,EAAE,CAAC;aACxD,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "private": false,
3
+ "name": "trpc-uwebsockets",
4
+ "description": "uWebSockets adapter for tRPC",
5
+ "version": "0.8.0",
6
+ "module": "./dist/index.js",
7
+ "types": "./types/index.d.ts",
8
+ "scripts": {
9
+ "start": "jest --watch",
10
+ "build": "tsc",
11
+ "build:watch": "tsc --watch",
12
+ "test": "jest",
13
+ "test:watch": "jest --watch",
14
+ "test:coverage": "jest --coverage",
15
+ "test:publish": "yarn test && yarn build && yarn pack",
16
+ "prebuild": "yarn clean",
17
+ "prepublishOnly": "yarn prettier && yarn lint && yarn build",
18
+ "clean": "rimraf -rf ./dist && rimraf -rf ./types && rimraf -rf ./*-*.tgz",
19
+ "format": "yarn prettier && yarn lint",
20
+ "lint": "eslint . --ext .ts --fix",
21
+ "lint:dry": "eslint . --ext .ts",
22
+ "prettier": "prettier --config .prettierrc 'src/**/*.ts' --write",
23
+ "prettier:dry": "prettier --config .prettierrc 'src/**/*.ts'"
24
+ },
25
+ "dependencies": {
26
+ "@trpc/server": "^9.26.2",
27
+ "uWebSockets.js": "uNetworking/uWebSockets.js#v20.10.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/jest": "^28.1.6",
31
+ "babel-jest": "^28.1.3",
32
+ "jest": "^28.1.3",
33
+ "node-fetch": "2",
34
+ "@rollup/plugin-typescript": "^8.3.3",
35
+ "@swc/core": "^1.2.215",
36
+ "@swc/jest": "^0.2.21",
37
+ "@trpc/client": "^9.26.2",
38
+ "@types/node": "^18.0.6",
39
+ "@types/webrtc": "^0.0.32",
40
+ "@typescript-eslint/eslint-plugin": "^5.30.6",
41
+ "@typescript-eslint/parser": "^5.30.6",
42
+ "abort-controller": "^3.0.0",
43
+ "eslint": "^8.19.0",
44
+ "eslint-config-prettier": "^8.5.0",
45
+ "eslint-plugin-jest": "^26.6.0",
46
+ "eslint-plugin-prettier": "^4.2.1",
47
+ "jest-environment-jsdom": "^27.1.0",
48
+ "jest-environment-node": "^28.1.3",
49
+ "prettier": "^2.7.1",
50
+ "rimraf": "^3.0.2",
51
+ "rollup": "^2.77.0",
52
+ "rollup-plugin-swc": "^0.2.1",
53
+ "ts-jest": "^28.0.7",
54
+ "ts-node": "^10.9.1",
55
+ "typescript": "^4.4.4",
56
+ "zod": "^3.17.9"
57
+ },
58
+ "files": [
59
+ "dist",
60
+ "src",
61
+ "types",
62
+ "test"
63
+ ],
64
+ "license": "MIT",
65
+ "keywords": [],
66
+ "repository": {
67
+ "type": "git",
68
+ "url": "https://github.com/romanzy-1612/trpc-uwebsockets.git"
69
+ },
70
+ "author": "Roman Volovoy"
71
+ }
package/src/index.ts ADDED
@@ -0,0 +1,118 @@
1
+ import {
2
+ AnyRouter,
3
+ inferRouterContext,
4
+ resolveHTTPResponse,
5
+ } from '@trpc/server';
6
+ import { HTTPRequest } from '@trpc/server/dist/declarations/src/http/internals/types';
7
+ import type * as uWs from 'uWebSockets.js';
8
+ import {
9
+ UWebSocketsRegisterEndpointOptions,
10
+ UWebSocketsRequestObject,
11
+ } from './types';
12
+ import { readPostBody } from './utils';
13
+ export * from './types';
14
+
15
+ /**
16
+ *
17
+ * @param uWsApp uWebsockets server instance
18
+ * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
19
+ * @param opts router and createContext functions
20
+ */
21
+ export function createUWebSocketsHandler<TRouter extends AnyRouter>(
22
+ uWsApp: uWs.TemplatedApp,
23
+ pathPrefix: string,
24
+ opts: UWebSocketsRegisterEndpointOptions<TRouter>
25
+ ) {
26
+ const prefixTrimLength = pathPrefix.length + 1; // remove /* from url
27
+
28
+ const handler = async (res: uWs.HttpResponse, req: uWs.HttpRequest) => {
29
+ const method = req.getMethod().toUpperCase();
30
+ if (method !== 'GET' && method !== 'POST') {
31
+ // handle only get and post requests, while the rest
32
+ // will not be captured and propagated further
33
+ req.setYield(true);
34
+ return;
35
+ }
36
+ const path = req.getUrl().substring(prefixTrimLength);
37
+ const query = new URLSearchParams(decodeURIComponent(req.getQuery()));
38
+
39
+ const headers: Record<string, string> = {};
40
+ req.forEach((key, value) => {
41
+ headers[key] = value;
42
+ });
43
+
44
+ // new request object needs to be created, because socket
45
+ // can only be accessed synchronously, after await it cannot be accessed
46
+ const requestObj: UWebSocketsRequestObject = {
47
+ headers,
48
+ method,
49
+ query,
50
+ path,
51
+ };
52
+
53
+ const bodyResult = await readPostBody(method, res);
54
+
55
+ // req is no longer available!
56
+
57
+ const createContext = async function _(): Promise<
58
+ inferRouterContext<TRouter>
59
+ > {
60
+ //res could be proxied here
61
+ return await opts.createContext?.({
62
+ // res,
63
+ req: requestObj,
64
+ });
65
+ };
66
+
67
+ const fakeReqObject: HTTPRequest = {
68
+ method,
69
+ headers,
70
+ query,
71
+ body: bodyResult.ok ? bodyResult.data : undefined,
72
+ };
73
+
74
+ // TODO batching, onError options need implementation.
75
+ // responseMeta is not applicable?
76
+ const result = await resolveHTTPResponse({
77
+ path,
78
+ createContext,
79
+ router: opts.router,
80
+ req: fakeReqObject,
81
+ error: bodyResult.ok ? null : bodyResult.error,
82
+ });
83
+
84
+ if ('status' in result) {
85
+ res.writeStatus(result.status.toString()); //temp
86
+ } else {
87
+ // assume something went bad, should never happen?
88
+ // there is no way to know from res object that something was send to the socket
89
+ // can proxy it to detect res calls during createContext and resolve
90
+ // then will need to exit from here
91
+
92
+ res.cork(() => {
93
+ res.writeStatus('500 INTERNAL SERVER ERROR');
94
+ res.end();
95
+ });
96
+ return;
97
+ }
98
+
99
+ for (const [key, value] of Object.entries(result.headers ?? {})) {
100
+ if (typeof value === 'undefined') {
101
+ continue;
102
+ }
103
+ // FIX not sure why it could be an array. This code path is not tested
104
+ if (Array.isArray(value))
105
+ value.forEach((header) => {
106
+ res.writeHeader(key, header);
107
+ });
108
+ else res.writeHeader(key, value);
109
+ }
110
+
111
+ res.cork(() => {
112
+ if (result.body) res.write(result.body);
113
+ res.end();
114
+ });
115
+ };
116
+
117
+ uWsApp.any(pathPrefix + '/*', handler);
118
+ }
package/src/types.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { AnyRouter, inferRouterContext } from '@trpc/server';
2
+ import { HttpResponse } from 'uWebSockets.js';
3
+
4
+ export type UWebSocketsRegisterEndpointOptions<TRouter extends AnyRouter> = {
5
+ router: TRouter;
6
+ createContext?: (
7
+ opts: UWebSocketsCreateContextOptions
8
+ ) => Promise<inferRouterContext<TRouter>> | inferRouterContext<TRouter>;
9
+ };
10
+
11
+ export type UWebSocketsRequestObject = {
12
+ headers: Record<string, string>;
13
+ method: 'POST' | 'GET';
14
+ query: URLSearchParams;
15
+ path: string;
16
+ };
17
+
18
+ // if this to be used, it needs to be proxied
19
+ export type UWebSocketsResponseObject = HttpResponse;
20
+
21
+ export type UWebSocketsCreateContextOptions = {
22
+ req: UWebSocketsRequestObject;
23
+ // res: UWebSocketsResponseObject;
24
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { TRPCError } from '@trpc/server';
2
+ import { HttpResponse } from 'uWebSockets.js';
3
+
4
+ export function readPostBody(method: string, res: HttpResponse) {
5
+ return new Promise<
6
+ { ok: true; data: unknown } | { ok: false; error: TRPCError }
7
+ >((resolve) => {
8
+ if (method == 'GET') {
9
+ // no body in get request
10
+ resolve({
11
+ ok: true,
12
+ data: undefined,
13
+ });
14
+ }
15
+
16
+ let buffer: Buffer;
17
+ res.onData((ab, isLast) => {
18
+ const chunk = Buffer.from(ab);
19
+
20
+ if (isLast) {
21
+ if (buffer) {
22
+ // large request, with multiple chunks
23
+ resolve({
24
+ ok: true,
25
+ data: buffer.toString(), // do i need utf8?
26
+ });
27
+ } else {
28
+ // only a single chunk was recieved
29
+ resolve({
30
+ ok: true,
31
+ data: chunk.toString(),
32
+ });
33
+ }
34
+ } else {
35
+ if (buffer) {
36
+ buffer = Buffer.concat([buffer, chunk]);
37
+ } else {
38
+ buffer = Buffer.concat([chunk]);
39
+ }
40
+ }
41
+ });
42
+
43
+ res.onAborted(() => {
44
+ resolve({
45
+ ok: false,
46
+ error: new TRPCError({ code: 'CLIENT_CLOSED_REQUEST' }),
47
+ });
48
+ });
49
+ });
50
+ }
@@ -0,0 +1,171 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import AbortController from 'abort-controller';
3
+ import fetch from 'node-fetch';
4
+ import { z } from 'zod';
5
+ import { UWebSocketsCreateContextOptions } from '../src/types';
6
+ import uWs from 'uWebSockets.js';
7
+
8
+ import * as trpc from '@trpc/server';
9
+ import { TRPCError } from '@trpc/server';
10
+ import { createUWebSocketsHandler } from '../src/index';
11
+ import { createTRPCClient } from '@trpc/client';
12
+
13
+ const testPort = 8732;
14
+
15
+ type Context = {
16
+ user: {
17
+ name: string;
18
+ } | null;
19
+ };
20
+ async function startServer() {
21
+ const createContext = (_opts: UWebSocketsCreateContextOptions): Context => {
22
+ const getUser = () => {
23
+ if (_opts.req.headers.authorization === 'meow') {
24
+ return {
25
+ name: 'KATT',
26
+ };
27
+ }
28
+ return null;
29
+ };
30
+
31
+ return {
32
+ user: getUser(),
33
+ };
34
+ };
35
+
36
+ const router = trpc
37
+ .router<Context>()
38
+ .query('hello', {
39
+ input: z
40
+ .object({
41
+ who: z.string().nullish(),
42
+ })
43
+ .nullish(),
44
+ resolve({ input, ctx }) {
45
+ return {
46
+ text: `hello ${input?.who ?? ctx.user?.name ?? 'world'}`,
47
+ };
48
+ },
49
+ })
50
+ .query('error', {
51
+ resolve() {
52
+ throw new TRPCError({
53
+ code: 'BAD_REQUEST',
54
+ message: 'error as expected',
55
+ });
56
+ },
57
+ })
58
+ .mutation('test', {
59
+ input: z.object({
60
+ value: z.string(),
61
+ }),
62
+ resolve({ input, ctx }) {
63
+ return {
64
+ originalValue: input.value,
65
+ user: ctx.user,
66
+ };
67
+ },
68
+ });
69
+
70
+ const app = uWs.App();
71
+
72
+ // Handle CORS
73
+ app.options('/trpc/*', (res) => {
74
+ res.writeHeader('Access-Control-Allow-Origin', '*');
75
+ res.writeStatus('200 OK');
76
+ res.end();
77
+ });
78
+
79
+ // need to register everything on the app object,
80
+ // as uWebSockets does not have middleware
81
+ createUWebSocketsHandler(app, '/trpc', {
82
+ router,
83
+ createContext,
84
+ });
85
+
86
+ const { server, socket } = await new Promise<{
87
+ server: uWs.TemplatedApp;
88
+ socket: uWs.us_listen_socket;
89
+ }>((resolve) => {
90
+ app.listen('0.0.0.0', testPort, (socket) => {
91
+ resolve({
92
+ server: app,
93
+ socket,
94
+ });
95
+ });
96
+ });
97
+
98
+ const client = createTRPCClient<typeof router>({
99
+ url: `http://localhost:${testPort}/trpc`,
100
+
101
+ AbortController: AbortController as any,
102
+ fetch: fetch as any,
103
+ headers: {
104
+ authorization: 'meow',
105
+ },
106
+ });
107
+
108
+ return {
109
+ close: () =>
110
+ new Promise<void>((resolve, reject) => {
111
+ try {
112
+ uWs.us_listen_socket_close(socket);
113
+ } catch (error) {
114
+ reject();
115
+ }
116
+ resolve();
117
+ }),
118
+ router,
119
+ client,
120
+ };
121
+ }
122
+
123
+ let t: trpc.inferAsyncReturnType<typeof startServer>;
124
+ beforeEach(async () => {
125
+ t = await startServer();
126
+ });
127
+ afterEach(async () => {
128
+ await t.close();
129
+ });
130
+
131
+ test('simple query', async () => {
132
+ expect(
133
+ await t.client.query('hello', {
134
+ who: 'test',
135
+ })
136
+ ).toMatchInlineSnapshot(`
137
+ Object {
138
+ "text": "hello test",
139
+ }
140
+ `);
141
+
142
+ // t.client.runtime.headers()
143
+
144
+ expect(await t.client.query('hello')).toMatchInlineSnapshot(`
145
+ Object {
146
+ "text": "hello KATT",
147
+ }
148
+ `);
149
+ });
150
+
151
+ // Error status codes are correct
152
+ test('error handling', async () => {
153
+ expect(t.client.query('error', null)).rejects.toThrowError(
154
+ 'error as expected'
155
+ );
156
+ });
157
+
158
+ test('simple mutation', async () => {
159
+ expect(
160
+ await t.client.mutation('test', {
161
+ value: 'lala',
162
+ })
163
+ ).toMatchInlineSnapshot(`
164
+ Object {
165
+ "originalValue": "lala",
166
+ "user": Object {
167
+ "name": "KATT",
168
+ },
169
+ }
170
+ `);
171
+ });
@@ -0,0 +1,11 @@
1
+ import { AnyRouter } from '@trpc/server';
2
+ import type * as uWs from 'uWebSockets.js';
3
+ import { UWebSocketsRegisterEndpointOptions } from './types';
4
+ export * from './types';
5
+ /**
6
+ *
7
+ * @param uWsApp uWebsockets server instance
8
+ * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
9
+ * @param opts router and createContext functions
10
+ */
11
+ export declare function createUWebSocketsHandler<TRouter extends AnyRouter>(uWsApp: uWs.TemplatedApp, pathPrefix: string, opts: UWebSocketsRegisterEndpointOptions<TRouter>): void;
@@ -0,0 +1,16 @@
1
+ import { AnyRouter, inferRouterContext } from '@trpc/server';
2
+ import { HttpResponse } from 'uWebSockets.js';
3
+ export declare type UWebSocketsRegisterEndpointOptions<TRouter extends AnyRouter> = {
4
+ router: TRouter;
5
+ createContext?: (opts: UWebSocketsCreateContextOptions) => Promise<inferRouterContext<TRouter>> | inferRouterContext<TRouter>;
6
+ };
7
+ export declare type UWebSocketsRequestObject = {
8
+ headers: Record<string, string>;
9
+ method: 'POST' | 'GET';
10
+ query: URLSearchParams;
11
+ path: string;
12
+ };
13
+ export declare type UWebSocketsResponseObject = HttpResponse;
14
+ export declare type UWebSocketsCreateContextOptions = {
15
+ req: UWebSocketsRequestObject;
16
+ };
@@ -0,0 +1,9 @@
1
+ import { TRPCError } from '@trpc/server';
2
+ import { HttpResponse } from 'uWebSockets.js';
3
+ export declare function readPostBody(method: string, res: HttpResponse): Promise<{
4
+ ok: true;
5
+ data: unknown;
6
+ } | {
7
+ ok: false;
8
+ error: TRPCError;
9
+ }>;