Looking to fix my tRPC implementation

NNehilor4/25/2023
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 });
NNehilor4/25/2023
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 };

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 };
NNehilor4/25/2023
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);
});


This is my result:
Nnlucas4/25/2023
You’ve added a prefix on the server but the errors don’t show the prefix
Nnlucas4/25/2023
So you need the prefix on your client
NNehilor4/25/2023
Should be the same prefix @Nick Lucas ? or something different? Sorry I am new on this
Nnlucas4/25/2023
It's just a HTTP URI
Nnlucas4/25/2023
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
Nnlucas4/25/2023
If you host tRPC at one URL, don't be surprised when a different URL returns a 404
NNehilor4/25/2023
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 };

Result:
Nnlucas4/25/2023
What's the actual error code now?
Nnlucas4/25/2023
And is the port you've set actually correct? I don't see that in your API setup
NNehilor4/25/2023
I am getting this:
NNehilor4/25/2023
My app uses 3000
Nnlucas4/25/2023
What port is the API on though?
Nnlucas4/25/2023
the updated code is port 2021, the error says 4000. Something's wrong 😄
NNehilor4/25/2023
Yeah I updated it one sec
NNehilor4/25/2023
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 };
NNehilor4/25/2023
This is where I am not sure
NNehilor4/25/2023
NNehilor4/26/2023
Hi @nlucas sorry for bothering you, please let me know when you have a few mins to help me with this, thanks
Nnlucas4/26/2023
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
Nnlucas4/26/2023
Why not follow an Express tutorial and just try to get a simple rest endpoint going and a simple react spa connect to it?
Nnlucas4/26/2023
Then you can start swapping out parts and add tRPC to the express API
NNehilor4/27/2023
I am following this guide but I am still getting the error: https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/express-server
NNehilor4/27/2023
@Nick Lucas I managed to fix it, thanks so much for the help! it was related with the address:
Server
app.use('/trpc', tRPCConfig);

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