Code Generation Capabilities
Mifty's powerful code generation system automatically creates complete, production-ready modules from your database design. This eliminates hours of boilerplate coding and ensures consistent, high-quality code across your application.
๐ Overviewโ
Mifty provides two main approaches to code generation:
- ๐จ Visual Database Designer โ Auto-generate modules
- ๐ Manual Configuration โ Interactive module creation
Both approaches generate the same comprehensive module structure with all necessary files and patterns.
๐ฏ What Gets Generatedโ
When you generate a module, Mifty creates a complete, production-ready structure:
src/modules/user/
โโโ ๐ controllers/
โ โโโ ๐ user.controller.ts # HTTP request handlers
โโโ ๐ services/
โ โโโ ๐ user.service.ts # Business logic implementation
โ โโโ ๐ interfaces/
โ โโโ ๐ user.service.interface.ts
โโโ ๐ repositories/
โ โโโ ๐ user.repository.ts # Data access layer
โ โโโ ๐ interfaces/
โ โโโ ๐ user.repository.interface.ts
โโโ ๐ entities/
โ โโโ ๐ user.entity.ts # TypeScript type definitions
โโโ ๐ dtos/
โ โโโ ๐ user-response.dto.ts # Response formatting
โโโ ๐ validations/
โ โโโ ๐ user.validation.ts # Input validation schemas
โโโ ๐ routes/
โ โโโ ๐ user.routes.ts # Express route definitions
โโโ ๐ tests/
โ โโโ ๐ user.service.test.ts # Unit tests
โ โโโ ๐ user.controller.test.ts # Controller tests
โโโ ๐ di.ts # Dependency injection setup
๐ Generated Files Overviewโ
| File Type | Purpose | Features |
|---|---|---|
| Controller | HTTP request handling | CRUD operations, validation, error handling |
| Service | Business logic | Domain operations, data transformation |
| Repository | Data access | Database operations, query optimization |
| Entity | Type definitions | Prisma types, DTOs, interfaces |
| Validation | Input validation | Zod schemas, transformation logic |
| Routes | API endpoints | RESTful routes, middleware integration |
| Tests | Quality assurance | Unit tests, integration tests |
| DI | Dependency injection | Service registration, container setup |
๐จ Method 1: Visual Database Designerโ
Step 1: Design Your Databaseโ
# Start the database designer
npm run db-designer
Open http://localhost:3001/ui and visually design your database:
- Add Tables: Click "Add Table" and name your entities
- Define Columns: Add fields with types, constraints, and validations
- Create Relationships: Connect tables with foreign keys
- Save Design: Your design is saved to
src/db.design.ts
Step 2: Generate Modulesโ
# Generate modules from your visual design
npm run generate
Choose option 2 (From db design) and Mifty will:
- โ
Read your
db.design.tsfile - โ Generate modules for each table
- โ Create all relationships and foreign keys
- โ Set up proper validation schemas
- โ Generate complete test suites
Example: Visual Design to Codeโ
Visual Design (src/db.design.ts):
export const dbDesign = {
User: {
columns: {
id: { type: 'String', primary: true, randomUUID: true },
email: { type: 'String', unique: true, nullable: false },
name: { type: 'String', nullable: true },
createdAt: { type: 'DateTime', default: 'now()' }
}
},
Post: {
columns: {
id: { type: 'String', primary: true, randomUUID: true },
title: { type: 'String', nullable: false },
content: { type: 'String', nullable: true },
authorId: { type: 'String', nullable: false },
createdAt: { type: 'DateTime', default: 'now()' }
},
relations: {
author: { type: 'manyToOne', model: 'User', foreignKey: 'authorId' }
}
}
};
Generated Controller (user.controller.ts):
@injectable()
export class UserController extends BaseController<User, UserCreateDto, UserUpdateDto> {
constructor(
@inject('IUserService') private userService: IUserService
) {
super({
service: userService,
responseClass: UserResponse,
createSchema: userValidation.create,
updateSchema: userValidation.update,
searchFields: ['name', 'email'],
defaultInclude: { posts: true }
});
}
}
Generated Service (user.service.ts):
@injectable()
export class UserService extends BaseService<User, UserCreateDto, UserUpdateDto> implements IUserService {
constructor(
@inject('IUserRepository') repository: IUserRepository
) {
super(repository);
}
// Custom business logic methods can be added here
}
Generated Validation (user.validation.ts):
export const createUserSchema = flatToNestedSchema(
z.object({
email: z.string().email(),
name: z.string().optional(),
}),
data => ({
email: data.email,
name: data.name,
})
);
export const userValidation = {
create: createUserSchema,
update: updateUserSchema,
idParam: userIdParamSchema,
search: searchQuerySchema
};
๐ Method 2: Manual Interactive Generationโ
Step 1: Start Interactive Generatorโ
npm run generate
Choose option 1 (Manually) for interactive prompts.
Step 2: Configure Your Moduleโ
The generator will ask you to configure:
๐๏ธ Basic Module Informationโ
Enter module name: product
๐ Fields Configurationโ
Add custom fields? (y/n): y
Field name: title
Field type: string
Is optional? (y/n): n
Add validation rules? (y/n): y
Validation rule: min(3).max(100)
๐ Relationships Configurationโ
Add relationships? (y/n): y
Relationship name: category
Related model: Category
Relationship type: manyToOne
Foreign key: categoryId
๐ฃ๏ธ Routes Configurationโ
Include route: getAll? (y/n): y
Include route: getById? (y/n): y
Include route: create? (y/n): y
Include route: update? (y/n): y
Include route: delete? (y/n): y
Include route: search? (y/n): y
๐งช Testing Configurationโ
Generate service tests? (y/n): y
Generate controller tests? (y/n): y
Generate integration tests? (y/n): y
Step 3: Generated Outputโ
The generator creates all files with your specifications:
// Generated entity with your custom fields
export type Product = Prisma.ProductGetPayload<{
include: {
category: true
}
}>;
// Generated validation with your rules
const createProductSchema = z.object({
title: z.string().min(3).max(100),
categoryId: z.string().uuid(),
});
// Generated routes with your selections
router.get('/product/', productController.findWithPagination);
router.get('/product/search', productController.search);
router.get('/product/:id', productController.getById);
router.post('/product/', productController.create);
router.put('/product/:id', productController.update);
router.delete('/product/:id', productController.delete);
๐ง Advanced Generation Featuresโ
๐ฏ Prisma Integrationโ
Mifty automatically integrates with your Prisma schema:
// Reads existing Prisma models
const getAllPrismaModelNames = (): string[] => {
const schemaContent = fs.readFileSync('src/prisma/schema.prisma', 'utf-8');
const modelMatches = schemaContent.match(/model\s+(\w+)\s*{/g);
return modelMatches.map(match => match.match(/model\s+(\w+)/)[1]);
};
// Generates type-safe entities
export type User = Prisma.UserGetPayload<{
include: {
posts: true,
profile: true
}
}>;
๐ Relationship Handlingโ
Mifty automatically handles complex relationships:
One-to-Many Relationshipsโ
// Generated validation for User -> Posts relationship
const createPostSchema = flatToNestedSchema(
z.object({
title: z.string(),
authorId: z.string().uuid(),
}),
data => ({
title: data.title,
author: { connect: { id: data.authorId } }
})
);
Many-to-Many Relationshipsโ
// Generated validation for User <-> Role relationship
const createUserSchema = flatToNestedSchema(
z.object({
email: z.string().email(),
roleIds: z.array(z.string().uuid()),
}),
data => ({
email: data.email,
roles: { connect: data.roleIds.map(id => ({ id })) }
})
);
๐งช Test Generationโ
Comprehensive test suites are automatically generated:
Unit Testsโ
describe('UserService', () => {
let userService: UserService;
let mockRepository: jest.Mocked<IUserRepository>;
beforeEach(() => {
mockRepository = createMockRepository();
userService = new UserService(mockRepository);
});
describe('create', () => {
it('should create a user successfully', async () => {
const createDto: UserCreateDto = {
email: 'test@example.com',
name: 'Test User'
};
mockRepository.create.mockResolvedValue(mockUser);
const result = await userService.create(createDto);
expect(result).toEqual(mockUser);
expect(mockRepository.create).toHaveBeenCalledWith(createDto);
});
});
});
Integration Testsโ
describe('User Routes', () => {
let app: Application;
beforeAll(async () => {
app = await createTestApp();
});
describe('POST /api/v1/user', () => {
it('should create a new user', async () => {
const userData = {
email: 'test@example.com',
name: 'Test User'
};
const response = await request(app)
.post('/api/v1/user')
.send(userData)
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data.email).toBe(userData.email);
});
});
});
๐จ Customization Optionsโ
๐ง Template Customizationโ
You can customize the generated code by modifying templates in src/scripts/templates/:
// Custom controller template
export const generateControllerTemplate = (name: string, options: any) => {
return `
@injectable()
export class ${pascalCase(name)}Controller extends BaseController {
constructor(
@inject('I${pascalCase(name)}Service') private service: I${pascalCase(name)}Service
) {
super({
service,
responseClass: ${pascalCase(name)}Response,
// Your custom configuration
searchFields: ${JSON.stringify(options.searchFields)},
defaultInclude: ${JSON.stringify(options.defaultInclude)}
});
}
// Add custom methods here
}`;
};
๐ฏ Field Type Mappingโ
Mifty automatically maps database types to TypeScript/Zod types:
| Database Type | TypeScript Type | Zod Validation |
|---|---|---|
String | string | z.string() |
Int | number | z.number().int() |
Float | number | z.number() |
Boolean | boolean | z.boolean() |
DateTime | Date | z.union([z.string(), z.date()]) |
Json | any | z.any() |
Enum | union type | z.enum([...]) |
๐ Validation Transformationโ
Mifty generates smart validation schemas that handle nested relationships:
// Flat input schema for API
const flatSchema = z.object({
title: z.string(),
categoryId: z.string().uuid(),
});
// Transformed to nested Prisma input
const transformedSchema = flatSchema.transform(data => ({
title: data.title,
category: { connect: { id: data.categoryId } }
}));
๐ Generation Commandsโ
Basic Commandsโ
# Interactive generator
npm run generate
# Generate specific module
npm run generate generate-module user
# Generate from database design
npm run generate generate-module auto
Advanced Commandsโ
# Generate with AI assistance
npm run generate generate-ai --module user --type test
# Generate only tests
npm run generate generate-ai --module user --type test
# Generate only documentation
npm run generate generate-ai --module user --type docs
๐ Generated Code Qualityโ
๐ก๏ธ Type Safetyโ
All generated code is fully type-safe:
// Generated with proper Prisma types
export type User = Prisma.UserGetPayload<{
include: { posts: true }
}>;
// Type-safe service methods
async findById(id: string): Promise<User> {
return this.repository.findById(id);
}
๐งช Test Coverageโ
Generated tests provide comprehensive coverage:
- โ Unit Tests: Service and repository logic
- โ Integration Tests: API endpoint testing
- โ Validation Tests: Input validation scenarios
- โ Error Handling: Exception and edge cases
๐ Best Practicesโ
Generated code follows enterprise patterns:
- โ Clean Architecture: Layered separation of concerns
- โ Dependency Injection: Loose coupling and testability
- โ Error Handling: Proper exception management
- โ Validation: Input sanitization and transformation
- โ Documentation: JSDoc comments and type annotations
๐ Regeneration and Updatesโ
Safe Regenerationโ
Mifty supports safe regeneration of modules:
# Regenerate existing module (prompts for confirmation)
npm run generate generate-module user
Incremental Updatesโ
You can regenerate specific parts:
- Update database design in visual designer
- Regenerate entities to reflect schema changes
- Keep custom business logic in services
- Update tests to match new structure
Migration Strategyโ
When updating existing modules:
- Backup custom code before regeneration
- Regenerate base files (entities, repositories)
- Merge custom logic back into services
- Update tests for new functionality
๐ก Pro Tipsโ
๐ฏ Optimization Tipsโ
- Use meaningful names for better generated code
- Design relationships carefully for optimal queries
- Add validation rules during generation for better security
- Generate tests early for better development workflow
๐ง Customization Best Practicesโ
- Extend base classes rather than modifying generated code
- Add custom methods to services for business logic
- Use dependency injection for additional services
- Keep generated files clean and add customizations in separate files
๐ Performance Considerationsโ
- Generated queries are optimized for common use cases
- Pagination is built into all list endpoints
- Search functionality uses database indexes
- Relationships are loaded efficiently with Prisma includes
The code generation system in Mifty eliminates the tedious work of writing boilerplate code while ensuring consistency, type safety, and best practices across your entire application.