trpc-uwebsockets 0.8.2 → 0.9.1

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 CHANGED
@@ -15,6 +15,7 @@ Import needed packages
15
15
  ```typescript
16
16
  import { App } from 'uWebSockets.js';
17
17
  import * as trpc from '@trpc/server';
18
+ import z from 'zod';
18
19
  ```
19
20
 
20
21
  Define tRPC context and router
@@ -26,12 +27,11 @@ type Context = {
26
27
  } | null;
27
28
  };
28
29
 
29
- const createContext: any = (opts: UWebSocketsContextOptions): Context => {
30
+ const createContext = (opts: UWebSocketsContextOptions): Context => {
30
31
  const getUser = () => {
31
- if (opts.req.headers.authorization === 'meow') {
32
- return {
33
- name: 'KATT',
34
- };
32
+ if (opts?.req.headers.authorization) {
33
+ // const user = await decodeJwtToken(req.headers.authorization.split(' ')[1])
34
+ // return user;
35
35
  }
36
36
  return null;
37
37
  };
@@ -55,7 +55,7 @@ const router = trpc.router<Context>().query('hello', {
55
55
  });
56
56
  ```
57
57
 
58
- Initialize uWebsockets server and attach tTRP router
58
+ Initialize uWebsockets server and attach tRPC router
59
59
 
60
60
  ```typescript
61
61
  const app = App();
@@ -65,11 +65,42 @@ createUWebSocketsHandler(app, '/trpc', {
65
65
  createContext,
66
66
  });
67
67
 
68
+ /* dont crash on unknown request */
69
+ app.any('/*', (res) => {
70
+ res.writeStatus('404 NOT FOUND');
71
+ res.end();
72
+ });
73
+
68
74
  app.listen('0.0.0.0', 8000, () => {
69
- console.log('server listening on http://localhost:8000');
75
+ console.log('Server listening on http://localhost:8000');
70
76
  });
71
77
  ```
72
78
 
79
+ # API
80
+
81
+ Create context options
82
+
83
+ ```typescript
84
+ type UWebSocketsCreateContextOptions = {
85
+ /* read-only request information */
86
+ req: {
87
+ headers: Record<string, string>;
88
+ method: 'POST' | 'GET';
89
+ query: URLSearchParams;
90
+ path: string;
91
+ getCookies: (opts?: CookieParseOptions) => Record<string, string>;
92
+ };
93
+ /* */
94
+ res: {
95
+ setStatus(status: number): void;
96
+ setHeader(key: string, value: string): void;
97
+ setCookie(key: string, value: string, opts?: CookieSerializeOptions): void;
98
+ };
99
+ /* instance of the uWebSockets server */
100
+ uWs: TemplatedApp;
101
+ };
102
+ ```
103
+
73
104
  # Testing
74
105
 
75
106
  ```bash
@@ -81,3 +112,8 @@ or
81
112
  ```bash
82
113
  yarn test:watch
83
114
  ```
115
+
116
+ # Todo
117
+
118
+ - [ ] Expose batching options (like express adapter)
119
+ - [ ] Implement onError handling (like express adapter)
package/dist/index.js CHANGED
@@ -13,16 +13,20 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
13
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
16
19
  Object.defineProperty(exports, "__esModule", { value: true });
17
20
  exports.createUWebSocketsHandler = void 0;
18
21
  const server_1 = require("@trpc/server");
19
22
  const utils_1 = require("./utils");
23
+ const cookie_1 = __importDefault(require("cookie"));
20
24
  __exportStar(require("./types"), exports);
21
25
  /**
22
26
  *
23
27
  * @param uWsApp uWebsockets server instance
24
28
  * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
25
- * @param opts router and createContext functions
29
+ * @param opts router and createContext options
26
30
  */
27
31
  function createUWebSocketsHandler(uWsApp, pathPrefix, opts) {
28
32
  const prefixTrimLength = pathPrefix.length + 1; // remove /* from url
@@ -42,63 +46,94 @@ function createUWebSocketsHandler(uWsApp, pathPrefix, opts) {
42
46
  });
43
47
  // new request object needs to be created, because socket
44
48
  // can only be accessed synchronously, after await it cannot be accessed
45
- const requestObj = {
49
+ const request = {
46
50
  headers,
47
51
  method,
48
52
  query,
49
53
  path,
54
+ getCookies: (0, utils_1.getCookieFn)(headers),
55
+ };
56
+ const resOverride = {
57
+ headers: new Map(),
58
+ cookies: [],
59
+ status: 0,
60
+ };
61
+ const response = {
62
+ setCookie: (name, value, opts) => {
63
+ const serialized = cookie_1.default.serialize(name, value, opts); //.substring(12); //remove the "Set-Cookie: "
64
+ resOverride.cookies.push(serialized);
65
+ },
66
+ setStatus: (status) => {
67
+ resOverride.status = status;
68
+ },
69
+ setHeader: (key, value) => {
70
+ resOverride.headers.set(key, value);
71
+ },
50
72
  };
51
73
  const bodyResult = await (0, utils_1.readPostBody)(method, res);
52
74
  // req is no longer available!
53
75
  const createContext = async function _() {
54
76
  //res could be proxied here
55
77
  return await opts.createContext?.({
56
- // res,
57
- req: requestObj,
78
+ uWs: uWsApp,
79
+ req: request,
80
+ res: response,
58
81
  });
59
82
  };
60
- const fakeReqObject = {
83
+ const internalReqObj = {
61
84
  method,
62
85
  headers,
63
86
  query,
64
87
  body: bodyResult.ok ? bodyResult.data : undefined,
65
88
  };
66
89
  // TODO batching, onError options need implementation.
67
- // responseMeta is not applicable?
68
90
  const result = await (0, server_1.resolveHTTPResponse)({
69
91
  path,
70
92
  createContext,
71
93
  router: opts.router,
72
- req: fakeReqObject,
94
+ req: internalReqObj,
73
95
  error: bodyResult.ok ? null : bodyResult.error,
74
96
  });
75
- if ('status' in result) {
76
- res.writeStatus(result.status.toString()); //temp
77
- }
78
- else {
79
- // assume something went bad, should never happen?
80
- // there is no way to know from res object that something was send to the socket
81
- // can proxy it to detect res calls during createContext and resolve
82
- // then will need to exit from here
83
- res.cork(() => {
84
- res.writeStatus('500 INTERNAL SERVER ERROR');
85
- res.end();
86
- });
87
- return;
88
- }
89
- for (const [key, value] of Object.entries(result.headers ?? {})) {
90
- if (typeof value === 'undefined') {
91
- continue;
97
+ // user returned already, do nothing
98
+ res.cork(() => {
99
+ if (resOverride.status != 0) {
100
+ res.writeStatus(resOverride.status.toString());
92
101
  }
93
- // FIX not sure why it could be an array. This code path is not tested
94
- if (Array.isArray(value))
95
- value.forEach((header) => {
96
- res.writeHeader(key, header);
97
- });
98
- else
102
+ else if ('status' in result) {
103
+ res.writeStatus(result.status.toString());
104
+ }
105
+ else {
106
+ // assume something went bad, should never happen?
107
+ throw new Error('No status to send');
108
+ // res.writeStatus('500 INTERNAL SERVER ERROR');
109
+ // res.end();
110
+ // return;
111
+ }
112
+ //send all cookies
113
+ resOverride.cookies.forEach((value) => {
114
+ res.writeHeader('Set-Cookie', value);
115
+ });
116
+ resOverride.headers.forEach((value, key) => {
99
117
  res.writeHeader(key, value);
100
- }
101
- res.cork(() => {
118
+ });
119
+ for (const [key, value] of Object.entries(result.headers ?? {})) {
120
+ if (typeof value === 'undefined') {
121
+ continue;
122
+ }
123
+ // make sure to never override user defined headers
124
+ // cookies are an exception
125
+ if (resOverride.headers.has(key))
126
+ continue;
127
+ // not sure why it could be an array. This code path is not tested
128
+ // maybe its duplicates for the same key? like multiple "Set-Cookie"
129
+ if (Array.isArray(value))
130
+ value.forEach((header) => {
131
+ res.writeHeader(key, header);
132
+ });
133
+ else
134
+ res.writeHeader(key, value);
135
+ }
136
+ //now send user headers
102
137
  if (result.body)
103
138
  res.write(result.body);
104
139
  res.end();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,yCAIsB;AAOtB,mCAAuC;AACvC,0CAAwB;AAExB;;;;;GAKG;AACH,SAAgB,wBAAwB,CACtC,MAAwB,EACxB,UAAkB,EAClB,IAAiD;IAEjD,MAAM,gBAAgB,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,qBAAqB;IAErE,MAAM,OAAO,GAAG,KAAK,EAAE,GAAqB,EAAE,GAAoB,EAAE,EAAE;QACpE,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,EAAE,CAAC,WAAW,EAAE,CAAC;QAC7C,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM,EAAE;YACzC,o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MAAM,CAAC,CAAC;oBAC/B,CAAC,CAAC,CAAC;;oBACA,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;aAClC;YAED,uBAAuB;YACvB,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;AAvID,4DAuIC"}
package/dist/utils.js CHANGED
@@ -1,7 +1,20 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readPostBody = void 0;
6
+ exports.readPostBody = exports.getCookieFn = void 0;
4
7
  const server_1 = require("@trpc/server");
8
+ const cookie_1 = __importDefault(require("cookie"));
9
+ /*
10
+ cookie: 'cookie1=abc; cookie2=d.e'
11
+ */
12
+ const getCookieFn = (headers) => (opts) => {
13
+ if (!('cookie' in headers))
14
+ return {};
15
+ return cookie_1.default.parse(headers.cookie, opts);
16
+ };
17
+ exports.getCookieFn = getCookieFn;
5
18
  function readPostBody(method, res) {
6
19
  return new Promise((resolve) => {
7
20
  if (method == 'GET') {
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AAGzC,SAAgB,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,EAA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EAAE,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE,uBAAuB,EAAE,CAAC;aACxD,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AA9CD,oCA8CC"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "trpc-uwebsockets",
4
- "description": "uWebSockets adapter for tRPC",
5
- "version": "0.8.2",
4
+ "description": "tRPC adapter for uWebSockets.js server",
5
+ "version": "0.9.1",
6
6
  "main": "./dist/index.js",
7
7
  "type": "commonjs",
8
8
  "types": "./types/index.d.ts",
@@ -25,28 +25,30 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@trpc/server": "^9.26.2",
28
+ "cookie": "^0.5.0",
28
29
  "uWebSockets.js": "uNetworking/uWebSockets.js#v20.10.0"
29
30
  },
30
31
  "devDependencies": {
31
- "@types/jest": "^28.1.6",
32
- "babel-jest": "^28.1.3",
33
- "jest": "^28.1.3",
34
- "node-fetch": "2",
35
32
  "@rollup/plugin-typescript": "^8.3.3",
36
33
  "@swc/core": "^1.2.215",
37
34
  "@swc/jest": "^0.2.21",
38
35
  "@trpc/client": "^9.26.2",
36
+ "@types/cookie": "^0.5.1",
37
+ "@types/jest": "^28.1.6",
39
38
  "@types/node": "^18.0.6",
40
39
  "@types/webrtc": "^0.0.32",
41
40
  "@typescript-eslint/eslint-plugin": "^5.30.6",
42
41
  "@typescript-eslint/parser": "^5.30.6",
43
42
  "abort-controller": "^3.0.0",
43
+ "babel-jest": "^28.1.3",
44
44
  "eslint": "^8.19.0",
45
45
  "eslint-config-prettier": "^8.5.0",
46
46
  "eslint-plugin-jest": "^26.6.0",
47
47
  "eslint-plugin-prettier": "^4.2.1",
48
+ "jest": "^28.1.3",
48
49
  "jest-environment-jsdom": "^27.1.0",
49
50
  "jest-environment-node": "^28.1.3",
51
+ "node-fetch": "2",
50
52
  "prettier": "^2.7.1",
51
53
  "rimraf": "^3.0.2",
52
54
  "rollup": "^2.77.0",
package/src/index.ts CHANGED
@@ -4,28 +4,36 @@ import {
4
4
  resolveHTTPResponse,
5
5
  } from '@trpc/server';
6
6
  import { HTTPRequest } from '@trpc/server/dist/declarations/src/http/internals/types';
7
- import type * as uWs from 'uWebSockets.js';
7
+ import { CookieParseOptions, CookieSerializeOptions } from 'cookie';
8
+ import type {
9
+ HttpRequest,
10
+ HttpResponse,
11
+ RecognizedString,
12
+ TemplatedApp,
13
+ } from 'uWebSockets.js';
8
14
  import {
9
- UWebSocketsRegisterEndpointOptions,
15
+ UWebSocketsRegisterEndpointOptions as UWebSocketsCreateHandlerOptions,
10
16
  UWebSocketsRequestObject,
17
+ UWebSocketsResponseObject,
11
18
  } from './types';
12
- import { readPostBody } from './utils';
19
+ import { getCookieFn, readPostBody } from './utils';
20
+ import cookie from 'cookie';
13
21
  export * from './types';
14
22
 
15
23
  /**
16
24
  *
17
25
  * @param uWsApp uWebsockets server instance
18
26
  * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
19
- * @param opts router and createContext functions
27
+ * @param opts router and createContext options
20
28
  */
21
29
  export function createUWebSocketsHandler<TRouter extends AnyRouter>(
22
- uWsApp: uWs.TemplatedApp,
30
+ uWsApp: TemplatedApp,
23
31
  pathPrefix: string,
24
- opts: UWebSocketsRegisterEndpointOptions<TRouter>
32
+ opts: UWebSocketsCreateHandlerOptions<TRouter>
25
33
  ) {
26
34
  const prefixTrimLength = pathPrefix.length + 1; // remove /* from url
27
35
 
28
- const handler = async (res: uWs.HttpResponse, req: uWs.HttpRequest) => {
36
+ const handler = async (res: HttpResponse, req: HttpRequest) => {
29
37
  const method = req.getMethod().toUpperCase();
30
38
  if (method !== 'GET' && method !== 'POST') {
31
39
  // handle only get and post requests, while the rest
@@ -43,11 +51,35 @@ export function createUWebSocketsHandler<TRouter extends AnyRouter>(
43
51
 
44
52
  // new request object needs to be created, because socket
45
53
  // can only be accessed synchronously, after await it cannot be accessed
46
- const requestObj: UWebSocketsRequestObject = {
54
+ const request: UWebSocketsRequestObject = {
47
55
  headers,
48
56
  method,
49
57
  query,
50
58
  path,
59
+ getCookies: getCookieFn(headers),
60
+ };
61
+
62
+ const resOverride = {
63
+ headers: new Map<string, string>(),
64
+ cookies: [] as string[],
65
+ status: 0,
66
+ };
67
+
68
+ const response: UWebSocketsResponseObject = {
69
+ setCookie: (
70
+ name: string,
71
+ value: string,
72
+ opts?: CookieSerializeOptions
73
+ ) => {
74
+ const serialized = cookie.serialize(name, value, opts); //.substring(12); //remove the "Set-Cookie: "
75
+ resOverride.cookies.push(serialized);
76
+ },
77
+ setStatus: (status: number) => {
78
+ resOverride.status = status;
79
+ },
80
+ setHeader: (key: string, value: string) => {
81
+ resOverride.headers.set(key, value);
82
+ },
51
83
  };
52
84
 
53
85
  const bodyResult = await readPostBody(method, res);
@@ -59,12 +91,13 @@ export function createUWebSocketsHandler<TRouter extends AnyRouter>(
59
91
  > {
60
92
  //res could be proxied here
61
93
  return await opts.createContext?.({
62
- // res,
63
- req: requestObj,
94
+ uWs: uWsApp,
95
+ req: request,
96
+ res: response,
64
97
  });
65
98
  };
66
99
 
67
- const fakeReqObject: HTTPRequest = {
100
+ const internalReqObj: HTTPRequest = {
68
101
  method,
69
102
  headers,
70
103
  query,
@@ -72,43 +105,56 @@ export function createUWebSocketsHandler<TRouter extends AnyRouter>(
72
105
  };
73
106
 
74
107
  // TODO batching, onError options need implementation.
75
- // responseMeta is not applicable?
76
108
  const result = await resolveHTTPResponse({
77
109
  path,
78
110
  createContext,
79
111
  router: opts.router,
80
- req: fakeReqObject,
112
+ req: internalReqObj,
81
113
  error: bodyResult.ok ? null : bodyResult.error,
82
114
  });
83
115
 
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();
116
+ // user returned already, do nothing
117
+ res.cork(() => {
118
+ if (resOverride.status != 0) {
119
+ res.writeStatus(resOverride.status.toString());
120
+ } else if ('status' in result) {
121
+ res.writeStatus(result.status.toString());
122
+ } else {
123
+ // assume something went bad, should never happen?
124
+ throw new Error('No status to send');
125
+
126
+ // res.writeStatus('500 INTERNAL SERVER ERROR');
127
+ // res.end();
128
+ // return;
129
+ }
130
+
131
+ //send all cookies
132
+ resOverride.cookies.forEach((value) => {
133
+ res.writeHeader('Set-Cookie', value);
134
+ });
135
+
136
+ resOverride.headers.forEach((value, key) => {
137
+ res.writeHeader(key, value);
95
138
  });
96
- return;
97
- }
98
139
 
99
- for (const [key, value] of Object.entries(result.headers ?? {})) {
100
- if (typeof value === 'undefined') {
101
- continue;
140
+ for (const [key, value] of Object.entries(result.headers ?? {})) {
141
+ if (typeof value === 'undefined') {
142
+ continue;
143
+ }
144
+ // make sure to never override user defined headers
145
+ // cookies are an exception
146
+ if (resOverride.headers.has(key)) continue;
147
+
148
+ // not sure why it could be an array. This code path is not tested
149
+ // maybe its duplicates for the same key? like multiple "Set-Cookie"
150
+ if (Array.isArray(value))
151
+ value.forEach((header) => {
152
+ res.writeHeader(key, header);
153
+ });
154
+ else res.writeHeader(key, value);
102
155
  }
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
156
 
111
- res.cork(() => {
157
+ //now send user headers
112
158
  if (result.body) res.write(result.body);
113
159
  res.end();
114
160
  });
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AnyRouter, inferRouterContext } from '@trpc/server';
2
- import { HttpResponse } from 'uWebSockets.js';
3
-
2
+ import { TemplatedApp } from 'uWebSockets.js';
3
+ import { CookieParseOptions, CookieSerializeOptions } from 'cookie';
4
4
  export type UWebSocketsRegisterEndpointOptions<TRouter extends AnyRouter> = {
5
5
  router: TRouter;
6
6
  createContext?: (
@@ -13,12 +13,18 @@ export type UWebSocketsRequestObject = {
13
13
  method: 'POST' | 'GET';
14
14
  query: URLSearchParams;
15
15
  path: string;
16
+ getCookies: (opts?: CookieParseOptions) => Record<string, string>;
16
17
  };
17
18
 
18
19
  // if this to be used, it needs to be proxied
19
- export type UWebSocketsResponseObject = HttpResponse;
20
+ export type UWebSocketsResponseObject = {
21
+ setCookie(key: string, value: string, opts?: CookieSerializeOptions): void;
22
+ setStatus(status: number): void;
23
+ setHeader(key: string, value: string): void;
24
+ };
20
25
 
21
26
  export type UWebSocketsCreateContextOptions = {
22
27
  req: UWebSocketsRequestObject;
23
- // res: UWebSocketsResponseObject;
28
+ uWs: TemplatedApp;
29
+ res: UWebSocketsResponseObject;
24
30
  };
package/src/utils.ts CHANGED
@@ -1,5 +1,16 @@
1
1
  import { TRPCError } from '@trpc/server';
2
2
  import { HttpResponse } from 'uWebSockets.js';
3
+ import cookie, { CookieParseOptions } from 'cookie';
4
+ /*
5
+ cookie: 'cookie1=abc; cookie2=d.e'
6
+ */
7
+
8
+ export const getCookieFn =
9
+ (headers: Record<string, string>) => (opts?: CookieParseOptions) => {
10
+ if (!('cookie' in headers)) return {};
11
+
12
+ return cookie.parse(headers.cookie, opts);
13
+ };
3
14
 
4
15
  export function readPostBody(method: string, res: HttpResponse) {
5
16
  return new Promise<
@@ -1,38 +1,17 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import AbortController from 'abort-controller';
3
3
  import fetch from 'node-fetch';
4
- import { z } from 'zod';
5
4
  import { UWebSocketsCreateContextOptions } from '../src/types';
6
5
  import uWs from 'uWebSockets.js';
7
-
6
+ import z from 'zod';
8
7
  import * as trpc from '@trpc/server';
9
- import { TRPCError } from '@trpc/server';
8
+ import { inferAsyncReturnType, TRPCError } from '@trpc/server';
10
9
  import { createUWebSocketsHandler } from '../src/index';
11
- import { createTRPCClient } from '@trpc/client';
10
+ import { createTRPCClient, HTTPHeaders } from '@trpc/client';
12
11
 
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
- };
12
+ const testPort = 8799;
35
13
 
14
+ function makeRouter() {
36
15
  const router = trpc
37
16
  .router<Context>()
38
17
  .query('hello', {
@@ -65,8 +44,58 @@ async function startServer() {
65
44
  user: ctx.user,
66
45
  };
67
46
  },
47
+ })
48
+ .query('cookie-monster', {
49
+ resolve({ input, ctx }) {
50
+ const cookies = ctx.req.getCookies();
51
+
52
+ const combined = cookies['cookie1'] + cookies['cookie2'];
53
+ ctx.res.setCookie('one', 'nom');
54
+ ctx.res.setCookie('two', 'nom nom');
55
+ ctx.res.setHeader('x-spooked', 'true');
56
+ ctx.res.setStatus(201);
57
+ return {
58
+ combined,
59
+ user: ctx.user,
60
+ };
61
+ },
68
62
  });
69
63
 
64
+ return router;
65
+ }
66
+ export type Router = ReturnType<typeof makeRouter>;
67
+
68
+ function makeContext() {
69
+ const createContext = ({
70
+ req,
71
+ res,
72
+ uWs,
73
+ }: UWebSocketsCreateContextOptions) => {
74
+ const getUser = () => {
75
+ if (req.headers.authorization === 'meow') {
76
+ return {
77
+ name: 'KATT',
78
+ };
79
+ }
80
+ if (req.getCookies()?.user === 'romanzy')
81
+ return {
82
+ name: 'romanzy',
83
+ };
84
+ return null;
85
+ };
86
+
87
+ return {
88
+ req,
89
+ res,
90
+ uWs,
91
+ user: getUser(),
92
+ };
93
+ };
94
+
95
+ return createContext;
96
+ }
97
+ export type Context = inferAsyncReturnType<ReturnType<typeof makeContext>>;
98
+ async function startServer() {
70
99
  const app = uWs.App();
71
100
 
72
101
  // Handle CORS
@@ -76,51 +105,63 @@ async function startServer() {
76
105
  res.end();
77
106
  });
78
107
 
108
+ app.get('/', (res) => {
109
+ res.writeStatus('200 OK');
110
+
111
+ res.end();
112
+ });
113
+
79
114
  // need to register everything on the app object,
80
115
  // as uWebSockets does not have middleware
81
116
  createUWebSocketsHandler(app, '/trpc', {
82
- router,
83
- createContext,
117
+ router: makeRouter(),
118
+ createContext: makeContext(),
119
+ });
120
+
121
+ app.put('/trpc/put', (res) => {
122
+ res.writeStatus('204');
123
+ res.end();
124
+ });
125
+
126
+ app.any('/*', (res) => {
127
+ res.writeStatus('404 NOT FOUND');
128
+ res.end();
84
129
  });
85
130
 
86
- const { server, socket } = await new Promise<{
87
- server: uWs.TemplatedApp;
131
+ const { socket } = await new Promise<{
88
132
  socket: uWs.us_listen_socket;
89
133
  }>((resolve) => {
90
134
  app.listen('0.0.0.0', testPort, (socket) => {
91
135
  resolve({
92
- server: app,
93
136
  socket,
94
137
  });
95
138
  });
96
139
  });
97
140
 
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
141
  return {
109
142
  close: () =>
110
143
  new Promise<void>((resolve, reject) => {
111
144
  try {
112
145
  uWs.us_listen_socket_close(socket);
146
+ resolve();
113
147
  } catch (error) {
114
148
  reject();
115
149
  }
116
- resolve();
117
150
  }),
118
- router,
119
- client,
120
151
  };
121
152
  }
122
153
 
123
- let t: trpc.inferAsyncReturnType<typeof startServer>;
154
+ function makeClient(headers) {
155
+ return createTRPCClient<Router>({
156
+ url: `http://localhost:${testPort}/trpc`,
157
+
158
+ AbortController: AbortController as any,
159
+ fetch: fetch as any,
160
+ headers,
161
+ });
162
+ }
163
+
164
+ let t!: trpc.inferAsyncReturnType<typeof startServer>;
124
165
  beforeEach(async () => {
125
166
  t = await startServer();
126
167
  });
@@ -129,8 +170,11 @@ afterEach(async () => {
129
170
  });
130
171
 
131
172
  test('simple query', async () => {
173
+ // t.client.runtime.headers = ()
174
+ const client = makeClient({});
175
+
132
176
  expect(
133
- await t.client.query('hello', {
177
+ await client.query('hello', {
134
178
  who: 'test',
135
179
  })
136
180
  ).toMatchInlineSnapshot(`
@@ -139,25 +183,16 @@ test('simple query', async () => {
139
183
  }
140
184
  `);
141
185
 
142
- // t.client.runtime.headers()
143
-
144
- expect(await t.client.query('hello')).toMatchInlineSnapshot(`
145
- Object {
146
- "text": "hello KATT",
147
- }
148
- `);
186
+ expect(client.query('error', null)).rejects.toThrowError('error as expected');
149
187
  });
150
188
 
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
- });
189
+ test('mutation with header', async () => {
190
+ const client = makeClient({
191
+ authorization: 'meow',
192
+ });
157
193
 
158
- test('simple mutation', async () => {
159
194
  expect(
160
- await t.client.mutation('test', {
195
+ await client.mutation('test', {
161
196
  value: 'lala',
162
197
  })
163
198
  ).toMatchInlineSnapshot(`
@@ -169,3 +204,55 @@ test('simple mutation', async () => {
169
204
  }
170
205
  `);
171
206
  });
207
+
208
+ // Error status codes are correct
209
+ test('reads cookies', async () => {
210
+ const client = makeClient({
211
+ cookie: 'cookie1=abc; cookie2=d.e; user=romanzy',
212
+ });
213
+
214
+ expect(await client.query('cookie-monster')).toMatchInlineSnapshot(`
215
+ Object {
216
+ "combined": "abcd.e",
217
+ "user": Object {
218
+ "name": "romanzy",
219
+ },
220
+ }
221
+ `);
222
+ });
223
+
224
+ test('setting cookies and headers', async () => {
225
+ const monsterRes = await fetch(
226
+ `http://localhost:${testPort}/trpc/cookie-monster`
227
+ );
228
+ expect(monsterRes.status).toEqual(201);
229
+ expect(monsterRes.headers.get('set-cookie')).toEqual(
230
+ 'one=nom, two=nom%20nom'
231
+ );
232
+ expect(monsterRes.headers.get('x-spooked')).toEqual('true');
233
+ });
234
+
235
+ test('error handling', async () => {
236
+ const indexRes = await fetch(`http://localhost:${testPort}`);
237
+ expect(indexRes.status).toEqual(200);
238
+
239
+ const putRes = await fetch(`http://localhost:${testPort}/trpc/put`, {
240
+ method: 'PUT',
241
+ });
242
+ expect(putRes.status).toEqual(204);
243
+
244
+ const badInput = '{"who": "test';
245
+ const badRes = await fetch(
246
+ `http://localhost:${testPort}/trpc/hello?input=${badInput}`
247
+ );
248
+ expect(badRes.status).toEqual(400);
249
+
250
+ const badPath = await fetch(
251
+ `http://localhost:${testPort}/trpc/nonexisting?input=${badInput}`
252
+ );
253
+ expect(badPath.status).toEqual(400);
254
+
255
+ const uncaught = await fetch(`http://localhost:${testPort}/badurl`);
256
+
257
+ expect(uncaught.status).toEqual(404);
258
+ });
package/types/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { AnyRouter } from '@trpc/server';
2
- import type * as uWs from 'uWebSockets.js';
3
- import { UWebSocketsRegisterEndpointOptions } from './types';
2
+ import type { TemplatedApp } from 'uWebSockets.js';
3
+ import { UWebSocketsRegisterEndpointOptions as UWebSocketsCreateHandlerOptions } from './types';
4
4
  export * from './types';
5
5
  /**
6
6
  *
7
7
  * @param uWsApp uWebsockets server instance
8
8
  * @param pathPrefix The path to endpoint without trailing slash (ex: "/trpc")
9
- * @param opts router and createContext functions
9
+ * @param opts router and createContext options
10
10
  */
11
- export declare function createUWebSocketsHandler<TRouter extends AnyRouter>(uWsApp: uWs.TemplatedApp, pathPrefix: string, opts: UWebSocketsRegisterEndpointOptions<TRouter>): void;
11
+ export declare function createUWebSocketsHandler<TRouter extends AnyRouter>(uWsApp: TemplatedApp, pathPrefix: string, opts: UWebSocketsCreateHandlerOptions<TRouter>): void;
package/types/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AnyRouter, inferRouterContext } from '@trpc/server';
2
- import { HttpResponse } from 'uWebSockets.js';
2
+ import { TemplatedApp } from 'uWebSockets.js';
3
+ import { CookieParseOptions, CookieSerializeOptions } from 'cookie';
3
4
  export declare type UWebSocketsRegisterEndpointOptions<TRouter extends AnyRouter> = {
4
5
  router: TRouter;
5
6
  createContext?: (opts: UWebSocketsCreateContextOptions) => Promise<inferRouterContext<TRouter>> | inferRouterContext<TRouter>;
@@ -9,8 +10,15 @@ export declare type UWebSocketsRequestObject = {
9
10
  method: 'POST' | 'GET';
10
11
  query: URLSearchParams;
11
12
  path: string;
13
+ getCookies: (opts?: CookieParseOptions) => Record<string, string>;
14
+ };
15
+ export declare type UWebSocketsResponseObject = {
16
+ setCookie(key: string, value: string, opts?: CookieSerializeOptions): void;
17
+ setStatus(status: number): void;
18
+ setHeader(key: string, value: string): void;
12
19
  };
13
- export declare type UWebSocketsResponseObject = HttpResponse;
14
20
  export declare type UWebSocketsCreateContextOptions = {
15
21
  req: UWebSocketsRequestObject;
22
+ uWs: TemplatedApp;
23
+ res: UWebSocketsResponseObject;
16
24
  };
package/types/utils.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { TRPCError } from '@trpc/server';
2
2
  import { HttpResponse } from 'uWebSockets.js';
3
+ import { CookieParseOptions } from 'cookie';
4
+ export declare const getCookieFn: (headers: Record<string, string>) => (opts?: CookieParseOptions) => Record<string, string>;
3
5
  export declare function readPostBody(method: string, res: HttpResponse): Promise<{
4
6
  ok: true;
5
7
  data: unknown;