Automatically generate a tRPC Shield from your Prisma Schema. Updates every time npx prisma generate
runs.
- 0.0.0-rc.4 and higher
- 0.0.0-rc.3 and lower
Using npm:
npm install prisma-trpc-shield-generator
Using yarn:
yarn add prisma-trpc-shield-generator
1- Star this repo 😉
2- Install tRPC Shield
npm install trpc-shield
3- Add the generator to your Prisma schema
generator trpc_shield {
provider = "prisma-trpc-shield-generator"
contextPath = "../src/context"
}
4- Make sure you have a valid Context
file, as specified in contextPath
option. The official Context for reference.
5- Running npx prisma generate
for the following schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
will generate the following shield
import { shield, allow } from 'trpc-shield';
import { Context } from '../../../context';
export const permissions = shield<Context>({
query: {
aggregatePost: allow,
aggregateUser: allow,
findFirstPost: allow,
findFirstUser: allow,
findManyPost: allow,
findManyUser: allow,
findUniquePost: allow,
findUniqueUser: allow,
groupByPost: allow,
groupByUser: allow,
},
mutation: {
createOnePost: allow,
createOneUser: allow,
deleteManyPost: allow,
deleteManyUser: allow,
deleteOnePost: allow,
deleteOneUser: allow,
updateManyPost: allow,
updateManyUser: allow,
updateOnePost: allow,
updateOneUser: allow,
upsertOnePost: allow,
upsertOneUser: allow,
},
});
5- Attach generated shield as a middleware to your top-level procedure
export const permissionsMiddleware = t.middleware(permissions);
export const shieldedProcedure = t.procedure.use(permissionsMiddleware);
Option | Description | Type | Default |
---|---|---|---|
output |
Output directory for the generated tRPC Shield | string |
./generated |
contextPath |
Sets the context path used in your shield and rules | string |
../../../../src/context |
Use additional options in the schema.prisma
generator trpc_shield {
provider = "prisma-trpc-shield-generator"
output = "./shield"
contextPath = "../context"
}