Help with type safe trpc fetch call

webdev newbie here. I have a trpc procedure that fetches some json. I want to validate it and have tRPC throw an error if the data isn't structured correctly which i use it. I'm trying to make it type safe but this is the best i can come up with. I'm trying to understand some of the type errors if i do it different. 1. Why do I need to validate the data twice? this code validates the rawData then it validates it again in the .output(). Doesn't this make the .output() code redundant? I'm repeating the same .array() and rowSchema in 2 places. Is there a more maintainable way to write this? 2. The implemetatio of 'unkown' type feels messy. Is there an altenative type you would typically use here? I've tried Row[] but with no joy.
import { z } from "zod";
import { rowSchema, type Row } from "~/schema";

import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";

export const tableRouter = createTRPCRouter({
rowData: publicProcedure.output(z.array(rowSchema)).query(async () => {
const response = await fetch(
"https://www.ag-grid.com/example-assets/space-mission-data.json",
);
const rawData: unknown = await response.json();
const validatedData = rowSchema.array().parse(rawData);
return validatedData;
}),
});
import { z } from "zod";
import { rowSchema, type Row } from "~/schema";

import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";

export const tableRouter = createTRPCRouter({
rowData: publicProcedure.output(z.array(rowSchema)).query(async () => {
const response = await fetch(
"https://www.ag-grid.com/example-assets/space-mission-data.json",
);
const rawData: unknown = await response.json();
const validatedData = rowSchema.array().parse(rawData);
return validatedData;
}),
});
1 Reply
Rigrig
RigrigOP13mo ago
This is something else that seems to work ok.
const data = await response
.json()
.then((json) => rowSchema.array().parse(json));
return data;
const data = await response
.json()
.then((json) => rowSchema.array().parse(json));
return data;
i've also saw this implemented elsewhere but the t3 stack throws eslint error
const data = await response.json().then(rowSchema.array().parse(json)
return data
const data = await response.json().then(rowSchema.array().parse(json)
return data
Note: ChatGPT suggests that both uses of rowSchema.array() and .output(z.array(rowSchema)) are necessary as they validate types at different time - runtime or compile time. I don't quite understand the difference. Is this duplication something I just need to accept? I switched to tRPC to get the infered types and baked in validation
Want results from more Discord servers?
Add your server