Skip to main content

bunjs-architecture

Provides Bun.js clean architecture patterns — routes/controllers/services/repositories, camelCase conventions, Prisma schemas. Use when designing layered Bun.js apps or planning structured workflows.

来源信息

仓库
MadAppGang/magus
最近来源活动
2026年9月7日 04:11
检测到的 SKILL.md 语言
英语
星标
10
分支
4

安装方式

默认使用会先检查来源的 Prompt;你也可以切换为直接命令,或下载本地副本。

检查来源文件

决定是否安装前,请先阅读 SKILL.md,以及 SkillsMP 当前展示的配套文件。

正在显示 SKILL.md

SKILL.md
来源说明 · 只读预览
name
bunjs-architecture
description
Provides Bun.js clean architecture patterns — routes/controllers/services/repositories, camelCase conventions, Prisma schemas. Use when designing layered Bun.js apps or planning structured workflows.
disable-model-invocation
true
# Bun.js Clean Architecture Patterns ## Overview This skill covers layered architecture, clean code patterns, camelCase naming conventions, and structured implementation workflows for Bun.js TypeScript backend applications. Use this skill when building complex, maintainable applications that require strict separation of concerns. **When to use this skill:** - Implementing layered architecture (routes → controllers → services → repositories) - Establishing coding conventions and naming standards - Designing database schemas with Prisma - Creating API endpoint specifications - Planning implementation workflows **See also:** - `${CLAUDE_PLUGIN_ROOT}/knowledge/backend/bunjs.md` - Core Bun patterns, HTTP servers, basic database access - `${CLAUDE_PLUGIN_ROOT}/skills/backend/bunjs-production/SKILL.md` - Production deployment, Docker, AWS, Redis - `${CLAUDE_PLUGIN_ROOT}/knowledge/backend/bunjs-apidog.md` - OpenAPI specifications and Apidog integration ## Clean Architecture Principles ### 1. Layered Architecture **ALWAYS** separate concerns into distinct layers with single responsibilities: ``` ┌─────────────────────────────────────┐ │ Routes Layer │ ← Define API routes, attach middleware │ (src/routes/) │ Map to controllers └──────────────┬──────────────────────┘ │ ┌──────────────▼──────────────────────┐ │ Controllers Layer │ ← Handle HTTP requests/responses │ (src/controllers/) │ Call services, no business logic └──────────────┬──────────────────────┘ │ ┌──────────────▼──────────────────────┐ │ Services Layer │ ← Implement business logic │ (src/services/) │ Orchestrate repositories └──────────────┬──────────────────────┘ No HTTP concerns │ ┌──────────────▼──────────────────────┐ │ Repositories Layer │ ← Encapsulate database access │ (src/database/repositories/) │ Use Prisma, type-safe queries └─────────────────────────────────────┘ No business logic ``` **Critical Rules:** - Controllers NEVER contain business logic (only HTTP handling) - Services NEVER access HTTP context (no `req`, `res`, `Context`) - Repositories are the ONLY layer that touches Prisma/database - Each layer depends only on layers below it ### 2. Dependency Flow ```typescript // ✅ CORRECT: Downward dependency flow Routes → Controllers → Services → Repositories → Database // ❌ WRONG: Upward dependency (service accessing controller) Service imports from Controller // NEVER DO THIS // ❌ WRONG: Skip layers (controller accessing repository directly) Controller → Repository // Should go through Service ``` ### 3. Separation of Concerns | Layer | Responsibilities | Forbidden | |-------|------------------|-----------| | **Routes** | Define endpoints, attach middleware, map to controllers | Business logic, DB access | | **Controllers** | Extract data from HTTP, call services, format responses | Business logic, DB access, validation logic | | **Services** | Business logic, orchestrate operations, manage transactions | HTTP handling, direct DB access | | **Repositories** | Database queries, type-safe Prisma operations | Business logic, HTTP handling | ## camelCase Conventions (CRITICAL) ### Why camelCase Everywhere? **TypeScript-first full-stack development requires ONE naming convention across all layers:** - ✅ Database → Prisma → TypeScript → API → Frontend (1:1 mapping) - ✅ Zero translation layer = zero mapping bugs - ✅ Autocomplete works perfectly everywhere - ✅ Type safety maintained end-to-end **This is non-negotiable for our stack.** ### API Field Naming: camelCase **CRITICAL: All JSON REST API field names MUST use camelCase.** **Why:** - ✅ Native to JavaScript/JSON - No transformation needed - ✅ Industry standard - Google, Microsoft, Facebook, AWS use camelCase - ✅ TypeScript friendly - Direct mapping to interfaces - ✅ OpenAPI/Swagger convention - Standard for API specs - ✅ Auto-generated clients - Expected by code generation tools **Examples:** ```typescript // ✅ CORRECT: camelCase { "userId": "123", "firstName": "John", "lastName": "Doe", "emailAddress": "john@example.com", "createdAt": "2025-01-06T12:00:00Z", "isActive": true, "phoneNumber": "+1234567890" } // ❌ WRONG: snake_case { "user_id": "123", "first_name": "John", "created_at": "2025-01-06T12:00:00Z" } // ❌ WRONG: PascalCase { "UserId": "123", "FirstName": "John" } ``` **Consistent Application:** 1. **Request Bodies**: All fields in camelCase 2. **Response Bodies**: All fields in camelCase 3. **Query Parameters**: Use camelCase (`pageSize`, `sortBy`, `orderBy`) 4. **Zod Schemas**: Define fields in camelCase 5. **TypeScript Interfaces**: Match API camelCase ### Database Naming: camelCase **CRITICAL: All database identifiers (tables, columns, indexes, constraints) use camelCase.** **Why:** - ✅ Stack consistency - TypeScript is our primary language - ✅ Zero translation layer - Database names map 1:1 with TypeScript types - ✅ Reduced complexity - No snake_case ↔ camelCase conversion - ✅ Modern ORM compatibility - Prisma, Drizzle, TypeORM work seamlessly - ✅ Team productivity - Full-stack TypeScript developers think in camelCase **Naming Rules:** **1. Tables:** Singular, camelCase with `@@map()` to plural ```prisma model User { userId String @id // ... @@map("users") // Table name: users } ``` **2. Columns:** camelCase ```prisma userId, firstName, emailAddress, createdAt, isActive ``` **3. Primary Keys:** `{tableName}Id` ```prisma userId // in users table orderId // in orders table productId // in products table ``` **4. Foreign Keys:** Same as referenced primary key ```prisma model Order { orderId String @id userId String // references users.userId user User @relation(fields: [userId], references: [userId]) } ``` **5. Boolean Fields:** Prefix with is/has/can ```prisma isActive, isDeleted, isPublic hasPermission, hasAccess canEdit, canDelete ``` **6. Timestamps:** Consistent suffixes ```prisma createdAt // creation time updatedAt // last modification deletedAt // soft delete time lastLoginAt // specific event times publishedAt verifiedAt ``` **7. Indexes:** `idx{TableName}{ColumnName}` ```prisma @@index([emailAddress], name: "idxUsersEmailAddress") @@index([userId, createdAt], name: "idxOrdersUserIdCreatedAt") ``` **8. Constraints:** ```prisma // Foreign keys (Prisma auto-generates, but can specify) @@index([userId], map: "fkOrdersUserId") // Unique constraints @@unique([emailAddress], name: "unqUsersEmailAddress") ``` ### Prisma Schema Example (Perfect Mapping) ```prisma model User { userId String @id @default(cuid()) emailAddress String @unique firstName String? lastName String? phoneNumber String? isActive Boolean @default(true) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt lastLoginAt DateTime? orders Order[] sessions Session[] @@index([emailAddress], name: "idxUsersEmailAddress") @@index([createdAt], name: "idxUsersCreatedAt") @@map("users") } model Order { orderId String @id @default(cuid()) userId String totalAmount Decimal @db.Decimal(10, 2) orderStatus String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User @relation(fields: [userId], references: [userId]) orderItems OrderItem[] @@index([userId], name: "idxOrdersUserId") @@index([createdAt], name: "idxOrdersCreatedAt") @@map("orders") } model OrderItem { orderItemId String @id @default(cuid()) orderId String productId String quantity Int unitPrice Decimal @db.Decimal(10, 2) order Order @relation(fields: [orderId], references: [orderId]) @@index([orderId], name: "idxOrderItemsOrderId") @@map("orderItems") } ``` ### TypeScript Types (Perfect Match) ```typescript // Exact 1:1 mapping with database and API interface User { userId: string; emailAddress: string; firstName: string | null; lastName: string | null; phoneNumber: string | null; isActive: boolean; createdAt: Date; updatedAt: Date; lastLoginAt: Date | null; } interface Order { orderId: string; userId: string; totalAmount: number; orderStatus: string; createdAt: Date; updatedAt: Date; } ``` ### Benefits of Single Convention **No Translation Needed:** ```typescript // Database column userId // Prisma model userId // TypeScript type userId // API response userId // Frontend state userId // All identical → zero translation → zero bugs ✓ ``` ## Layer Templates ### Route Template ```typescript // src/routes/user.routes.ts import { Hono } from 'hono'; import * as userController from '@/controllers/user.controller'; import { validate, validateQuery } from '@middleware/validator'; import { authenticate, authorize } from '@middleware/auth'; import { createUserSchema, updateUserSchema, getUsersQuerySchema } from '@/schemas/user.schema'; const userRouter = new Hono(); // Public routes userRouter.get('/', validateQuery(getUsersQuerySchema), userController.getUsers); userRouter.get('/:id', userController.getUserById); userRouter.post('/', validate(createUserSchema), userController.createUser); // Protected routes userRouter.patch('/:id', authenticate, validate(updateUserSchema), userController.updateUser); userRouter.delete('/:id', authenticate, authorize('admin'), userController.deleteUser); export default userRouter; ``` ### Controller Template ```typescript // src/controllers/user.controller.ts import type { Context } from 'hono'; import * as userService from '@/services/user.service'; import type { CreateUserDto, UpdateUserDto, GetUsersQuery } from '@/schemas/user.schema'; export const createUser = async (c: Context) => { const data = c.get('validatedData') as CreateUserDto; const user = await userService.createUser(data); return c.json(user, 201); }; export const getUserById = async (c: Context) => { const id = c.req.param('id'); const user = await userService.getUserById(id); return c.json(user); }; export const getUsers = async (c: Context) => { const query = c.get('validatedQuery') as GetUsersQuery; const result = await userService.getUsers(query); return c.json(result); }; export const updateUser = async (c: Context) => { const id = c.req.param('id'); const data = c.get('validatedData') as UpdateUserDto; const user = await userService.updateUser(id, data); return c.json(user); }; export const deleteUser = async (c: Context) => { const id = c.req.param('id'); await userService.deleteUser(id); return c.json({ message: 'User deleted successfully' }); }; ``` **Controller Rules:** - ✅ Extract validated data from context - ✅ Call service layer functions - ✅ Format HTTP responses - ❌ NO business logic - ❌ NO database access - ❌ NO validation logic (use middleware) ### Service Template ```typescript // src/services/user.service.ts import { userRepository } from '@/database/repositories/user.repository'; import { NotFoundError, ConflictError } from '@core/errors'; import type { CreateUserDto, UpdateUserDto, GetUsersQuery } from '@/schemas/user.schema'; import bcrypt from 'bcrypt'; export const createUser = async (data: CreateUserDto) => { // Check for conflicts if (await userRepository.exists(data.emailAddress)) { throw new ConflictError('Email already exists'); } // Hash password (business logic) const hashedPassword = await bcrypt.hash(data.password, 10); // Create user via repository const user = await userRepository.create({ ...data, password: hashedPassword }); // Strip sensitive data before returning const { password, ...withoutPassword } = user; return withoutPassword; }; export const getUserById = async (id: string) => { const user = await userRepository.findById(id); if (!user) throw new NotFoundError('User'); const { password, ...withoutPassword } = user; return withoutPassword; }; export const getUsers = async (query: GetUsersQuery) => { const { page, limit, sortBy, order, role } = query; const { users, total } = await userRepository.findMany({ skip: (page - 1) * limit, take: limit, where: role ? { role } : undefined, orderBy: sortBy ? { [sortBy]: order } : { createdAt: order } }); return { data: users.map(({ password, ...u }) => u), pagination: { page, limit, total, totalPages: Math.ceil(total / limit) } }; }; export const updateUser = async (id: string, data: UpdateUserDto) => { const existing = await userRepository.findById(id); if (!existing) throw new NotFoundError('User'); // Hash password if provided if (data.password) { data.password = await bcrypt.hash(data.password, 10); } const user = await userRepository.update(id, data);
在 GitHub 查看
这个 SKILL.md 很大,SkillsMP 这里只预览前一段内容。 在 GitHub 查看