Nehilor
Nehilor16mo ago

Looking to fix my tRPC implementation

Hi guys I am looking for some help implementing tRPC in my current project, I have 3 files that need to be reviewed I think I almost have it but for some reason I am getting some errors. My goal is to replace the restful API endpoints and instead use tRPC. My first file is: src/server/app.ts Content:
import {
addContextHandler,
finalize,
initialize,
logger,
} from '@core-ui/service';
import * as dotenv from 'dotenv';
import express from 'express';
import { resolve } from 'path';
import 'reflect-metadata';
import { tRPCConfig } from './tRPC';

/* Refresh the token every 5 minutes */
dotenv.config();
export const app = express();

initialize({
app,
});

addContextHandler(app);

app.use('/lib', express.static(resolve('dist/lib'), {}));

app.use('/trpc', tRPCConfig);
logger.info('Current env = ${process.env.NODE_ENV}');
finalize({ app });
import {
addContextHandler,
finalize,
initialize,
logger,
} from '@core-ui/service';
import * as dotenv from 'dotenv';
import express from 'express';
import { resolve } from 'path';
import 'reflect-metadata';
import { tRPCConfig } from './tRPC';

/* Refresh the token every 5 minutes */
dotenv.config();
export const app = express();

initialize({
app,
});

addContextHandler(app);

app.use('/lib', express.static(resolve('dist/lib'), {}));

app.use('/trpc', tRPCConfig);
logger.info('Current env = ${process.env.NODE_ENV}');
finalize({ app });
15 Replies
Nehilor
Nehilor16mo ago
Second file: src/server/tRPC/index.ts Content:
import { inferAsyncReturnType, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import config from 'config';
import { z } from 'zod';

const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => {
return {
req,
res,
};
};

type Context = inferAsyncReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();

const { router } = t;
const publicProcedure = t.procedure;

const alertsRouter = router({
featureHealthAlerts: publicProcedure
.input(
z.object({
serviceAlias: z.string().nullish(),
}),
)
.query(async ({ input }) => {
try {
const serviceAlias = input.serviceAlias ?? 'kong';
const baseURL: unknown = config.get(
`coreUI.service.serviceProxies.${serviceAlias}.baseURL`,
);
const response: any = await fetch(`${baseURL}`);
return response;
} catch (error: any) {
throw new Error(error?.message);
}
}),
});

const appRouter = router({
alerts: alertsRouter,
});

export type AppRouter = typeof appRouter;

const tRPCConfig = trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
onError({ error }) {
console.error('Something went wrong', error);
},
batching: {
enabled: true,
},
});

export { tRPCConfig };
import { inferAsyncReturnType, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import config from 'config';
import { z } from 'zod';

const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => {
return {
req,
res,
};
};

type Context = inferAsyncReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();

const { router } = t;
const publicProcedure = t.procedure;

const alertsRouter = router({
featureHealthAlerts: publicProcedure
.input(
z.object({
serviceAlias: z.string().nullish(),
}),
)
.query(async ({ input }) => {
try {
const serviceAlias = input.serviceAlias ?? 'kong';
const baseURL: unknown = config.get(
`coreUI.service.serviceProxies.${serviceAlias}.baseURL`,
);
const response: any = await fetch(`${baseURL}`);
return response;
} catch (error: any) {
throw new Error(error?.message);
}
}),
});

const appRouter = router({
alerts: alertsRouter,
});

export type AppRouter = typeof appRouter;

const tRPCConfig = trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
onError({ error }) {
console.error('Something went wrong', error);
},
batching: {
enabled: true,
},
});

export { tRPCConfig };
Third file: src/client/tRPC/index.ts Content:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `/`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `/`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
Whats my goal? I would like to get results using this query for example:
import { client } from '../../tRPC';
const test = client.alerts.featureHealthAlerts.query({ serviceAlias: 'kong' });
test.then(data => {
console.log('data => ', data);
});
import { client } from '../../tRPC';
const test = client.alerts.featureHealthAlerts.query({ serviceAlias: 'kong' });
test.then(data => {
console.log('data => ', data);
});
This is my result:
Nick
Nick16mo ago
You’ve added a prefix on the server but the errors don’t show the prefix So you need the prefix on your client
Nehilor
Nehilor16mo ago
Should be the same prefix @Nick Lucas ? or something different? Sorry I am new on this
Nick
Nick16mo ago
It's just a HTTP URI You wouldn't take out a rental agreement at 231 Spooner Street and then be surprised when all your stuff isn't in 234 Spooner Street. It's a different location If you host tRPC at one URL, don't be surprised when a different URL returns a 404
Nehilor
Nehilor16mo ago
Ok I have added this: src/client/tRPC/index.ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `http://localhost:2021/trpc`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = `http://localhost:2021/trpc`;
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
Result:
Nick
Nick16mo ago
What's the actual error code now? And is the port you've set actually correct? I don't see that in your API setup
Nehilor
Nehilor16mo ago
I am getting this:
Nehilor
Nehilor16mo ago
My app uses 3000
Nick
Nick16mo ago
What port is the API on though? the updated code is port 2021, the error says 4000. Something's wrong 😄
Nehilor
Nehilor16mo ago
Yeah I updated it one sec My app works on this port: https://localhost.sparkcognition.com:3000/ I mean reactjs, so should I use this config:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = 'https://localhost.sparkcognition.com:3000';

const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { AppRouter } from '../../server/tRPC';

const url = 'https://localhost.sparkcognition.com:3000';

const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url,
}),
],
});

export { client };
This is where I am not sure
Nehilor
Nehilor16mo ago
Nehilor
Nehilor16mo ago
Hi @nlucas sorry for bothering you, please let me know when you have a few mins to help me with this, thanks
Nick
Nick16mo ago
This strikes me as needing to go back to basics a little. Setting a URL on both sides isn’t that hard, but throwing tRPC and next into the mix isn’t helping you Why not follow an Express tutorial and just try to get a simple rest endpoint going and a simple react spa connect to it? Then you can start swapping out parts and add tRPC to the express API
Nehilor
Nehilor16mo ago
I am following this guide but I am still getting the error: https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/express-server
CodeSandbox
@examples/express-server - CodeSandbox
@examples/express-server using @trpc/client, @trpc/react-query, @trpc/server, express, zod
Nehilor
Nehilor16mo ago
@Nick Lucas I managed to fix it, thanks so much for the help! it was related with the address: Server
app.use('/trpc', tRPCConfig);
app.use('/trpc', tRPCConfig);
Client
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: '/trpc',
}),
],
});
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: '/trpc',
}),
],
});