Skip to main content

Creating a tRPC Route

Ok so now its time for you to do some coding!

I want to create a route with the endpoint:

api/trpc/place.getAllReviewedPlaces

It will be a query with no inputs. Dont worry about filling in the query function parameter for now. Hint, you do not need to create any router or file, you just need to add a procedure to a pre-existing router

Try to create it then open this block to see the solution
// src/server/routers/placeRouter.ts

import { router, publicProcedure, protectedProcedure } from '../trpc';
import { z } from 'zod';
import { db } from '@/db';
import { eq, and, or, sql, countDistinct, inArray } from 'drizzle-orm';
import {
places,
placeSummary,
types,
placesToTypes,
reviews,
} from '@/db/schema';
import { rateLimit } from '@/lib/ratelimit';
import { TRPCError } from '@trpc/server';

const PAGE_SIZE = 20; // Default page size

export const placeRouter = router({
// Optimized bounded search query
searchPlacesByBounds: publicProcedure...,
summary: publicProcedure...,
getAllReviewedPlaces: publicProcedure.query(),
});

Specifically, we added this to the place.ts file at the end of the other predefined routes

getAllReviewedPlaces: publicProcedure.query(),

Lets create a route that just returns hello world. The query function takes a function as a parameter. Whatever that function returns is what the query returns

Complete the query and return a JSON data structure with a data key corresponding to 'hello world'
getAllReviewedPlaces: publicProcedure.query(() => {
return { data: 'Hello, world!' };
}),

if we visit this url:

http://localhost:3000/api/trpc/place.getAllReviewedPlaces

we should see the following JSON

{ "result": { "data": { "data": "Hello, world!" } } }

Now let us actually create a route that will get all the places from our database - and now i need to show you how to query our database.