├── .eslintrc.js ├── .github └── workflows │ └── test.yml ├── .gitignore ├── .npmignore ├── .npmrc ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── RELEASE.md ├── assets ├── trpc-rabbitmq-readme.png └── trpc-rabbitmq.png ├── jest.config.js ├── package-lock.json ├── package.json ├── prettier.config.js ├── src ├── adapter │ ├── errors.ts │ └── index.ts ├── link │ └── index.ts └── types │ └── index.ts ├── test └── .keep ├── tsconfig.build.json ├── tsconfig.eslint.json └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | 3 | /** @type {import('eslint').Linter.Config} */ 4 | module.exports = { 5 | root: true, 6 | extends: [ 7 | 'eslint:recommended', 8 | 'plugin:import/recommended', 9 | 'plugin:import/typescript', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:promise/recommended', 12 | 'plugin:prettier/recommended' 13 | ], 14 | parser: '@typescript-eslint/parser', 15 | parserOptions: { 16 | ecmaFeatures: { jsx: false }, 17 | ecmaVersion: 'latest', 18 | sourceType: 'module', 19 | project: './tsconfig.eslint.json', 20 | tsconfigRootDir: __dirname 21 | }, 22 | env: { 23 | node: true 24 | }, 25 | rules: { 26 | '@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: false }], 27 | '@typescript-eslint/unbound-method': 'off', 28 | '@typescript-eslint/no-explicit-any': 'off' 29 | }, 30 | overrides: [ 31 | { 32 | files: ['*.js', '*.jsx', '*.mjs', '*.cjs'], 33 | rules: {} 34 | } 35 | ] 36 | }; 37 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout repo 8 | uses: actions/checkout@v2 9 | 10 | - name: Setup node 11 | uses: actions/setup-node@v3 12 | with: 13 | node-version: 16 14 | 15 | - name: Install dependencies 16 | run: npm ci 17 | 18 | - name: Run tests 19 | run: npm test 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | dist 4 | adapter/**/* 5 | link/**/* 6 | types/**/* -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | * 2 | !adapter/**/* 3 | !link/**/* 4 | !types/**/* 5 | !package.json 6 | !package-lock.json 7 | !LICENSE -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | sign-git-tag=false 2 | message="trpc-rabbitmq v%s" -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "yzhang.markdown-all-in-one", 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib", 3 | "editor.tabSize": 2, 4 | "editor.formatOnSave": true, 5 | "editor.codeActionsOnSave": { 6 | "source.fixAll.eslint": true 7 | }, 8 | "[javascript]": { 9 | "editor.defaultFormatter": "esbenp.prettier-vscode" 10 | }, 11 | "[jsonc]": { 12 | "editor.defaultFormatter": "esbenp.prettier-vscode" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Piotr Adamczyk 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | trpc-rabbitmq 3 |

trpc-rabbitmq

4 | 5 | 6 |
7 |
8 |
9 | 10 | 11 | ## Usage 12 | 13 | **1. Install `trpc-rabbitmq`.** 14 | 15 | ```bash 16 | # npm 17 | npm install trpc-rabbitmq 18 | # yarn 19 | yarn add trpc-rabbitmq 20 | # pnpm 21 | pnpm add trpc-rabbitmq 22 | ``` 23 | 24 | **2. Use `rmqLink` in your client code.** 25 | 26 | ```typescript 27 | import { createTRPCProxyClient } from '@trpc/client'; 28 | import { rmqLink } from 'trpc-rabbitmq/link'; 29 | 30 | import type { AppRouter } from './appRouter'; 31 | 32 | export const trpc = createTRPCProxyClient({ 33 | links: [ 34 | rmqLink({ 35 | url: "amqp://localhost", 36 | queue: "app" 37 | }) 38 | ], 39 | }); 40 | ``` 41 | 42 | **3. Use `createRMQHandler` to handle incoming calls via RabbitMQ on the server.** 43 | 44 | ```typescript 45 | import { createRMQHandler } from 'trpc-rabbitmq/adapter'; 46 | 47 | import { appRouter } from './appRouter'; 48 | 49 | createRMQHandler({ 50 | url: "amqp://localhost", 51 | queue: "app", 52 | router: appRouter 53 | }); 54 | ``` 55 | 56 | ## License 57 | 58 | Distributed under the MIT License. See LICENSE for more information. -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | npm run test 2 | npm version {{version}} 3 | npm run build 4 | npm publish {{--tag alpha}} 5 | -------------------------------------------------------------------------------- /assets/trpc-rabbitmq-readme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imxeno/trpc-rabbitmq/8bf5871c71a322f66a16ed80d36be130c06411ad/assets/trpc-rabbitmq-readme.png -------------------------------------------------------------------------------- /assets/trpc-rabbitmq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imxeno/trpc-rabbitmq/8bf5871c71a322f66a16ed80d36be130c06411ad/assets/trpc-rabbitmq.png -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | 3 | /** @type {import('ts-jest/dist/types').JestConfigWithTsJest} */ 4 | module.exports = { 5 | preset: 'ts-jest', 6 | testEnvironment: 'node', 7 | rootDir: './test', 8 | snapshotFormat: { 9 | escapeString: true, 10 | printBasicPrototype: true 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "trpc-rabbitmq", 3 | "version": "0.1.3", 4 | "description": "tRPC adapter for RabbitMQ", 5 | "author": "Piotr Adamczyk ", 6 | "license": "MIT", 7 | "keywords": [ 8 | "trpc", 9 | "rabbitmq", 10 | "rmq" 11 | ], 12 | "homepage": "https://github.com/imxeno/trpc-rabbitmq", 13 | "repository": "github:imxeno/trpc-rabbitmq", 14 | "bugs": "https://github.com/imxeno/trpc-rabbitmq/issues", 15 | "scripts": { 16 | "prepublish": "npm run build", 17 | "test": "tsc --noEmit && jest --verbose --passWithNoTests", 18 | "build": "rimraf dist && rimraf adapter && rimraf link && rimraf types && tsc -p tsconfig.build.json && shx mv dist/* . && rimraf dist" 19 | }, 20 | "peerDependencies": { 21 | "@trpc/client": "10.0.0-proxy-beta.18", 22 | "@trpc/server": "10.0.0-proxy-beta.18" 23 | }, 24 | "devDependencies": { 25 | "@trivago/prettier-plugin-sort-imports": "^3.3.0", 26 | "@types/amqplib": "^0.8.2", 27 | "@types/jest": "^29.1.2", 28 | "@types/node": "^18.8.5", 29 | "@typescript-eslint/eslint-plugin": "^5.40.0", 30 | "@typescript-eslint/parser": "^5.40.0", 31 | "eslint": "^8.25.0", 32 | "eslint-config-prettier": "^8.5.0", 33 | "eslint-plugin-import": "^2.26.0", 34 | "eslint-plugin-prettier": "^4.2.1", 35 | "eslint-plugin-promise": "^6.1.0", 36 | "jest": "^29.1.2", 37 | "jest-environment-jsdom": "^29.1.2", 38 | "prettier": "^2.7.1", 39 | "rimraf": "^3.0.2", 40 | "shx": "^0.3.4", 41 | "superjson": "^1.10.1", 42 | "ts-jest": "^29.0.3", 43 | "ts-node": "^10.9.1", 44 | "typescript": "^4.8.4", 45 | "zod": "^3.19.1" 46 | }, 47 | "dependencies": { 48 | "amqp-connection-manager": "^4.1.7", 49 | "amqplib": "^0.10.3" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | 3 | /** @type import("prettier").Options */ 4 | module.exports = { 5 | printWidth: 100, 6 | tabWidth: 2, 7 | useTabs: false, 8 | semi: true, 9 | singleQuote: true, 10 | arrowParens: 'avoid', 11 | trailingComma: 'none', 12 | endOfLine: 'lf', 13 | importOrder: ['__', '', '^[./]'], 14 | importOrderSeparation: true, 15 | importOrderSortSpecifiers: true 16 | }; 17 | -------------------------------------------------------------------------------- /src/adapter/errors.ts: -------------------------------------------------------------------------------- 1 | import { TRPCError } from '@trpc/server'; 2 | 3 | export function getErrorFromUnknown(cause: unknown): TRPCError { 4 | if (cause instanceof Error && cause.name === 'TRPCError') { 5 | return cause as TRPCError; 6 | } 7 | 8 | let errorCause: Error | undefined = undefined; 9 | let stack: string | undefined = undefined; 10 | 11 | if (cause instanceof Error) { 12 | errorCause = cause; 13 | stack = cause.stack; 14 | } 15 | 16 | const error = new TRPCError({ 17 | message: 'Internal server error', 18 | code: 'INTERNAL_SERVER_ERROR', 19 | cause: errorCause 20 | }); 21 | 22 | if (stack) { 23 | error.stack = stack; 24 | } 25 | 26 | return error; 27 | } 28 | -------------------------------------------------------------------------------- /src/adapter/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AnyRouter, 3 | ProcedureType, 4 | TRPCError, 5 | callProcedure, 6 | inferRouterContext 7 | } from '@trpc/server'; 8 | import type { OnErrorFunction } from '@trpc/server/dist/internals/types'; 9 | import * as amqp from 'amqp-connection-manager'; 10 | import type { ConsumeMessage } from 'amqplib'; 11 | 12 | import { getErrorFromUnknown } from './errors'; 13 | 14 | const AMQP_METHOD_PROCEDURE_TYPE_MAP: Record = { 15 | query: 'query', 16 | mutation: 'mutation' 17 | }; 18 | 19 | export type CreateRMQHandlerOptions = { 20 | url: string; 21 | queue: string; 22 | router: TRouter; 23 | durable?: boolean; 24 | onError?: OnErrorFunction; 25 | }; 26 | 27 | export const createRMQHandler = ( 28 | opts: CreateRMQHandlerOptions 29 | ) => { 30 | const { url, queue, router, durable, onError } = opts; 31 | 32 | const connection = amqp.connect(url); 33 | connection.createChannel({ 34 | setup: async (channel: amqp.Channel) => { 35 | await channel.assertQueue(queue, { durable }); 36 | 37 | void channel.consume(opts.queue, async msg => { 38 | if (!msg) return; 39 | channel.ack(msg); 40 | const { correlationId, replyTo } = msg.properties; 41 | if (!correlationId || !replyTo) return; 42 | const res = await handleMessage(router, msg, onError); 43 | if (!res) return; 44 | void channel.sendToQueue(replyTo as string, Buffer.from(JSON.stringify({ trpc: res })), { 45 | correlationId: correlationId as string 46 | }); 47 | }); 48 | } 49 | }); 50 | 51 | return { close: () => connection.close() }; 52 | }; 53 | 54 | async function handleMessage( 55 | router: TRouter, 56 | msg: ConsumeMessage, 57 | onError?: OnErrorFunction 58 | ) { 59 | const { transformer } = router._def._config; 60 | 61 | try { 62 | const message = JSON.parse(msg.content.toString('utf-8')); 63 | if (!('trpc' in message)) return; 64 | const { trpc } = message; 65 | if (!('id' in trpc) || trpc.id === null || trpc.id === undefined) return; 66 | if (!trpc) return; 67 | 68 | const { id, params } = trpc; 69 | const type = AMQP_METHOD_PROCEDURE_TYPE_MAP[trpc.method] ?? ('query' as const); 70 | const ctx: inferRouterContext | undefined = undefined; 71 | 72 | try { 73 | const path = params.path; 74 | 75 | if (!path) { 76 | throw new Error('No path provided'); 77 | } 78 | 79 | if (type === 'subscription') { 80 | throw new TRPCError({ 81 | message: 'RabbitMQ link does not support subscriptions (yet?)', 82 | code: 'METHOD_NOT_SUPPORTED' 83 | }); 84 | } 85 | 86 | const deserializeInputValue = (rawValue: unknown) => { 87 | return typeof rawValue !== 'undefined' ? transformer.input.deserialize(rawValue) : rawValue; 88 | }; 89 | 90 | const input = deserializeInputValue(params.input); 91 | 92 | const output = await callProcedure({ 93 | procedures: router._def.procedures, 94 | path, 95 | rawInput: input, 96 | ctx, 97 | type 98 | }); 99 | 100 | return { 101 | id, 102 | result: { 103 | type: 'data', 104 | data: output 105 | } 106 | }; 107 | } catch (cause) { 108 | const error = getErrorFromUnknown(cause); 109 | onError?.({ 110 | error, 111 | type, 112 | path: trpc?.path, 113 | input: trpc?.input, 114 | ctx, 115 | req: msg 116 | }); 117 | 118 | return { 119 | id, 120 | error: router.getErrorShape({ 121 | error, 122 | type, 123 | path: trpc?.path, 124 | input: trpc?.input, 125 | ctx 126 | }) 127 | }; 128 | } 129 | } catch (cause) { 130 | // TODO: Assume json parsing error (so shouldn't happen), but we need to handle this better 131 | return {}; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/link/index.ts: -------------------------------------------------------------------------------- 1 | import { TRPCClientError, TRPCLink } from '@trpc/client'; 2 | import type { AnyRouter } from '@trpc/server'; 3 | import { observable } from '@trpc/server/observable'; 4 | import * as amqp from 'amqp-connection-manager'; 5 | import { randomUUID } from 'crypto'; 6 | import EventEmitter from 'events'; 7 | 8 | import type { TRPCRMQRequest, TRPCRMQResponse } from '../types'; 9 | 10 | const REPLY_QUEUE = 'amq.rabbitmq.reply-to'; 11 | 12 | export type TRPCRMQLinkOptions = { 13 | url: string; 14 | queue: string; 15 | durable?: boolean; 16 | }; 17 | 18 | export const rmqLink = (opts: TRPCRMQLinkOptions): TRPCLink => { 19 | return runtime => { 20 | const { url, queue, durable } = opts; 21 | const responseEmitter = new EventEmitter(); 22 | responseEmitter.setMaxListeners(0); 23 | 24 | const connection = amqp.connect(url); 25 | const channel = connection.createChannel({ 26 | setup: async (channel: amqp.Channel) => { 27 | await channel.assertQueue(queue, { durable }); 28 | await channel.consume( 29 | REPLY_QUEUE, 30 | msg => { 31 | if (!msg) return; 32 | responseEmitter.emit( 33 | msg.properties.correlationId as string, 34 | JSON.parse(msg.content.toString('utf-8')) 35 | ); 36 | }, 37 | { noAck: true } 38 | ); 39 | } 40 | }); 41 | 42 | const sendToQueue = async (message: TRPCRMQRequest) => 43 | new Promise(resolve => { 44 | const correlationId = randomUUID(); 45 | responseEmitter.once(correlationId, resolve); 46 | void channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)), { 47 | correlationId, 48 | replyTo: REPLY_QUEUE 49 | }); 50 | }); 51 | 52 | return ({ op }) => { 53 | return observable(observer => { 54 | const { id, type, path } = op; 55 | 56 | try { 57 | const input = runtime.transformer.serialize(op.input); 58 | 59 | const onMessage = (message: TRPCRMQResponse) => { 60 | if (!('trpc' in message)) return; 61 | const { trpc } = message; 62 | if (!trpc) return; 63 | if (!('id' in trpc) || trpc.id === null || trpc.id === undefined) return; 64 | if (id !== trpc.id) return; 65 | 66 | if ('error' in trpc) { 67 | const error = runtime.transformer.deserialize(trpc.error); 68 | observer.error(TRPCClientError.from({ ...trpc, error })); 69 | return; 70 | } 71 | 72 | observer.next({ 73 | result: { 74 | ...trpc.result, 75 | ...((!trpc.result.type || trpc.result.type === 'data') && { 76 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 77 | data: runtime.transformer.deserialize(trpc.result.data)! 78 | }) 79 | } 80 | }); 81 | 82 | observer.complete(); 83 | }; 84 | 85 | sendToQueue({ 86 | trpc: { 87 | id, 88 | method: type, 89 | params: { path, input } 90 | } 91 | }) 92 | .then(onMessage) 93 | .catch(cause => { 94 | observer.error( 95 | new TRPCClientError(cause instanceof Error ? cause.message : 'Unknown error') 96 | ); 97 | }); 98 | } catch (cause) { 99 | observer.error( 100 | new TRPCClientError(cause instanceof Error ? cause.message : 'Unknown error') 101 | ); 102 | } 103 | 104 | // eslint-disable-next-line @typescript-eslint/no-empty-function 105 | return () => {}; 106 | }); 107 | }; 108 | }; 109 | }; 110 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | TRPCClientOutgoingMessage, 3 | TRPCErrorResponse, 4 | TRPCRequest, 5 | TRPCResultMessage 6 | } from '@trpc/server/rpc'; 7 | 8 | export type TRPCRMQRequest = { 9 | trpc: TRPCRequest | TRPCClientOutgoingMessage; 10 | }; 11 | 12 | export type TRPCRMQSuccessResponse = { 13 | trpc: TRPCResultMessage; 14 | }; 15 | 16 | export type TRPCRMQErrorResponse = { 17 | trpc: TRPCErrorResponse; 18 | }; 19 | 20 | export type TRPCRMQResponse = TRPCRMQSuccessResponse | TRPCRMQErrorResponse; 21 | -------------------------------------------------------------------------------- /test/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imxeno/trpc-rabbitmq/8bf5871c71a322f66a16ed80d36be130c06411ad/test/.keep -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "noEmit": false, 5 | "outDir": "dist" 6 | }, 7 | "include": ["src"] 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["**/*", ".eslintrc.js"], 4 | "exclude": ["node_modules", "adapter", "link", "types"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noEmit": true, 4 | "target": "ES2017", 5 | "module": "commonjs", 6 | "strict": true, 7 | "declaration": true, 8 | "declarationMap": true, 9 | "sourceMap": true, 10 | "skipLibCheck": true, 11 | "allowJs": true, 12 | "checkJs": false, 13 | "moduleResolution": "node", 14 | "esModuleInterop": true, 15 | "removeComments": false, 16 | "noUncheckedIndexedAccess": true, 17 | "importsNotUsedAsValues": "error" 18 | }, 19 | "include": ["src", "test"] 20 | } 21 | --------------------------------------------------------------------------------