madappgang/claude-code/bunjs-architecture

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when implementing clean architecture (routes/controllers/services/repositories), establishing camelCase conventions, designing Prisma schemas, or planning structured workflows for Bun.js applications. See bunjs for basics, bunjs-production for deployment.

Install

npx vskill@latest install madappgang/claude-code/bunjs-architecture

SKILL.md

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:

  • dev:bunjs - Core Bun patterns, HTTP servers, basic database access
  • dev:bunjs-production - Production deployment, Docker, AWS, Redis
  • dev:bunjs-apidog - 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
LayerResponsibilitiesForbidden
RoutesDefine endpoints, attach middleware, map to controllersBusiness logic, DB access
ControllersExtract data from HTTP, call services, format responsesBusiness logic, DB access, validation logic
ServicesBusiness logic, orchestrate operations, manage transactionsHTTP handling, direct DB access
RepositoriesDatabase queries, type-safe Prisma operationsBusiness 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;
};

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
279
Repository forks
32
7-day trend score
28

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 12 May 2026, 5 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/madappgang/claude-code/bunjs-architecture/badge)](https://verified-skill.com/skills/madappgang/claude-code/bunjs-architecture)

Something wrong with this skill or its page? Tell us.