diff --git a/README.md b/README.md
index 811b479..21148ad 100644
--- a/README.md
+++ b/README.md
@@ -2,17 +2,9 @@
This is an adapter which allows you to mount tRPC onto a Koa server. This is similar to the [trpc/packages/server/src/adapters/express.ts](https://github.com/trpc/trpc/blob/next/packages/server/src/adapters/express.ts) adapter.
-# How to add tRPC to a Koa server
+# How to Add tRPC to a Koa Server
-Initialize a tRPC router and pass into `createKoaMiddleware` with the following parameters:
-
-- router (required): the trpc router
-- createContext (optional): a function returning the trpc context. If defined, the type should be registered on trpc initialization as shown in an example below and the trpc docs: https://trpc.io/docs/context
-- prefix (optional): what to prefix the trpc routes with, such as `/trpc`
-
-In addition to these examples, see the implementations in [`./test/createKoaMiddleware`](https://github.com/BlairCurrey/trpc-koa-adapter/blob/master/test/createKoaMiddleware.test.ts).
-
-Example:
+Initialize a tRPC router and pass into `createKoaMiddleware` (along with other desired [options](#arguments)). Here is a minimal example:
```ts
import Koa from 'koa';
@@ -31,29 +23,46 @@ const trpcRouter = trpc.router({
.output(Object)
.query((req) => {
return ALL_USERS.find((user) => req.input === user.id);
- })
+ }),
});
const app = new Koa();
const adapter = createKoaMiddleware({
router: trpcRouter,
- prefix: '/trpc'
+ prefix: '/trpc',
});
app.use(adapter);
app.listen(4000);
```
You can now reach the endpoint with:
+
```sh
curl -X GET "http://localhost:4000/trpc/user?input=1" -H 'content-type: application/json'
```
-
-Returns:
+
+Returns:
+
```json
{ "id": 1, "name": "bob" }
```
-Using the context:
+# createKoaMiddleware Arguments
+
+The middleware takes a configuration object with the following properties:
+
+| Option | Required | Description |
+| -------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| router | Required | The tRPC router to mount |
+| createContext | Optional | A function returning the tRPC context. If defined, the type should be registered on tRPC initialization as shown in an example below and the tRPC docs: https://trpc.io/docs/context |
+| prefix | Optional | The prefix for tRPC routes, such as `/trpc` |
+| `nodeHTTPRequestHandler` options | Optional | Any of the options used by the underlying request handler. See tRPC's [nodeHTTPRequestHandler](https://github.com/trpc/trpc/blob/next/packages/server/src/adapters/node-http/nodeHTTPRequestHandler.ts) for more details |
+
+# More examples
+
+In addition to these examples, see the implementations in [`./test/createKoaMiddleware.test.ts`](https://github.com/BlairCurrey/trpc-koa-adapter/blob/master/test/createKoaMiddleware.test.ts).
+
+## Using the Context:
```ts
const createContext = async ({ req, res }: CreateTrpcKoaContextOptions) => {
@@ -80,7 +89,7 @@ const trpcRouter = trpc.router({
ALL_USERS.push(newUser);
return newUser;
- })
+ }),
});
const adapter = createKoaMiddleware({
@@ -90,6 +99,10 @@ const adapter = createKoaMiddleware({
});
```
+# Note About Using With a Body Parser:
+
+Using a bodyparser such as [`@koa/bodyparser`](https://github.com/koajs/bodyparser), [`koa-bodyparser`](https://www.npmjs.com/package/koa-bodyparser), or otherwise parsing the body will consume the data stream on the incoming request. To ensure that tRPC can handle the request, this library looks for the parsed body on `ctx.request.body`, which is where `@koa/bodyparser` and `koa-bodyparser` store the parsed body. If for some reason the parsed body is being stored somewhere else, and you need to parse the body before this middleware, the body will not be available to tRPC and mutations will fail as detailed [in this github issue](https://github.com/BlairCurrey/trpc-koa-adapter/issues/24).
+
# Development
The project uses `pnpm` for package management.
@@ -102,4 +115,4 @@ To get started clone the repo, install packages, build, and ensure tests pass:
pnpm build
pnpm test
-Git commit messages must follow [conventional commit standard](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional) (enforced by husky hooks). Versioning is handle by github actions and is determined by commit messages according to the [semantic-release](https://github.com/semantic-release/semantic-release#commit-message-format) rules and [`.releaserc`](.releaserc) configuration.
\ No newline at end of file
+Git commit messages must follow [conventional commit standard](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional) (enforced by husky hooks). Versioning is handle by github actions and is determined by commit messages according to the [semantic-release](https://github.com/semantic-release/semantic-release#commit-message-format) rules and [`.releaserc`](.releaserc) configuration.
diff --git a/package.json b/package.json
index b69bc41..8e2db78 100644
--- a/package.json
+++ b/package.json
@@ -28,15 +28,17 @@
"middleware",
"typescript"
],
- "packageManager": "pnpm@7.19.0",
+ "packageManager": "pnpm@8.15.4",
"devDependencies": {
"@commitlint/cli": "^17.6.6",
"@commitlint/config-conventional": "^17.6.6",
+ "@koa/bodyparser": "^5.0.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@trpc/server": "^10.33.0",
"@types/jest": "^29.5.2",
"@types/koa": "^2.13.6",
+ "@types/koa-bodyparser": "^4.3.12",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.60.1",
"@typescript-eslint/parser": "^5.60.1",
@@ -46,6 +48,7 @@
"husky": "^8.0.3",
"jest": "^29.5.0",
"koa": "^2.14.2",
+ "koa-bodyparser": "^4.4.1",
"lint-staged": "^13.2.3",
"prettier": "^2.8.8",
"semantic-release": "^21.0.6",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 245a7a3..287fce3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11,6 +11,9 @@ devDependencies:
'@commitlint/config-conventional':
specifier: ^17.6.6
version: 17.6.6
+ '@koa/bodyparser':
+ specifier: ^5.0.0
+ version: 5.0.0
'@semantic-release/changelog':
specifier: ^6.0.3
version: 6.0.3(semantic-release@21.0.6)
@@ -26,6 +29,9 @@ devDependencies:
'@types/koa':
specifier: ^2.13.6
version: 2.13.6
+ '@types/koa-bodyparser':
+ specifier: ^4.3.12
+ version: 4.3.12
'@types/supertest':
specifier: ^2.0.12
version: 2.0.12
@@ -53,6 +59,9 @@ devDependencies:
koa:
specifier: ^2.14.2
version: 2.14.2
+ koa-bodyparser:
+ specifier: ^4.4.1
+ version: 4.4.1
lint-staged:
specifier: ^13.2.3
version: 13.2.3
@@ -934,6 +943,15 @@ packages:
'@jridgewell/sourcemap-codec': 1.4.15
dev: true
+ /@koa/bodyparser@5.0.0:
+ resolution: {integrity: sha512-JEiZVe2e85qPOqA+Nw/SJC5fkFw3XSekh0RSoqz5F6lFYuhEspgqAb972rQRCJesv27QUsz96vU/Vb92wF1GUg==}
+ engines: {node: '>= 16'}
+ dependencies:
+ co-body: 6.1.0
+ lodash.merge: 4.6.2
+ type-is: 1.6.18
+ dev: true
+
/@nodelib/fs.scandir@2.1.5:
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -1397,6 +1415,12 @@ packages:
resolution: {integrity: sha512-GJhpTepz2udxGexqos8wgaBx4I/zWIDPh/KOGEwAqtuGDkOUJu5eFvwmdBX4AmB8Odsr+9pHCQqiAqDL/yKMKw==}
dev: true
+ /@types/koa-bodyparser@4.3.12:
+ resolution: {integrity: sha512-hKMmRMVP889gPIdLZmmtou/BijaU1tHPyMNmcK7FAHAdATnRcGQQy78EqTTxLH1D4FTsrxIzklAQCso9oGoebQ==}
+ dependencies:
+ '@types/koa': 2.13.6
+ dev: true
+
/@types/koa-compose@3.2.5:
resolution: {integrity: sha512-B8nG/OoE1ORZqCkBVsup/AKcvjdgoHnfi4pZMn5UwAPCbhk/96xyv284eBYW8JlQbQ7zDmnpFr68I/40mFoIBQ==}
dependencies:
@@ -1933,6 +1957,11 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
dev: true
+ /bytes@3.1.2:
+ resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
+ engines: {node: '>= 0.8'}
+ dev: true
+
/cache-content-type@1.0.1:
resolution: {integrity: sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==}
engines: {node: '>= 6.0.0'}
@@ -2078,6 +2107,15 @@ packages:
wrap-ansi: 7.0.0
dev: true
+ /co-body@6.1.0:
+ resolution: {integrity: sha512-m7pOT6CdLN7FuXUcpuz/8lfQ/L77x8SchHCF4G0RBTJO20Wzmhn5Sp4/5WsKy8OSpifBSUrmg83qEqaDHdyFuQ==}
+ dependencies:
+ inflation: 2.1.0
+ qs: 6.11.2
+ raw-body: 2.5.2
+ type-is: 1.6.18
+ dev: true
+
/co@4.6.0:
resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==}
engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}
@@ -2255,6 +2293,10 @@ packages:
keygrip: 1.1.0
dev: true
+ /copy-to@2.0.1:
+ resolution: {integrity: sha512-3DdaFaU/Zf1AnpLiFDeNCD4TOWe3Zl2RZaTzUvWiIk5ERzcCodOE20Vqq4fzCbNoHURFHT4/us/Lfq+S2zyY4w==}
+ dev: true
+
/core-util-is@1.0.3:
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
dev: true
@@ -3094,6 +3136,17 @@ packages:
toidentifier: 1.0.1
dev: true
+ /http-errors@2.0.0:
+ resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
+ engines: {node: '>= 0.8'}
+ dependencies:
+ depd: 2.0.0
+ inherits: 2.0.4
+ setprototypeof: 1.2.0
+ statuses: 2.0.1
+ toidentifier: 1.0.1
+ dev: true
+
/http-proxy-agent@7.0.0:
resolution: {integrity: sha512-+ZT+iBxVUQ1asugqnD6oWoRiS25AkjNfG085dKJGtGxkdwLQrMKU5wJr2bOOFAXzKcTuqq+7fZlTMgG3SRfIYQ==}
engines: {node: '>= 14'}
@@ -3130,6 +3183,13 @@ packages:
hasBin: true
dev: true
+ /iconv-lite@0.4.24:
+ resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
+ engines: {node: '>=0.10.0'}
+ dependencies:
+ safer-buffer: 2.1.2
+ dev: true
+
/ignore@5.2.4:
resolution: {integrity: sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==}
engines: {node: '>= 4'}
@@ -3172,6 +3232,11 @@ packages:
engines: {node: '>=12'}
dev: true
+ /inflation@2.1.0:
+ resolution: {integrity: sha512-t54PPJHG1Pp7VQvxyVCJ9mBbjG3Hqryges9bXoOO6GExCPa+//i/d5GSuFtpx3ALLd7lgIAur6zrIlBQyJuMlQ==}
+ engines: {node: '>= 0.8.0'}
+ dev: true
+
/inflight@1.0.6:
resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
dependencies:
@@ -3856,6 +3921,15 @@ packages:
engines: {node: '>=6'}
dev: true
+ /koa-bodyparser@4.4.1:
+ resolution: {integrity: sha512-kBH3IYPMb+iAXnrxIhXnW+gXV8OTzCu8VPDqvcDHW9SQrbkHmqPQtiZwrltNmSq6/lpipHnT7k7PsjlVD7kK0w==}
+ engines: {node: '>=8.0.0'}
+ dependencies:
+ co-body: 6.1.0
+ copy-to: 2.0.1
+ type-is: 1.6.18
+ dev: true
+
/koa-compose@4.1.0:
resolution: {integrity: sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==}
dev: true
@@ -4779,6 +4853,16 @@ packages:
engines: {node: '>=8'}
dev: true
+ /raw-body@2.5.2:
+ resolution: {integrity: sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==}
+ engines: {node: '>= 0.8'}
+ dependencies:
+ bytes: 3.1.2
+ http-errors: 2.0.0
+ iconv-lite: 0.4.24
+ unpipe: 1.0.0
+ dev: true
+
/rc@1.2.8:
resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}
hasBin: true
@@ -4975,6 +5059,10 @@ packages:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
dev: true
+ /safer-buffer@2.1.2:
+ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+ dev: true
+
/semantic-release@21.0.6:
resolution: {integrity: sha512-NDyosObAwUNzPpdf+mpL49Xy+5iYHjdWM34LBNdbdYv9vBLbw+eCCDihxcqPh+f9m4ZzlBrYCkHUaZv2vPGW9A==}
engines: {node: '>=18'}
@@ -5200,6 +5288,11 @@ packages:
engines: {node: '>= 0.6'}
dev: true
+ /statuses@2.0.1:
+ resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==}
+ engines: {node: '>= 0.8'}
+ dev: true
+
/stream-combiner2@1.1.1:
resolution: {integrity: sha512-3PnJbYgS56AeWgtKF5jtJRT6uFJe56Z0Hc5Ngg/6sI6rIt8iiMBTa9cvdyFfpMQjaVHr8dusbNeFGIIonxOvKw==}
dependencies:
@@ -5625,6 +5718,11 @@ packages:
engines: {node: '>= 10.0.0'}
dev: true
+ /unpipe@1.0.0:
+ resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
+ engines: {node: '>= 0.8'}
+ dev: true
+
/update-browserslist-db@1.0.11(browserslist@4.21.9):
resolution: {integrity: sha512-dCwEFf0/oT85M1fHBg4F0jtLwJrutGoHSQXCh7u4o2t1drG+c0a9Flnqww6XUKSfQMPpJBRjU8d4RXB09qtvaA==}
hasBin: true
diff --git a/src/index.ts b/src/index.ts
index 8a33a96..98bc8f7 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -7,6 +7,23 @@ import {
import { Middleware } from 'koa';
import { IncomingMessage, ServerResponse } from 'http';
+declare module 'koa' {
+ interface Request {
+ /* eslint-disable @typescript-eslint/no-explicit-any */
+ body?: any;
+ }
+}
+declare module 'http' {
+ interface IncomingMessage {
+ /* eslint-disable @typescript-eslint/no-explicit-any */
+ body?: any;
+ }
+ interface ServerResponse {
+ /* eslint-disable @typescript-eslint/no-explicit-any */
+ body?: any;
+ }
+}
+
export type CreateTrpcKoaContextOptions = NodeHTTPCreateContextFnOptions<
IncomingMessage,
ServerResponse
@@ -27,6 +44,13 @@ export const createKoaMiddleware =
if (prefix && !request.path.startsWith(prefix)) return next();
+ // put parsed body (by koa-bodyparser/@koa/bodyparser for example)
+ // where nodeHTTPRequestHandler will look for it.
+ // https://github.com/BlairCurrey/trpc-koa-adapter/issues/24
+ if ('body' in request) {
+ req.body = request.body;
+ }
+
// koa uses 404 as a default status but some logic in
// nodeHTTPRequestHandler assumes default status of 200.
// https://github.com/trpc/trpc/blob/abc941152b71ff2d68c63156eb5a142174779261/packages/server/src/adapters/node-http/nodeHTTPRequestHandler.ts#L63
diff --git a/test/createKoaMiddleware.test.ts b/test/createKoaMiddleware.test.ts
index fb92640..727c6a5 100644
--- a/test/createKoaMiddleware.test.ts
+++ b/test/createKoaMiddleware.test.ts
@@ -1,70 +1,31 @@
-import Koa from 'koa';
-import { createKoaMiddleware, CreateTrpcKoaContextOptions } from '../dist';
+import Koa, { Context } from 'koa';
+import { createKoaMiddleware, CreateTrpcKoaContextOptions } from '../src';
import request from 'supertest';
import { inferAsyncReturnType, initTRPC } from '@trpc/server';
import * as nodeHTTPAdapter from '@trpc/server/adapters/node-http';
+import { Server } from 'http';
+import koaBodyParserOld from 'koa-bodyparser';
+import koaBodyParser from '@koa/bodyparser';
-const ALL_USERS = [
- { id: 1, name: 'bob' },
- { id: 2, name: 'alice' },
-];
-
-const createContext = async ({ req, res }: CreateTrpcKoaContextOptions) => {
- return {
- req,
- res,
- isAuthed: () => req.headers.authorization === 'trustme',
- };
-};
-
-type TrpcContext = inferAsyncReturnType;
-
-const trpc = initTRPC.context().create();
-const trpcRouter = trpc.router({
- users: trpc.procedure.output(Object).query(() => {
- return ALL_USERS;
- }),
- user: trpc.procedure
- .input(Number)
- .output(Object)
- .query((req) => {
- return ALL_USERS.find((user) => req.input === user.id);
- }),
- createUser: trpc.procedure.input(Object).mutation(({ input, ctx }) => {
- if (!ctx.isAuthed()) {
- ctx.res.statusCode = 401;
- return;
- }
-
- const newUser = { id: Math.random(), name: input.name };
- ALL_USERS.push(newUser);
-
- return newUser;
- }),
-});
-
-const app = new Koa();
-
-const adapter = createKoaMiddleware({
- router: trpcRouter,
- createContext,
- prefix: '/trpc',
-});
-
-app.use(adapter);
-
-const server = app.listen(3089);
+describe('Unit', () => {
+ const router = initTRPC.create().router({});
+ const next = jest.fn();
+ let spyNodeHTTPRequestHandler: jest.SpyInstance;
-afterAll(() => server.close());
+ beforeEach(async () => {
+ spyNodeHTTPRequestHandler = jest
+ .spyOn(nodeHTTPAdapter, 'nodeHTTPRequestHandler')
+ .mockImplementationOnce(jest.fn());
+ });
-describe('createKoaMiddleware', () => {
- // re-initialize trpc router. top-level createContext type was
- // registered to top-level router, which would result in
- // a type error if used in createKoaMiddleware function with a
- // different createContext return type
- const router = initTRPC.create().router({});
+ afterEach(async () => {
+ jest.restoreAllMocks();
+ });
it('should return a function accepting 2 arguments', () => {
+ const adapter = createKoaMiddleware({
+ router,
+ });
expect(typeof adapter).toBe('function');
expect(adapter.length).toBe(2);
});
@@ -72,134 +33,203 @@ describe('createKoaMiddleware', () => {
expect(createKoaMiddleware.length).toBe(1);
});
it('createKoaMiddleware should call nodeHTTPRequestHandler if request prefix matches', () => {
- const trpcAdapterWithPrefix = createKoaMiddleware({ router, prefix: '/trpc' });
+ const adapter = createKoaMiddleware({ router, prefix: '/trpc' });
- const mockCtxWithPrefix = {
+ const ctx = {
request: {
path: '/trpc/users',
},
req: {},
res: {},
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any;
- const mockNext = jest.fn(async () => {
- return {};
- });
- const originalNodeHTTPRequestHandler = nodeHTTPAdapter.nodeHTTPRequestHandler;
- Object.defineProperty(nodeHTTPAdapter, 'nodeHTTPRequestHandler', { value: jest.fn() });
- const spyNodeHTTPRequestHandler = jest.spyOn(nodeHTTPAdapter, 'nodeHTTPRequestHandler');
+ } as Context;
- trpcAdapterWithPrefix(mockCtxWithPrefix, mockNext);
+ adapter(ctx, next);
- expect(mockNext.mock.calls.length).toBe(0);
+ expect(next).not.toHaveBeenCalled();
expect(spyNodeHTTPRequestHandler).toHaveBeenCalled();
-
- Object.defineProperty(nodeHTTPAdapter, 'nodeHTTPRequestHandler', {
- value: originalNodeHTTPRequestHandler,
- });
});
it('createKoaMiddleware should call nodeHTTPRequestHandler if no prefix set', () => {
- const trpcAdapterWithoutPrefix = createKoaMiddleware({ router });
+ const adapter = createKoaMiddleware({ router });
- const mockCtxWithPrefix = {
+ const ctx = {
request: {
path: '/users',
},
req: {},
res: {},
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any;
- const mockNext = jest.fn(async () => {
- return {};
- });
- const originalNodeHTTPRequestHandler = nodeHTTPAdapter.nodeHTTPRequestHandler;
- Object.defineProperty(nodeHTTPAdapter, 'nodeHTTPRequestHandler', { value: jest.fn() });
- const spyNodeHTTPRequestHandler = jest.spyOn(nodeHTTPAdapter, 'nodeHTTPRequestHandler');
+ } as Context;
- trpcAdapterWithoutPrefix(mockCtxWithPrefix, mockNext);
+ adapter(ctx, next);
- expect(mockNext.mock.calls.length).toBe(0);
+ expect(next).not.toHaveBeenCalled();
expect(spyNodeHTTPRequestHandler).toHaveBeenCalled();
-
- Object.defineProperty(nodeHTTPAdapter, 'nodeHTTPRequestHandler', {
- value: originalNodeHTTPRequestHandler,
- });
});
it('createKoaMiddleware should call next and not process request if prefix set and request doesnt have prefix', () => {
- const trpcAdapterWithPrefix = createKoaMiddleware({ router, prefix: '/trpc' });
+ const adapter = createKoaMiddleware({ router, prefix: '/trpc' });
- const mockCtx = {
+ const ctx = {
request: {
path: '/users', // prefix missing from path
},
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any;
- const mockNext = jest.fn(async () => {
- return {};
- });
- const spyNodeHTTPRequestHandler = jest.spyOn(nodeHTTPAdapter, 'nodeHTTPRequestHandler');
+ } as Context;
- trpcAdapterWithPrefix(mockCtx, mockNext);
+ adapter(ctx, next);
- expect(mockNext.mock.calls.length).toBe(1);
+ expect(next).toHaveBeenCalled();
expect(spyNodeHTTPRequestHandler).not.toHaveBeenCalled();
});
-});
+ it('createKoaMiddleware should call nodeHTTPRequestHandler with req.body if parsed body found on request.body', () => {
+ const adapter = createKoaMiddleware({ router });
-describe('API calls', () => {
- describe('Can call tRPC server endpoints succesfully', () => {
- it('GET /users', async () => {
- const response = await request(server)
- .get('/trpc/users')
- .set('content-type', 'application/json');
-
- expect(response.headers['content-type']).toMatch(/json/);
- expect(response.status).toEqual(200);
- expect(response.body.result.data).toEqual(ALL_USERS);
- });
+ const ctx = {
+ request: { path: '/users', body: { name: 'Person1', age: 20 } },
+ req: {},
+ res: {},
+ } as Context;
+ adapter(ctx, next);
- it('GET /user?id=1', async () => {
- const id = 1;
- const response = await request(server)
- .get('/trpc/user')
- .set('content-type', 'application/json')
- .query({ input: id });
+ expect(next).not.toHaveBeenCalled();
+ expect(spyNodeHTTPRequestHandler).toBeCalledWith(
+ expect.objectContaining({ req: { body: ctx.request.body } })
+ );
+ });
+});
- expect(response.headers['content-type']).toMatch(/json/);
- expect(response.status).toEqual(200);
- expect(response.body.result.data).toEqual(ALL_USERS.find((user) => user.id === id));
- });
+describe('Integration', () => {
+ const ALL_USERS = [
+ { id: 1, name: 'bob' },
+ { id: 2, name: 'alice' },
+ ];
+
+ const createContext = async ({ req, res }: CreateTrpcKoaContextOptions) => {
+ return {
+ req,
+ res,
+ isAuthed: () => req.headers.authorization === 'trustme',
+ };
+ };
- it('POST /createUser', async () => {
- const response = await request(server)
- .post('/trpc/createUser')
- .send({ name: 'eve' })
- .set('content-type', 'application/json')
- .set('authorization', 'trustme');
- const { data: newUser } = response.body.result;
-
- expect(response.headers['content-type']).toMatch(/json/);
- expect(response.status).toEqual(200);
- expect(newUser).toEqual(ALL_USERS.find((user) => user.id === newUser.id));
- });
+ type TrpcContext = inferAsyncReturnType;
- it('POST /createUser: failed auth sets status (using ctx)', async () => {
- const response = await request(server)
- .post('/trpc/createUser')
- .send({ name: 'eve' })
- .set('content-type', 'application/json');
+ const trpc = initTRPC.context().create();
+ const trpcRouter = trpc.router({
+ users: trpc.procedure.output(Object).query(() => {
+ return ALL_USERS;
+ }),
+ user: trpc.procedure
+ .input(Number)
+ .output(Object)
+ .query((req) => {
+ return ALL_USERS.find((user) => req.input === user.id);
+ }),
+ createUser: trpc.procedure.input(Object).mutation(({ input, ctx }) => {
+ if (!ctx.isAuthed()) {
+ ctx.res.statusCode = 401;
+ return;
+ }
+
+ const newUser = { id: Math.random(), name: input.name };
+ ALL_USERS.push(newUser);
+
+ return newUser;
+ }),
+ });
- expect(response.headers['content-type']).toMatch(/json/);
- expect(response.status).toEqual(401);
- });
+ const adapter = createKoaMiddleware({
+ router: trpcRouter,
+ createContext,
+ prefix: '/trpc',
});
- describe('Bad requests fail as expected', () => {
- it('GET /some-non-existent-route', async () => {
- const response = await request(server).get('/some-non-existent-route');
- const response2 = await request(server).get('/trpc/some-non-existent-route');
- expect(response.status).toEqual(404);
- expect(response2.status).toEqual(404);
+ const testCases = [
+ {
+ description: 'Without body parser',
+ middleware: [],
+ },
+ {
+ description: 'With koa-bodyparser',
+ middleware: [koaBodyParserOld()],
+ },
+ {
+ description: 'With @koa/bodyparser',
+ middleware: [koaBodyParser()],
+ },
+ {
+ description: 'With @koa/bodyparser using patchNode',
+ middleware: [koaBodyParser({ patchNode: true, encoding: 'utf-8' })],
+ },
+ ];
+
+ testCases.forEach(({ description, middleware }) => {
+ describe(description, () => {
+ const app = new Koa();
+ middleware.forEach((middlewareItem) => app.use(middlewareItem));
+ app.use(adapter);
+ let server: Server;
+
+ beforeEach(async () => (server = app.listen(3098)));
+ afterEach(async () => {
+ if (server?.listening) {
+ await server.closeAllConnections();
+ await server.close();
+ }
+ });
+
+ describe('Can call tRPC server endpoints succesfully', () => {
+ it('GET /users', async () => {
+ const response = await request(server)
+ .get('/trpc/users')
+ .set('content-type', 'application/json');
+
+ expect(response.headers['content-type']).toMatch(/json/);
+ expect(response.status).toEqual(200);
+ expect(response.body.result.data).toEqual(ALL_USERS);
+ });
+
+ it('GET /user?id=1', async () => {
+ const id = 1;
+ const response = await request(server)
+ .get('/trpc/user')
+ .set('content-type', 'application/json')
+ .query({ input: id });
+
+ expect(response.headers['content-type']).toMatch(/json/);
+ expect(response.status).toEqual(200);
+ expect(response.body.result.data).toEqual(ALL_USERS.find((user) => user.id === id));
+ });
+
+ it('POST /createUser', async () => {
+ const response = await request(server)
+ .post('/trpc/createUser')
+ .send({ name: 'eve' })
+ .set('content-type', 'application/json')
+ .set('authorization', 'trustme');
+ const { data: newUser } = response.body.result;
+
+ expect(response.headers['content-type']).toMatch(/json/);
+ expect(response.status).toEqual(200);
+ expect(newUser).toEqual(ALL_USERS.find((user) => user.id === newUser.id));
+ });
+
+ it('POST /createUser: failed auth sets status (using ctx)', async () => {
+ const response = await request(server)
+ .post('/trpc/createUser')
+ .send({ name: 'eve' })
+ .set('content-type', 'application/json');
+
+ expect(response.headers['content-type']).toMatch(/json/);
+ expect(response.status).toEqual(401);
+ });
+ });
+ describe('Bad requests fail as expected', () => {
+ it('GET /some-non-existent-route', async () => {
+ const response = await request(server).get('/some-non-existent-route');
+ const response2 = await request(server).get('/trpc/some-non-existent-route');
+
+ expect(response.status).toEqual(404);
+ expect(response2.status).toEqual(404);
+ });
+ });
});
});
});
diff --git a/tsconfig.json b/tsconfig.json
index d8d7f0c..34df5f9 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,104 +1,14 @@
{
"compilerOptions": {
- /* Visit https://aka.ms/tsconfig to read more about this file */
-
- /* Projects */
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
-
- /* Language and Environment */
- "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
- // "jsx": "preserve", /* Specify what JSX code is generated. */
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
-
- /* Modules */
- "module": "commonjs" /* Specify what module code is generated. */,
- "rootDir": "./src" /* Specify the root folder within your source files. */,
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
- // "resolveJsonModule": true, /* Enable importing .json files. */
- // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
-
- /* JavaScript Support */
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
-
- /* Emit */
- "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
- "outDir": "./dist" /* Specify an output folder for all emitted files. */,
- // "removeComments": true, /* Disable emitting comments. */
- // "noEmit": true, /* Disable emitting files from a compilation. */
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
- // "newLine": "crlf", /* Set the newline character for emitting files. */
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
-
- /* Interop Constraints */
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
-
- /* Type Checking */
- "strict": true /* Enable all strict type-checking options. */,
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
-
- /* Completeness */
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
+ "target": "es2016",
+ "module": "commonjs",
+ "rootDir": "./src",
+ "declaration": true,
+ "outDir": "./dist",
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "skipLibCheck": true
},
"include": ["src/**/*"]
}