Skip to content

crudsmith – A TypeScript CLI tool that generates complete CRUD APIs (models, controllers, routes) for Node.js + Express + MongoDB from a single JSON schema. Save hours of boilerplate coding by letting crudsmith handle repetitive tasks, so you can focus on building features.

License

Notifications You must be signed in to change notification settings

myselfAbdullah007/crudsmith

Repository files navigation

CrudSmith

A powerful CLI tool that automatically generates TypeScript CRUD files from JSON schema definitions for MongoDB/Mongoose applications.

Features

  • 🚀 Automatic Generation: Generate models, controllers, and routes from JSON schema
  • 📝 TypeScript Support: Full TypeScript typing with interfaces and proper imports
  • 🏗️ Clean Architecture: Follows best practices with separate models, controllers, and routes
  • ESM Syntax: Uses modern ES modules (import/export)
  • 🔧 Flexible Schema: Support for various field types and options

Installation

npm install -g crudsmith

Or use with npx:

npx crudsmith --schema=path/to/schema.json

Usage

Basic Usage

crudsmith --schema=./schema.json

Schema Format

Create a JSON file with your model definition:

{
  "name": "User",
  "fields": {
    "name": {
      "type": "string",
      "required": true
    },
    "email": {
      "type": "string",
      "required": true,
      "unique": true
    },
    "age": {
      "type": "number"
    },
    "isActive": {
      "type": "boolean",
      "default": true
    },
    "createdAt": {
      "type": "date",
      "default": "Date.now"
    }
  }
}

Shorthand Syntax

You can also use shorthand syntax for simple fields:

{
  "name": "User",
  "fields": {
    "name": "string",
    "email": "string",
    "age": "number"
  }
}

Generated Files

The tool creates the following structure:

generated/
├── models/
│   └── User.model.ts
├── controllers/
│   └── User.controller.ts
├── routes/
│   └── User.routes.ts
├── server.ts              # Complete Express server with MongoDB connection
├── package.json           # Project dependencies and scripts
├── .env                   # Environment variables configuration
└── README.md              # Project documentation

Model File (User.model.ts)

import mongoose, { Schema, Document } from "mongoose";

export interface IUser extends Document {
  name: string;
  email: string;
  age?: number;
}

const UserSchema: Schema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  age: { type: Number }
}, {
  timestamps: true
});

export default mongoose.model<IUser>("User", UserSchema);

Controller File (User.controller.ts)

import { Request, Response } from "express";
import User, { IUser } from "../models/User.model.js";

export const createUser = async (req: Request, res: Response) => {
  // Implementation with proper error handling
};

export const getUsers = async (req: Request, res: Response) => {
  // Implementation with proper error handling
};

// ... other CRUD operations

Routes File (User.routes.ts)

import { Router } from "express";
import { 
  createUser, 
  getUsers, 
  getUserById, 
  updateUser, 
  deleteUser 
} from "../controllers/User.controller.js";

const router = Router();

router.post("/", createUser);
router.get("/", getUsers);
router.get("/:id", getUserById);
router.put("/:id", updateUser);
router.delete("/:id", deleteUser);

export default router;

Running the Generated Server

After generating your CRUD files, you can immediately run a complete Express server:

  1. Navigate to the generated directory:

    cd generated
  2. Install dependencies:

    npm install
  3. Set up MongoDB:

    • Local MongoDB: Make sure MongoDB is running locally
    • MongoDB Atlas: Update the MONGODB_URI in .env file
  4. Start the server:

    # Development mode with auto-reload
    npm run dev
    
    # Production mode
    npm start
  5. Test the API:

    # Health check
    curl http://localhost:3000/health
    
    # Create a new record
    curl -X POST http://localhost:3000/api/users \
      -H "Content-Type: application/json" \
      -d '{"name": "John Doe", "email": "john@example.com"}'
    
    # Get all records
    curl http://localhost:3000/api/users

The generated server includes:

  • Express.js with TypeScript support
  • MongoDB connection with Mongoose
  • CORS support for cross-origin requests
  • Environment variables configuration
  • Error handling and validation
  • Health check endpoint
  • Graceful shutdown handling
  • Development and production modes

Field Types

Supported field types:

  • string - String type
  • number - Number type
  • boolean - Boolean type
  • date - Date type
  • array - Array type
  • object - Object type

Field Options

  • required - Makes the field required
  • unique - Adds unique constraint
  • default - Sets default value
  • ref - References another model (for relationships)

Example Schemas

Simple User Schema

{
  "name": "User",
  "fields": {
    "name": "string",
    "email": "string",
    "age": "number"
  }
}

Complex Product Schema

{
  "name": "Product",
  "fields": {
    "name": {
      "type": "string",
      "required": true
    },
    "price": {
      "type": "number",
      "required": true
    },
    "description": "string",
    "category": {
      "type": "string",
      "ref": "Category"
    },
    "inStock": {
      "type": "boolean",
      "default": true
    },
    "tags": {
      "type": "array"
    }
  }
}

Development

Building

npm run build

Development Mode

npm run dev

License

MIT

About

crudsmith – A TypeScript CLI tool that generates complete CRUD APIs (models, controllers, routes) for Node.js + Express + MongoDB from a single JSON schema. Save hours of boilerplate coding by letting crudsmith handle repetitive tasks, so you can focus on building features.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published