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
The ctx
object has access to the database:
-
ctx.database
(protected): This instance is enhanced with the user session using Zenstack. It provides access control based on the current user's permissions. -
ctx.databaseUnprotected
: This is the raw Prisma client instance without any protection or enhancement. -
ctx.session.user
: This is the current logged-in user making the request.
Here is an example that count the number of likes of a specific tweet:
import { z } from 'zod'
import { Trpc } from '@/core/trpc/server'
export const CustomTweetRouter = Trpc.createRouter({
countLikesTweets: Trpc.procedure
.input(z.object({ tweetId: z.string() }))
.mutation(async ({ ctx, input }) => {
console.log(`Hello ${ctx.session.user.id}`)
const likes = await ctx.database.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