Skip to content

Instantly share code, notes, and snippets.

@zachlankton
Last active December 1, 2022 12:52
Show Gist options
  • Save zachlankton/e0eee693b543ad894c51dcba2c686e4d to your computer and use it in GitHub Desktop.
Save zachlankton/e0eee693b543ad894c51dcba2c686e4d to your computer and use it in GitHub Desktop.
Bare Minumum Prisma Generator Code

Prisma Generator

Bare Minumum Prisma Generator Code

This gist gives you quickest way to get started creating your own prisma generators in your own projects.

If you want to get a little more fancy/advanced and package your generator for the community check out: https://github.com/YassinEldeeb/create-prisma-generator

  • Create the file below in your prisma folder.
  • Make sure to make this file executable
    • chmod +x generator-crud.ts
  • Will need ts-node installed globally
    • Alternatively could use node and *.mjs extension

prisma/generator-crud.ts

#!/usr/bin/env ts-node

import { generatorHandler, GeneratorOptions } from '@prisma/generator-helper';
import { logger } from '@prisma/sdk';
const GENERATOR_NAME = 'generator-crud';
generatorHandler({
  onManifest() {
    logger.info(`${GENERATOR_NAME}:Registered`);
    return {
      version: '1.0',
      defaultOutput: '../generated',
      prettyName: GENERATOR_NAME,
    };
  },
  onGenerate: async (options: GeneratorOptions) => {
    console.log('DATAMODEL', options.dmmf.datamodel);
    console.log('FIELDS', options.dmmf.datamodel.models[0].fields);
  },
});

The above generator does not actually generate any output, just console logs out the primary inputs that you would use for generating whatever you want! Your imagination is the only limit.

Then use the generator in your prisma.schema

prisma/prisma.schema

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

generator crud {
  // provider is basically a path pointer to an executable
  provider = "./prisma/generator-crud.ts"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

/// @skipCrud()
/// @genPath(./src/users)
model Users {
  /// @IsOptional()
  id Int @id @default(autoincrement())

  /// @IsDefined()
  /// @IsEmail()
  email String @unique

  /// @IsString()
  name String?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment