Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
2 replies
Rig

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;
  }),
});
Was this page helpful?