tRPC and existing api

Hello, I have external API that I use on my project. I need to hide my api key so I need to create api routes as wrapper (to run serverside). Could I just use trpc for it instead of the normal api route way on nextjs? So on trpc get external api and return result and client fetches from trpc
7 Replies
Samathingamajig
yes
cje
cje2y ago
thats an excellent use case for trpc
rocawear
rocawear2y ago
Is there any examples for it, I am thinking about the typing. Do I need to use zod for input and output validation to get typings work correctly? So on my procedure I use axios to fetch my api and then its untyped. Then I parse it to get typings or somehow type output. Is this correct idea?
Samathingamajig
that idea is good what does axios offer for this?
rocawear
rocawear2y ago
https://trpc.io/docs/output-validation this seems to be the way. Axios to fetch data instead of default fetch
Output Validation | tRPC
tRPC gives you automatic type-safety of outputs without the need of adding a validator; however, it can be useful at times to strictly define the output type in order to prevent sensitive data of being leaked.
Samathingamajig
yeah i get that you're using axios instead of fetch, but im wondering why. i haven't used axios much but i havent seen anything it offers that fetch doesn't, cuz it used to just be a convenient wrapper around XMLHttpRequest before fetch came into existence the only thing i know of is that you can get percentage updates on huge file download/uploads i think
rocawear
rocawear2y ago
If somebody is also interested I managed to do it like this and using it on client with types:
import { z } from "zod";
import axios from "axios";

import { router, publicProcedure } from "../trpc";

export const productsRouter = router({
all: publicProcedure
.output(
z.array(
z.object({
id: z.number(),
title: z.string(),
price: z.number(),
description: z.string(),
category: z.string(),
image: z.string(),
rating: z.object({
rate: z.number(),
count: z.number(),
}),
})
)
)
.query(async () => {
const { data } = await axios.get("https://fakestoreapi.com/products");
return data;
}),
});
import { z } from "zod";
import axios from "axios";

import { router, publicProcedure } from "../trpc";

export const productsRouter = router({
all: publicProcedure
.output(
z.array(
z.object({
id: z.number(),
title: z.string(),
price: z.number(),
description: z.string(),
category: z.string(),
image: z.string(),
rating: z.object({
rate: z.number(),
count: z.number(),
}),
})
)
)
.query(async () => {
const { data } = await axios.get("https://fakestoreapi.com/products");
return data;
}),
});
const { data: products, isLoading, isError } = trpc.products.all.useQuery();
const { data: products, isLoading, isError } = trpc.products.all.useQuery();
Want results from more Discord servers?
Add your server