Create an API endpoint
Marblism already generates all the basic API endpoints you would need for each entity in your database:
- findMany
- findUnique
- create
- update
- delete
Marblism uses tRPC. You set up your routes on the server, and then you can call them directly from the front-end. It's super efficient, type-safe and makes the development process much simpler.
Let's see how to add an endpoint that returns the number of likes a tweet has.
1. Define a new route in the server router
/src/server/routers/countTweets.ts
import { z } from 'zod'
import { Trpc } from '@/core/trpc/server'
export const TweetRouter = Trpc.createRouter({
countTweets: Trpc.procedure
.input(z.object({ tweetId: z.string() }))
.mutation(async ({ ctx, input }) => {
check()
const likes = await ctx.prisma.like.findFirst({
where: { tweetId: input.tweetId },
})
return likes.length
}),
})
2. Export your newly created router
src/server/index.tsx
Trpc.createRouter({
ai: AiRouter,
auth: AuthenticationRouter,
billing: BillingRouter,
...
}),
3. Use it in the front-end
const { mutateAsync: getNumberLikes } = Api.Tweet.countLikes.useMutation()
//call await getNumberLikes({tweetId: '123'}) to get the number of likes