ultimate-crud
Version: 
Ultimate dynamic CRUD API generator with REST, GraphQL, OpenAPI support and association handling for Node.js/Express/Sequelize
409 lines (346 loc) β’ 8.83 kB
Markdown
# Ultimate CRUD
π **Ultimate dynamic CRUD API generator with REST, GraphQL, OpenAPI support and association handling for Node.js/Express/Sequelize**
Ultimate CRUD is a powerful library that automatically generates complete CRUD APIs (both REST and GraphQL) from your database schema using just configuration files. No more boilerplate code - define your entities, associations, and custom response messages, and get a fully functional API instantly.
## β¨ Features
- π₯ **Dynamic CRUD APIs** - Auto-generate REST and GraphQL endpoints
- ποΈ **Multi-Database Support** - MySQL, PostgreSQL, SQLite support via Sequelize
- π **Smart Associations** - Automatic relationship detection + manual configuration
- π **OpenAPI/Swagger** - Auto-generated API documentation
- π― **Custom Responses** - Configurable response messages and error codes
- ποΈ **Views & Procedures** - Support for database views and stored procedures
- π **TypeScript Ready** - Full TypeScript support (coming soon)
- β‘ **Zero Boilerplate** - Configuration over code approach
## π¦ Installation
```bash
npm install ultimate-crud
```
## π Quick Start
### 1. Basic Setup
```javascript
const express = require('express');
const { Sequelize } = require('sequelize');
const UltimateCrud = require('ultimate-crud');
const app = express();
// Initialize Sequelize
const sequelize = new Sequelize({
  dialect: 'mysql', // or 'postgres', 'sqlite'
  host: 'localhost',
  database: 'your_database',
  username: 'your_username',
  password: 'your_password'
});
// Define your entities configuration
const entities = [
  {
    name: 'users',
    type: 'table',
    route: '/api/users',
    responseMessages: {
      200: 'Users retrieved successfully',
      201: 'User created successfully',
      404: 'User not found',
      500: 'Internal server error'
    }
  },
  {
    name: 'posts',
    type: 'table',
    route: '/api/posts',
    associations: [
      {
        type: 'belongsTo',
        target: 'users',
        foreignKey: 'userId',
        as: 'author'
      }
    ]
  }
];
// Initialize Ultimate CRUD
const ultimateCrud = UltimateCrud.create({
  app,
  sequelize,
  entities,
  enableGraphQL: true,
  enableRest: true,
  enableOpenAPI: true
});
// Start the API
(async () => {
  await ultimateCrud.initialize();
  
  app.listen(3000, () => {
    console.log('π Server running on http://localhost:3000');
    console.log('π GraphQL Playground: http://localhost:3000/graphql');
    console.log('π OpenAPI Spec: http://localhost:3000/openapi.json');
  });
})();
```
### 2. Generated API Endpoints
After setup, you automatically get:
**REST Endpoints:**
- `GET /api/users` - Get all users
- `POST /api/users` - Create user
- `GET /api/users/:id` - Get user by ID
- `PUT /api/users/:id` - Update user
- `DELETE /api/users/:id` - Delete user
**GraphQL Endpoints:**
- `http://localhost:3000/graphql` - GraphQL endpoint with GraphiQL interface
**OpenAPI Documentation:**
- `http://localhost:3000/openapi.json` - Auto-generated OpenAPI spec
## π Configuration Guide
### Entity Types
#### 1. Tables (Full CRUD)
```javascript
{
  name: 'products',
  type: 'table',
  route: '/api/products',
  schema: 'public', // Optional for PostgreSQL
  responseMessages: {
    200: 'Success',
    201: 'Product created',
    400: 'Invalid data',
    404: 'Product not found',
    500: 'Server error'
  }
}
```
#### 2. Views (Read-only)
```javascript
{
  name: 'user_stats',
  type: 'view',
  route: '/api/stats/users',
  responseMessages: {
    200: 'Statistics retrieved successfully'
  }
}
```
#### 3. Custom Queries
```javascript
{
  name: 'popular_posts',
  type: 'query',
  route: '/api/posts/popular',
  sql: 'SELECT * FROM posts WHERE views > 1000 ORDER BY views DESC',
  responseMessages: {
    200: 'Popular posts retrieved'
  }
}
```
#### 4. Stored Procedures
```javascript
{
  name: 'user_report',
  type: 'procedure',
  route: '/api/reports/users',
  procedure: 'generate_user_report',
  responseMessages: {
    200: 'Report generated successfully'
  }
}
```
### Associations Configuration
```javascript
{
  name: 'posts',
  type: 'table',
  route: '/api/posts',
  associations: [
    {
      type: 'belongsTo',
      target: 'users',
      foreignKey: 'userId',
      targetKey: 'id',
      as: 'author'
    },
    {
      type: 'hasMany',
      target: 'comments',
      foreignKey: 'postId',
      sourceKey: 'id',
      as: 'comments'
    }
  ]
}
```
**Association Types:**
- `belongsTo` - Many-to-one relationship
- `hasMany` - One-to-many relationship
- `hasOne` - One-to-one relationship
## π οΈ Advanced Usage
### Custom Configuration Options
```javascript
const ultimateCrud = UltimateCrud.create({
  app,
  sequelize,
  entities,
  
  // Feature toggles
  enableGraphQL: true,
  enableRest: true,
  enableOpenAPI: true,
  
  // Custom paths
  graphqlPath: '/graphql',
  openapiPath: '/docs/openapi.json',
  
  // Database options
  syncDatabase: true, // Auto-sync database schema
  
  // Additional options
  cors: true,
  logging: true
});
```
### Using Individual Routers
```javascript
const { createCrudRouter, defineModelFromTable } = require('ultimate-crud');
// Create custom router for specific model
const User = await UltimateCrud.defineModelFromTable(sequelize, 'users');
const userRouter = UltimateCrud.createCrudRouter(User, {
  responseMessages: {
    200: 'Success',
    404: 'User not found'
  }
});
app.use('/api/users', userRouter);
```
## π API Response Format
All API responses follow a consistent format:
```json
{
  "message": "Success message",
  "data": {
    // Your data here
  }
}
```
Error responses:
```json
{
  "error": "Error message",
  "details": "Detailed error information"
}
```
## ποΈ Database Support
| Database | Supported | Notes |
|----------|-----------|-------|
| MySQL | β
 | Full support |
| PostgreSQL | β
 | Full support with schemas |
| SQLite | β
 | Full support |
| MariaDB | β
 | Via MySQL driver |
| SQL Server | β³ | Coming soon |
## π Examples
### Complete Blog API Example
```javascript
const entities = [
  {
    name: 'users',
    type: 'table',
    route: '/api/users',
    responseMessages: {
      200: 'Users retrieved successfully',
      201: 'User created successfully'
    }
  },
  {
    name: 'categories',
    type: 'table',
    route: '/api/categories'
  },
  {
    name: 'posts',
    type: 'table',
    route: '/api/posts',
    associations: [
      {
        type: 'belongsTo',
        target: 'users',
        foreignKey: 'authorId',
        as: 'author'
      },
      {
        type: 'belongsTo',
        target: 'categories',
        foreignKey: 'categoryId',
        as: 'category'
      },
      {
        type: 'hasMany',
        target: 'comments',
        foreignKey: 'postId',
        as: 'comments'
      }
    ]
  },
  {
    name: 'comments',
    type: 'table',
    route: '/api/comments',
    associations: [
      {
        type: 'belongsTo',
        target: 'posts',
        foreignKey: 'postId',
        as: 'post'
      },
      {
        type: 'belongsTo',
        target: 'users',
        foreignKey: 'userId',
        as: 'user'
      }
    ]
  },
  {
    name: 'post_stats',
    type: 'view',
    route: '/api/stats/posts'
  },
  {
    name: 'trending_posts',
    type: 'query',
    route: '/api/posts/trending',
    sql: `
      SELECT p.*, u.username as author_name, COUNT(c.id) as comment_count 
      FROM posts p 
      LEFT JOIN users u ON p.authorId = u.id 
      LEFT JOIN comments c ON p.id = c.postId 
      WHERE p.createdAt > DATE_SUB(NOW(), INTERVAL 7 DAY)
      GROUP BY p.id 
      ORDER BY comment_count DESC, p.views DESC 
      LIMIT 10
    `
  }
];
```
## π§ Development
### Running Tests
```bash
npm test
```
### Building
```bash
npm run build
```
## π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## π License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## πββοΈ Support
- π§ Email: support@ultimate-crud.dev
- π Issues: [GitHub Issues](https://github.com/yourusername/ultimate-crud/issues)
- π¬ Discussions: [GitHub Discussions](https://github.com/yourusername/ultimate-crud/discussions)
## πΊοΈ Roadmap
- [ ] TypeScript definitions
- [ ] Built-in authentication/authorization
- [ ] Rate limiting
- [ ] Caching support
- [ ] Real-time subscriptions
- [ ] CLI tool for scaffolding
- [ ] Admin dashboard
- [ ] Plugin system
---
Made with β€οΈ by the Ultimate CRUD team