Git Product home page Git Product logo

elysia-trpc's Introduction

@elysiajs/trpc

A plugin for elysia that adds support for using tRPC.

Installation

bun add @elysiajs/trpc

Example

import { Elysia, t } from 'elysia'
import { trpc, compile as c } from '@elysiajs/trpc'

import { initTRPC } from '@trpc/server'

const r = initTRPC.create()

const router = r.router({
    greet: r.procedure.input(c(t.String())).query(({ input }) => input)
})

export type Router = typeof router

const app = new Elysia()
    .use(trpc(router))
    .listen(8080)

API

This plugin extends the new method trpc to Elysia class.

trpc

Register tRPC router.

type tRPC = (router: Router<any>, options?: TRPCOptions) => this

export interface TRPCOptions
    extends Omit<
        FetchHandlerRequestOptions<any>,
        'req' | 'router' | 'endpoint'
    > {
    /**
     * tRPC endpoint
     *
     * @default '/trpc'
     */
    endpoint?: string
}

Note

WebSocket API is in an experimental state and unstable.

Is meant for experimental for better stabilization.

elysia-trpc's People

Contributors

bogeychan avatar danieldunderfelt avatar parweb avatar saltyaom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

elysia-trpc's Issues

Support tRPC v11

What is the problem this feature would solve?

The current elysia (1.1.0 of @elysiajs/trpc) seems not to support tRPC v11.
If I just bump @trpc/server and @trpc/client from 10.45.2 to 11.0.0-rc.477, it causes the following error:

# Unhandled error between tests
-------------------------------
41 |     }
42 |     constructor(message, opts){
43 |         const cause = opts?.cause;
44 |         // eslint-disable-next-line @typescript-eslint/ban-ts-comment
45 |         // @ts-ignore https://github.com/tc39/proposal-error-cause
46 |         super(message, {
             ^
TRPCClientError: No "query"-procedure on path "hello"
      at new TRPCClientError (.../node_modules/@trpc/client/dist/TRPCClientError.mjs:46:9)
      at from (.../node_modules/@trpc/client/dist/TRPCClientError.mjs:26:20)
      at .../node_modules/@trpc/client/dist/links/httpBatchLink.mjs:82:56
-------------------------------

If you need, I can create a repoduction repo.

What is the feature you are proposing to solve the problem?

Make @elysiajs/trpc support the latest tRPC (v11).

What alternatives have you considered?

No response

readme example fails

Tried the code from the trpc example and it failed to greet from the client (404s). Only major difference from the example was adding cors (for local development/recreation)

Bun 1.0.2

server.ts

import { cors } from '@elysiajs/cors';
import { Elysia, t } from 'elysia';
import { trpc, compile as c } from '@elysiajs/trpc';
import { initTRPC } from '@trpc/server';

const r = initTRPC.create();

const router = r.router({
  greet: r.procedure.input(c(t.String())).query(({ input }) => input)
});

export type Router = typeof router

const app = new Elysia()
  .use(cors())
  .use(trpc(router))
  .listen(8080)

client.ts

import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { Router } from './server';

const trpc = createTRPCProxyClient<App>({
  links: [
    httpBatchLink({
      url: 'http://localhost:8080',
    }),
  ],
});

const result = await trpc.greet.query('Hello Elysia');
console.log(result);

Confirmed that the client wasn't the issue by using a barebones trpc server file

server.trpc.ts

import { initTRPC } from '@trpc/server';
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import cors from 'cors';
import { z } from 'zod';

export const t = initTRPC.create();

const appRouter = t.router({
  greet: t.procedure
    .input(z.object({ message: z.string() }))
    .query(({ input }) => input)
});

export type Router = typeof appRouter;

const server = createHTTPServer({
  middleware: cors(),
  router: appRouter,
});

server.listen(8080);

turn on noUncheckedIndexedAccess rule in tsconfig

When setting noUncheckedIndexedAccess to true in a project consuming this library, type errors ensue:

node_modules/@elysiajs/trpc/src/index.ts:19:17 - error TS2339: Property 'path' does not exist on type 'ValueError | undefined'.

19         const { path, message } = [...check.Errors(value)][0]
                   ~~~~

node_modules/@elysiajs/trpc/src/index.ts:19:23 - error TS2339: Property 'message' does not exist on type 'ValueError | undefined'.

19         const { path, message } = [...check.Errors(value)][0]
                         ~~~~~~~


Found 6 errors in 3 files.

Errors  Files
     2  node_modules/@elysiajs/trpc/src/index.ts:19

Websockets not calling unsubscribe and error at connect

Getting the screenshot error on connect and also disconnect, also since is erroring out, it's not capable to unsubscribe.

import { appRouter, createTRPCContextFetch } from '@app-packages/api';
import { cors } from '@elysiajs/cors';
import { html } from '@elysiajs/html';
import { trpc } from '@elysiajs/trpc';
import dotenv from 'dotenv';
import { Elysia } from 'elysia';
import { renderTrpcPanel } from 'trpc-panel';

dotenv.config({
	override: true,
	path: '../../.env',
});

const app = new Elysia().use(html()).use(cors());

app.get('/panel', (context) => {
	context.headers['Content-Type'] = 'text/html; charset=utf-8';

	return renderTrpcPanel(appRouter, {
		url: 'http://localhost:8080/api/trpc',
		transformer: 'superjson',
	});
});

app.use(
	trpc(appRouter, {
		endpoint: '/api/trpc',
		createContext: createTRPCContextFetch,
	})
);

app.listen(8080);

// eslint-disable-next-line no-console
console.log('🦊 Server started on http://localhost:8080/panel');

with dependencies:

  "dependencies": {
    "@app-packages/api": "*",
    "@elysiajs/cors": "^0.8.0",
    "@elysiajs/html": "^0.8.0",
    "@elysiajs/trpc": "^0.8.0",
    "@trpc/server": "^10.45.0",
    "elysia": "^0.8.9",
    "trpc-panel": "^1.3.4"
  },
  "devDependencies": {
    "bun-types": "^1.0.22",
    "@types/ws": "^8.5.10",
    "@app/eslint-config": "*"
  },

The code itself:

	onNotifyClubChat: publicProcedure.subscription(async () => {
  	console.log('onNotifyClubChat');

  	return observable<string>((emit) => {
  		redisSubscriber.subscribe('club-chat');

  		const onMessage = (channel: string, message: string) => {
  			console.log('onNotifyClubChat message', channel, message);
  			emit.next(`${channel}:${message}`);
  		};
  		redisSubscriber.on('message', onMessage);

  		return () => {
  			console.log('onNotifyClubChat unsubscribed');
  			redisSubscriber.off('club-chat', onMessage);
  		};
  	});
  }),

The subscription is successfully sending the message or subscribing regardless of the error, but it's not unsubscribing, and that causes a memory leak.

image

problem with building my api

so i have an interesting usecase.. i have 2 microservices, that need to talk with each other...

  • one is bun+elysia
  • another one is nextjs serverless functions

I setup the elysia with trpc, and I also created a small "wrapper" package, that imports trpc router and returns the trpcApi object.
i did some small tests inside the package and things are working fine.

But then I import this "wrapper" into my nextjs, in order to make both APIs talk with each other and when i do that I get the error below (during build time)

../../node_modules/.pnpm/@[email protected]_@[email protected][email protected]/node_modules/@elysiajs/trpc/src/index.ts:19:17
Type error: Property 'path' does not exist on type 'ValueError | undefined'.

  17 |         if (check.Check(value)) return value
  18 | 
> 19 |         const { path, message } = [...check.Errors(value)][0]
     |                 ^
  20 | 
  21 |         throw new TRPCError({
  22 |             message: `${message} for ${path}`,
 ELIFECYCLE  Command failed with exit code 1.

I am using PNPM as my package manager, even for the bun project I am usign PNPM and packageManager and BUN just for the runtime

thanks for any help in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.