Skip to content

omar-dulaimi/prisma-json-server-generator

Repository files navigation

Prisma JSON Server Generator Logo

πŸš€ Prisma JSON Server Generator

Transform your Prisma schema into a fully functional REST API in seconds

npm version npm downloads GitHub stars License GitHub Sponsors

Quick Start β€’ New Features β€’ Examples β€’ Report Bug β€’ Request Feature


🎯 Why Choose This Generator?

πŸ”΄ Before (Manual Setup) 🟒 After (This Generator)
πŸ“ Create mock data manually πŸš€ npx prisma generate
✍️ Write JSON files by hand ⚑ json-server --watch db.json
πŸ”§ Set up json-server manually
πŸ”„ Maintain data consistency
πŸ“‹ Update when schema changes
❌ Time consuming βœ… 2 commands to full REST API
❌ Error prone βœ… Realistic data with faker.js
❌ Hard to maintain βœ… Auto-sync with schema changes
❌ Inconsistent data βœ… Customizable data patterns

πŸš€ Quick Start

Get a fully functional REST API running in under 2 minutes:

1️⃣ Install

npm install prisma-json-server-generator --save-dev
npm install -g json-server

2️⃣ Add to your Prisma schema

generator json_server {
  provider = "prisma-json-server-generator"
}

3️⃣ Generate & Launch

npx prisma generate        # Generate data
json-server --watch db.json --port 3001   # Launch API

4️⃣ Start Building! πŸŽ‰

Your REST API is now live at http://localhost:3001

  • GET /users - List all users
  • GET /posts - List all posts
  • POST /users - Create user
  • Full CRUD operations available!

πŸ†• New in v0.3.0

🎭 Custom Faker Patterns β€’ 🎯 Data Volume Control β€’ 🌱 Seed Data Support

🎭 Custom Patterns

{
  "customPatterns": {
    "User.email": "{{internet.email}}",
    "Product.price": "{{commerce.price}}"
  }
}

Generate realistic data with 50+ faker patterns

🎯 Volume Control

{
  "recordCounts": {
    "User": 100,
    "Product": 500,
    "Order": 1000
  }
}

Control exactly how much data you need

🌱 Seed Data

// seeds/admins.json
[{
  "id": 1,
  "role": "admin",
  "email": "[email protected]"
}]

Load real data then generate additional records


✨ Supported Prisma Versions

Prisma Version Generator Version Status
6.x (Latest) 0.3.0+ βœ… Fully Supported
5.x 0.2.5+ βœ… Compatible
4.x 0.2.0 - 0.2.4 ⚠️ Legacy
2.x/3.x 0.1.2 and lower ❌ Deprecated

πŸ“¦ Installation

πŸ“‹ Choose your package manager
# npm
npm install prisma-json-server-generator --save-dev

# yarn
yarn add prisma-json-server-generator --dev

# pnpm
pnpm add -D prisma-json-server-generator

Don't forget json-server:

npm install -g json-server

πŸ”§ Advanced Configuration

πŸ’ͺ Power User Setup

Create prisma/json-server-config.json:

{
  "outputFileName": "api-data.json",
  "recordCounts": {
    "User": 50,
    "Product": 200,
    "Category": 10,
    "Order": 300
  },
  "customPatterns": {
    "User.email": "{{internet.email}}",
    "User.firstName": "{{person.firstName}}",
    "User.lastName": "{{person.lastName}}",
    "User.avatar": "{{image.avatar}}",
    "Product.name": "{{commerce.productName}}",
    "Product.price": "{{commerce.price}}",
    "Product.description": "{{commerce.productDescription}}",
    "Category.name": "{{commerce.department}}",
    "Order.status": "{{helpers.arrayElement(['pending', 'shipped', 'delivered'])}}"
  },
  "seedData": {
    "enabled": true,
    "seedDataPath": "./seeds/",
    "generateAdditionalRecords": true
  }
}

Update your schema:

generator json_server {
  provider = "prisma-json-server-generator"
  config   = "./prisma/json-server-config.json"
}

🎨 Popular Faker Patterns

πŸ‘€ Person Data
{
  "User.firstName": "{{person.firstName}}",
  "User.lastName": "{{person.lastName}}",
  "User.fullName": "{{person.fullName}}",
  "User.jobTitle": "{{person.jobTitle}}",
  "User.bio": "{{person.bio}}"
}
🌐 Internet & Contact
{
  "User.email": "{{internet.email}}",
  "User.username": "{{internet.userName}}",
  "User.website": "{{internet.url}}",
  "User.phone": "{{phone.number}}"
}
πŸ›οΈ E-commerce
{
  "Product.name": "{{commerce.productName}}",
  "Product.price": "{{commerce.price}}",
  "Product.department": "{{commerce.department}}",
  "Product.material": "{{commerce.productMaterial}}"
}
πŸ“ Location
{
  "Address.street": "{{location.streetAddress}}",
  "Address.city": "{{location.city}}",
  "Address.country": "{{location.country}}",
  "Address.zipCode": "{{location.zipCode}}"
}

🌱 Seed Data Example

Setting up seed data

1. Create seed files:

seeds/
β”œβ”€β”€ users.json        # Admin users, test accounts
β”œβ”€β”€ categories.json   # Product categories  
└── settings.json     # App configuration

2. Example seed file (seeds/users.json):

[
  {
    "id": 1,
    "email": "[email protected]",
    "firstName": "Admin",
    "lastName": "User",
    "role": "ADMIN"
  },
  {
    "id": 2,
    "email": "[email protected]", 
    "firstName": "Demo",
    "lastName": "User",
    "role": "USER"
  }
]

3. Configure in your JSON config:

{
  "seedData": {
    "enabled": true,
    "seedDataPath": "./seeds/",
    "generateAdditionalRecords": true
  },
  "recordCounts": {
    "User": 25  // Will generate 23 more (25 - 2 seeds)
  }
}

πŸ§ͺ Testing

This project uses Vitest for lightning-fast testing:

# Run tests in watch mode
npm test

# Run tests once  
npm run test:run

# Generate coverage report
npm run test:coverage

Test Coverage:

  • βœ… Configuration validation
  • βœ… Faker pattern evaluation
  • βœ… Seed data loading
  • βœ… Record generation logic
  • βœ… Error handling

πŸ› οΈ Generator Options

In schema.prisma:

Option Description Type Default
output Output directory string ./generated
config External config file path string null
generator json_server {
  provider = "prisma-json-server-generator"
  output   = "./api-data"
  config   = "./my-config.json" 
}

In external config file:

Option Description Type Default
outputFileName Generated JSON filename string db.json
recordCounts Records per model Record<string,number> {}
customPatterns Faker patterns Record<string,string> {}
seedData Seed configuration object {}

🎨 Real-World Examples

πŸͺ E-commerce Store

Schema:

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  firstName String
  lastName  String
  orders    Order[]
}

model Product {
  id          Int      @id @default(autoincrement())
  name        String
  price       Float
  categoryId  Int
  category    Category @relation(fields: [categoryId], references: [id])
}

model Category {
  id       Int       @id @default(autoincrement())
  name     String
  products Product[]
}

model Order {
  id     Int  @id @default(autoincrement())
  userId Int
  user   User @relation(fields: [userId], references: [id])
  total  Float
}

Configuration:

{
  "recordCounts": {
    "User": 100,
    "Product": 500, 
    "Category": 12,
    "Order": 1000
  },
  "customPatterns": {
    "User.email": "{{internet.email}}",
    "User.firstName": "{{person.firstName}}",
    "User.lastName": "{{person.lastName}}",
    "Product.name": "{{commerce.productName}}",
    "Product.price": "{{commerce.price}}",
    "Category.name": "{{commerce.department}}"
  }
}

Generated API endpoints:

  • GET /users - Customer list
  • GET /products - Product catalog
  • GET /categories - Product categories
  • GET /orders - Order history
  • Full CRUD on all resources
πŸ“± Social Media App

Schema:

model User {
  id       Int    @id @default(autoincrement())
  username String @unique
  email    String @unique
  avatar   String?
  bio      String?
  posts    Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String
  imageUrl  String?
  likes     Int      @default(0)
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
}

Configuration:

{
  "recordCounts": {
    "User": 200,
    "Post": 1000
  },
  "customPatterns": {
    "User.username": "{{internet.userName}}",
    "User.email": "{{internet.email}}",
    "User.avatar": "{{image.avatar}}",
    "User.bio": "{{lorem.sentence}}",
    "Post.title": "{{lorem.sentence}}",
    "Post.content": "{{lorem.paragraphs}}",
    "Post.imageUrl": "{{image.url}}",
    "Post.likes": "{{number.int({'min': 0, 'max': 500})}}"
  }
}

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with ❀️ by Omar Dulaimi

⭐ Don't forget to star this repo if you found it useful! ⭐

About

Prisma 2+ generator to emit a JSON file that can be run with json-server

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published