Skip to content

omar-dulaimi/prisma-joi-generator

Repository files navigation

⚡ Prisma Joi Generator

🚀 Automatically generate Joi schemas from your Prisma schema

Latest Version

Downloads CI Status License

🎯 Zero-config • 🛡️ Type-safe • ⚡ Fast • 🔧 Customizable



💡 Transform your Prisma schema into powerful validation schemas

Automatically generates Joi schemas for all Prisma operations with full TypeScript support

💖 Support This Project

If this tool accelerates your development, consider supporting its growth

GitHub Sponsors

✨ Your sponsorship drives innovation and keeps this project thriving ✨

🚀 Latest Stable Release - Now with Prisma 6 Support!

Stable Release
🎉 Production Ready with Prisma 6 and Modern Tooling Support!

Latest Features

🆙 Prisma 6 Compatibility - Full support for the latest Prisma features:

  • New Prisma Client Generator support for ESM compatibility
  • Enhanced Type Safety with improved TypeScript integration
  • Modern Dependencies updated to latest stable versions

🔧 Enhanced Development Experience - Modern tooling and CI/CD pipeline:

  • Vitest Testing with comprehensive coverage
  • ESLint 9 with latest linting standards
  • Semantic Release for automated versioning

Core Features

🚀 Feature 📦 Version 🎯 Benefit
New Prisma Client 6.12.0+ 🆕 ESM-compatible generator support
Prisma 6.12.0+ 🏃‍♂️ Latest features & performance
Joi 17.13.3+ 🛡️ Enhanced validation & type safety
TypeScript 5.8+ ⚡ Cutting-edge language features
Testing Vitest 3 🧪 Comprehensive coverage
Tooling ESLint 9 🔧 Modern dev experience
Multi-DB All Providers 🗄️ PostgreSQL, MySQL, MongoDB, SQLite+

📦 Installation

# 🚀 Install the latest release
npm install prisma-joi-generator

🔄 Upgrading

The latest stable version maintains full API compatibility. Requirements:

  • Node.js 18+
  • Prisma 6.12.0+
  • Joi 17.13.3+

Simply update your dependencies and re-run npx prisma generate - no code changes needed!

npm update prisma-joi-generator
npx prisma generate

Why Choose Prisma Joi Generator?

Zero Config
Works instantly
Sensible defaults included
Auto Generated
Always in sync
Updates with schema changes
Type Safe
100% TypeScript
Catch errors at compile time
Comprehensive
Full CRUD coverage
All Prisma operations included
Configurable
Highly customizable
Adapt to your needs
Lightweight
Minimal footprint
Fast generation & runtime
Multi Database
All databases
PostgreSQL, MySQL, MongoDB+
Flexible
Your way
Custom paths & options

🚀 Quick Start

Installation

# NPM
npm install prisma-joi-generator

# Yarn
yarn add prisma-joi-generator

# PNPM  
pnpm add prisma-joi-generator

Setup

  1. Star this repo 😉

  2. Add the generator to your Prisma schema:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./generated/schemas"
}
  1. Generate your Joi schemas:
npx prisma generate

🆕 Prisma Client Generator Support

The latest stable version includes full support for both the legacy and new ESM-compatible prisma-client generator introduced in Prisma 6.12.0!

Generator Compatibility

The Joi generator now supports both Prisma client generators:

Legacy Generator (Existing Projects)

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

generator joi {
  provider = "prisma-joi-generator"
  output   = "./generated/schemas"
}

New ESM-Compatible Generator (Prisma 6.12.0+)

generator client {
  provider = "prisma-client"
  output = "./src/generated/client"
  runtime = "nodejs"
  moduleFormat = "esm"
  generatedFileExtension = "ts"
  importFileExtension = "ts"
}

generator joi {
  provider = "prisma-joi-generator"
  output   = "./generated/schemas"
}

Key Benefits of the New Generator

  • 🔗 ESM Compatibility - Full ES Module support
  • 📂 Custom Output Location - Generate client outside node_modules
  • 🔧 Runtime Flexibility - Support for Bun, Deno, Cloudflare Workers
  • ⚡ Better Performance - Optimized code generation
  • 🔮 Future-Ready - Will become the default in Prisma v7

Migration Guide

Existing Projects: No changes needed - continue using prisma-client-js

New Projects: Consider using the new prisma-client generator for modern features

Gradual Migration: Both generators are supported simultaneously during the transition

📋 Generated Output

For the following schema:

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?
  likes     BigInt
}

The generator creates different directory structures based on your configuration:

Grouped Structure (Default)

📁 generated/schemas/
├── 📁 enums/           // Enum validation schemas
│   ├── 📄 PostScalarFieldEnum.schema.ts
│   └── 📄 UserScalarFieldEnum.schema.ts
├── 📁 objects/         // Input type schemas  
│   ├── 📄 UserCreateInput.schema.ts
│   ├── 📄 UserWhereInput.schema.ts
│   └── 📄 PostCreateInput.schema.ts
├── 📄 findManyUser.schema.ts
├── 📄 findUniqueUser.schema.ts
├── 📄 createOneUser.schema.ts
├── 📄 updateOneUser.schema.ts
├── 📄 deleteOneUser.schema.ts
├── 📄 findManyPost.schema.ts
├── 📄 createOnePost.schema.ts
└── 📄 index.ts         // Barrel exports

By-Model Structure

📁 generated/schemas/
├── 📁 enums/           // Shared enums
├── 📁 models/
│   ├── 📁 user/
│   │   ├── 📄 findManyUser.schema.ts
│   │   ├── 📄 createOneUser.schema.ts
│   │   ├── 📁 objects/
│   │   │   ├── 📄 UserCreateInput.schema.ts
│   │   │   └── 📄 UserWhereInput.schema.ts
│   │   └── 📄 index.ts
│   └── 📁 post/
│       ├── 📄 findManyPost.schema.ts
│       ├── 📄 createOnePost.schema.ts
│       ├── 📁 objects/
│       └── 📄 index.ts
└── 📄 index.ts

Flat Structure

📁 generated/schemas/
├── 📄 findManyUser.schema.ts
├── 📄 createOneUser.schema.ts
├── 📄 UserCreateInput.schema.ts
├── 📄 UserWhereInput.schema.ts
├── 📄 PostScalarFieldEnum.schema.ts
├── 📄 findManyPost.schema.ts
├── 📄 createOnePost.schema.ts
└── 📄 index.ts

Version Compatibility

Version Prisma Joi TypeScript Node.js Status
Latest 6.12.0+ 17.13.3+ 5.8+ 18+ Stable - Full Features + Prisma 6 Support
Legacy 4.0.0+ 17.0+ 4.7+ 16+ 📦 Deprecated - Limited Support

Recommendation: Use npm install prisma-joi-generator for the latest stable release with full features and modern tooling.

⚙️ Configuration Options

The Prisma Joi Generator offers powerful configuration options to customize file generation, organization, and filtering according to your project needs.

Core Configuration

Option Description Type Default
output Output directory for generated files string "./generated"

🔧 File Type Filtering

Control which types of validation schemas are generated:

File Type Description Default
create Create operation schemas (createOne, createMany) true
update Update operation schemas (updateOne, updateMany) true
upsert Upsert operation schemas true
find Find operation schemas (findUnique, findFirst, findMany) true
delete Delete operation schemas (deleteOne, deleteMany) true
aggregate Aggregate operation schemas true
groupBy GroupBy operation schemas true
objects Input object schemas (WhereInput, CreateInput, etc.) true
enums Enum validation schemas true
filter Filter and where input schemas true
orderBy OrderBy input schemas true
unchecked Unchecked input schemas (without relations) true

📁 Directory Organization

Configure how generated files are organized:

Strategy Description Structure
grouped Organize by file type (default) schemas/, schemas/objects/, schemas/enums/
flat All files in single directory schemas/
by-model Organize by model name schemas/models/User/, schemas/models/Post/

Basic Configuration Examples

Minimal Setup

generator joi {
  provider = "prisma-joi-generator"
  output   = "./src/schemas"
}

Custom File Types

generator joi {
  provider = "prisma-joi-generator"
  output   = "./generated/validation"
  
  // Only generate create and find operations
  create = "true"
  find = "true"
  update = "false"
  delete = "false"
  objects = "true"
  enums = "true"
}

Flat Directory Structure

generator joi {
  provider = "prisma-joi-generator"
  output   = "./schemas"
  directoryStrategy = "flat"
}

🎯 Common Use Cases

REST API - Minimal Set

Perfect for REST APIs that only need create and read operations:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./src/validation/schemas"
  
  // Only essential operations
  create = "true"
  find = "true"
  update = "false"
  delete = "false"
  upsert = "false"
  aggregate = "false"
  groupBy = "false"
  
  // Required supporting schemas
  objects = "true"
  enums = "true"
}

Full Feature API

Complete validation for complex applications:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./schemas"
  directoryStrategy = "by-model"
  
  // All operations enabled (default behavior)
  create = "true"
  update = "true"
  upsert = "true"
  find = "true"
  delete = "true"
  aggregate = "true"
  groupBy = "true"
  objects = "true"
  enums = "true"
  filter = "true"
  orderBy = "true"
  unchecked = "true"
}

Read-Only API

For analytics dashboards or reporting systems:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./generated/read-schemas"
  
  // Only read operations
  create = "false"
  update = "false"
  delete = "false"
  upsert = "false"
  find = "true"
  aggregate = "true"
  groupBy = "true"
  
  // Supporting schemas for filtering and sorting
  objects = "true"
  enums = "true"
  filter = "true"
  orderBy = "true"
}

GraphQL Integration

Optimized for GraphQL resolvers with custom directory structure:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./src/graphql/validation"
  directoryStrategy = "grouped"
  
  // GraphQL typically needs input validation
  create = "true"
  update = "true"
  find = "true"
  delete = "true"
  objects = "true"
  enums = "true"
  filter = "true"
  
  // GraphQL handles its own aggregation
  aggregate = "false"
  groupBy = "false"
}

📋 Advanced Configuration Reference

Filter Strategy Options

generator joi {
  provider = "prisma-joi-generator"
  
  // Strategy 1: Selective (default) - Use individual flags
  create = "true"
  find = "false"
  
  // Strategy 2: Whitelist - Only generate specified types
  filterStrategy = "whitelist"
  includeTypes = "create,find,objects,enums"
  
  // Strategy 3: Blacklist - Generate all except specified
  filterStrategy = "blacklist"
  excludeTypes = "aggregate,groupBy,unchecked"
}

Directory Customization

generator joi {
  provider = "prisma-joi-generator"
  output   = "./validation"
  
  // Directory structure
  directoryStrategy = "grouped"
  
  // Custom directory names
  baseDirectory = "schemas"
  objectsDirectory = "inputs"
  enumsDirectory = "constants"
  modelsDirectory = "entities"
}

File Naming Patterns

generator joi {
  provider = "prisma-joi-generator"
  
  // Customize file naming patterns
  schemaFilePattern = "{operation}.validation"
  objectFilePattern = "{name}.input"
  enumFilePattern = "{name}.enum"
}

🔄 Migration Guide

Upgrading from Basic to Filtered Generation

Before (v0.1.x):

generator joi {
  provider = "prisma-joi-generator"
  output   = "./schemas"
}

After (v0.2.x+):

generator joi {
  provider = "prisma-joi-generator"
  output   = "./schemas"
  
  // Explicitly enable only needed types for better performance
  create = "true"
  find = "true"
  update = "true"
  delete = "false"    // Skip if not needed
  aggregate = "false" // Skip if not needed
  
  objects = "true"
  enums = "true"
}

Benefits of Migration:

  • 🚀 Faster generation - Only creates needed schemas
  • 📦 Smaller bundle size - Fewer files to import
  • 🎯 Better organization - Clear intent in configuration
  • 🛡️ Type safety - Prevents accidental usage of disabled operations

🔧 Advanced Usage

Model Customizations

Hide specific models from generation:

/// @@Gen.model(hide: true)
model InternalLog {
  id        Int      @id @default(autoincrement())
  message   String
  createdAt DateTime @default(now())
}

Database Provider Support

The generator supports all Prisma database providers:

  • PostgreSQL - Complete support including advanced types
  • MySQL - Full compatibility with all MySQL features
  • MongoDB - Native MongoDB schema generation
  • SQLite - Perfect for development and testing
  • SQL Server - Enterprise-grade support
  • CockroachDB - Distributed database support

📚 Examples

Express.js API Validation

import express from 'express';
import { PostCreateOneSchema, UserFindManySchema } from './generated/schemas';

const app = express();

// Create post with validation
app.post('/posts', async (req, res) => {
  try {
    const { error, value } = PostCreateOneSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ errors: error.details });
    }
    const post = await prisma.post.create(value);
    res.json(post);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Query with validation
app.get('/users', async (req, res) => {
  const { error, value } = UserFindManySchema.validate(req.query);
  if (error) {
    return res.status(400).json({ errors: error.details });
  }
  const users = await prisma.user.findMany(value);
  res.json(users);
});

Next.js API Routes

// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { UserCreateOneSchema } from '../../generated/schemas';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const { error, value } = UserCreateOneSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ error: error.message });
    }
    try {
      const user = await prisma.user.create(value);
      res.status(201).json(user);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
}

Fastify Integration

import Fastify from 'fastify';
import { PostCreateOneSchema, PostFindManySchema } from './generated/schemas';

const fastify = Fastify();

fastify.post('/posts', {
  preHandler: async (request, reply) => {
    const { error } = PostCreateOneSchema.validate(request.body);
    if (error) {
      reply.code(400).send({ error: error.message });
      return;
    }
  }
}, async (request, reply) => {
  const post = await prisma.post.create({ data: request.body });
  return post;
});

🔧 API Reference

Generated Schema Types

The generator creates the following types of schemas:

Operation Schemas

  • Create Operations: ModelCreateOneSchema, ModelCreateManySchema
  • Read Operations: ModelFindManySchema, ModelFindUniqueSchema, ModelFindFirstSchema
  • Update Operations: ModelUpdateOneSchema, ModelUpdateManySchema, ModelUpsertSchema
  • Delete Operations: ModelDeleteOneSchema, ModelDeleteManySchema
  • Aggregate Operations: ModelAggregateSchema, ModelGroupBySchema

Input Object Schemas

  • Create Inputs: ModelCreateInputObjectSchema, ModelCreateNestedInputObjectSchema
  • Update Inputs: ModelUpdateInputObjectSchema, ModelUpdateNestedInputObjectSchema
  • Where Inputs: ModelWhereInputObjectSchema, ModelWhereUniqueInputObjectSchema
  • Order Inputs: ModelOrderByInputObjectSchema

Schema Naming Convention

All generated schemas follow a consistent naming pattern:

{ModelName}{Operation}{Type}Schema

Examples:

  • UserCreateOneSchema - Schema for creating a single user
  • PostFindManyArgsSchema - Schema for finding multiple posts with arguments
  • UserWhereInputObjectSchema - Schema for user where conditions

🔍 Troubleshooting

Latest Version Information

Prisma 6 Compatibility

  • Full support for both prisma-client-js and prisma-client generators
  • Enhanced type safety with modern TypeScript features
  • Improved error messages and debugging experience

Current Requirements

  • Requires Node.js 18+
  • Requires Prisma 6.12.0+ and Joi 17.13.3+
  • All peer dependencies must be compatible

Upgrading to Latest Version

  • Backup your project before upgrading
  • Update all related dependencies (Prisma, Joi, TypeScript)
  • Re-run npx prisma generate after upgrading
  • Test thoroughly in development environment

Common Issues

Generator compatibility errors

  • Ensure you have either prisma-client-js or prisma-client generator in your schema
  • The Joi generator provides clear error messages with examples if no compatible generator is found
  • Both legacy and new generators are supported simultaneously

Error: Cannot find module './generated/schemas'

  • Ensure you've run npx prisma generate after adding the generator
  • Check that your output path is correct

TypeScript errors in generated schemas

  • Make sure all dependencies are installed and up to date
  • Ensure your TypeScript version is 5.8 or higher
  • Verify all Prisma packages are on the same version

Generated schemas not updating

  • Run npx prisma generate after modifying your schema
  • Check that the generator is properly configured in schema.prisma
  • Clear your build cache and regenerate

Joi validation errors

  • Ensure you have Joi 17.13.3+ installed for compatibility
  • Check that your input schemas match your Prisma model types
  • Review Joi documentation for proper validation syntax

Generator fails to run

  • Ensure you have the correct version installed
  • Check that your schema.prisma syntax is valid
  • Verify Node.js version compatibility (18+)
  • Clear node_modules and reinstall dependencies

🔧 Configuration Issues

No files generated with selective filtering

  • Ensure at least one file type is enabled (e.g., create = "true")
  • Check that objects = "true" and enums = "true" are enabled for supporting schemas
  • Verify your configuration syntax uses string values ("true" not true)

Missing operation schemas (createOne, findMany, etc.)

  • Confirm the operation type is enabled in configuration (e.g., create = "true" for createOne schemas)
  • Check that required dependencies are enabled (objects and enums)
  • Ensure your models define the operations you're trying to generate

Directory structure not as expected

  • Verify directoryStrategy is set correctly ("grouped", "flat", or "by-model")
  • Check custom directory names if using directory customization
  • Ensure output path exists and has write permissions

Configuration parsing errors

  • Use string values for boolean flags: create = "true" not create = true
  • Use comma-separated lists for arrays: includeTypes = "create,find,objects"
  • Check that all configuration keys are spelled correctly

Filter strategy not working

// ❌ Wrong: Mixed strategies
generator joi {
  provider = "prisma-joi-generator"
  filterStrategy = "whitelist"
  create = "true"  // Don't mix individual flags with strategies
}

// ✅ Correct: Consistent strategy
generator joi {
  provider = "prisma-joi-generator"
  filterStrategy = "whitelist"
  includeTypes = "create,find,objects,enums"
}

Performance issues with large schemas

  • Enable only needed file types to reduce generation time
  • Use directoryStrategy = "flat" for smaller projects
  • Consider splitting large schemas into multiple generators

TypeScript import errors with filtered schemas

  • Regenerate schemas after changing configuration
  • Update your imports to match the generated file structure
  • Check that index files are generated (generateIndex = "true")

📊 Configuration Validation

To debug configuration issues, you can temporarily enable all types and gradually disable:

generator joi {
  provider = "prisma-joi-generator"
  output   = "./debug-schemas"
  
  // Enable everything first
  create = "true"
  update = "true"
  find = "true"
  delete = "true"
  objects = "true"
  enums = "true"
  
  // Then gradually disable what you don't need
  // aggregate = "false"
  // groupBy = "false"
}

Getting Help

🤝 Contributing

Contributions are welcome! Here's how you can help:

Development Setup

  1. Fork and clone the repository
git clone https://github.com/your-username/prisma-joi-generator.git
cd prisma-joi-generator
  1. Install dependencies
npm install
  1. Run the development build
npm run gen-example
  1. Run tests
npm test

Testing

We have comprehensive tests covering:

  • Unit Tests: Core transformation logic
  • Integration Tests: End-to-end schema generation
  • Multi-Provider Tests: All database providers
  • Performance Tests: Large schema handling

Run specific test suites:

npm run test:basic           // Basic functionality
npm run test:multi           // Multi-provider testing  
npm run test:coverage        // Coverage reports
npm run test:comprehensive   // Full test suite

Contribution Guidelines

  1. Create an issue for bugs or feature requests
  2. Follow the existing code style (ESLint + Prettier)
  3. Add tests for new functionality
  4. Update documentation as needed
  5. Submit a pull request with a clear description

Code Style

We use ESLint and Prettier for consistent code formatting:

npm run lint      // Check and fix linting issues
npm run format    // Format code with Prettier

Release Process

This project uses semantic versioning and automated releases:

  • Patch: Bug fixes and small improvements
  • Minor: New features and enhancements
  • Major: Breaking changes

📄 License

This project is licensed under the MIT License.

🔗 Related Projects

🙏 Acknowledgments




🌟 **Show Your Support** 🌟

GitHub Stars



Stable
v1.0.0
Legacy
v0.2.0

Made with ❤️ by Omar Dulaimi

⚡ Accelerating Prisma development, one schema at a time

About

Prisma 2+ generator to emit Joi schemas from your Prisma schema

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 2

  •  
  •  

Languages