prisma-trpc-shield-generator

0.1.0 • Public • Published

Prisma tRPC Shield Generator

npm version npm HitCount npm

Automatically generate a tRPC Shield from your Prisma Schema. Updates every time npx prisma generate runs.

Buy Me A Coffee

Table of Contents

Supported Prisma Versions

Prisma 4

  • 0.0.0-rc.4 and higher

Prisma 2/3

  • 0.0.0-rc.3 and lower

Installation

Using npm:

 npm install prisma-trpc-shield-generator

Using yarn:

 yarn add prisma-trpc-shield-generator

Usage

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);

Additional Options

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"
}

Package Sidebar

Install

npm i prisma-trpc-shield-generator

Weekly Downloads

598

Version

0.1.0

License

MIT

Unpacked Size

26.9 kB

Total Files

33

Last publish

Collaborators

  • omar-dulaimi