modra40

bunjs-docker-mastery

0
0
# Install this skill:
npx skills add mOdrA40/claude-codex-skills-directory --skill "bunjs-docker-mastery"

Install specific skill from multi-skill repository

# Description

|

# SKILL.md


name: bunjs-docker-mastery
description: |
Senior/Lead Developer Bun.js + Docker dengan pengalaman 20 tahun. Skill ini digunakan ketika: (1) Membuat project Bun.js baru dengan Docker, (2) Code review dan refactoring untuk clean code, (3) Debugging complex issues, (4) Optimisasi performa dan scalability, (5) Arsitektur aplikasi production-ready, (6) Memilih library yang tepat dan terpercaya, (7) Setup CI/CD dan deployment. Trigger keywords: "bun", "bunjs", "bun.js", "docker", "typescript backend", "clean code", "scalable", "maintainable", "debugging", "performance".


Bun.js + Docker Mastery

"Simplicity is the ultimate sophistication." โ€” Leonardo da Vinci

Filosofi Inti (20 Tahun Wisdom)

KISS - Keep It Stupid Simple

// โŒ Over-engineering
class UserServiceFactoryAbstractSingletonProxyDecorator { ... }

// โœ… Simple & Clear
const userService = { create, update, delete, findById }

Less is More

  • 1 file = 1 tanggung jawab (max 200 lines)
  • 1 function = 1 task (max 20 lines)
  • Jika butuh komentar panjang, refactor kodenya
  • Nama yang jelas > komentar yang panjang

Red Flags (Warning Signs)

  • File > 300 lines โ†’ split
  • Function > 30 lines โ†’ extract
  • Nested callback > 2 level โ†’ refactor
  • Cyclomatic complexity > 10 โ†’ simplify
  • any type โ†’ define proper types

Quick Start

Inisialisasi Project Baru

# Gunakan script init
./scripts/init-project.sh my-app

# Atau manual
bun init
bun add hono zod drizzle-orm pino
bun add -d @types/bun vitest

Struktur Folder Production-Ready

src/
โ”œโ”€โ”€ index.ts              # Entry point ONLY (max 20 lines)
โ”œโ”€โ”€ app.ts                # App setup & middleware registration
โ”œโ”€โ”€ config/
โ”‚   โ”œโ”€โ”€ index.ts          # Export semua config
โ”‚   โ”œโ”€โ”€ env.ts            # Environment validation dengan Zod
โ”‚   โ””โ”€โ”€ database.ts       # Database config
โ”œโ”€โ”€ routes/
โ”‚   โ”œโ”€โ”€ index.ts          # Route aggregator
โ”‚   โ”œโ”€โ”€ user.route.ts     # User routes
โ”‚   โ””โ”€โ”€ auth.route.ts     # Auth routes
โ”œโ”€โ”€ controllers/          # HTTP layer ONLY
โ”œโ”€โ”€ services/             # Business logic
โ”œโ”€โ”€ repositories/         # Data access layer
โ”œโ”€โ”€ middlewares/
โ”‚   โ”œโ”€โ”€ auth.ts           # Authentication
โ”‚   โ”œโ”€โ”€ validate.ts       # Request validation
โ”‚   โ””โ”€โ”€ error.ts          # Error handler
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ response.ts       # Standard response helper
โ”‚   โ”œโ”€โ”€ logger.ts         # Pino logger setup
โ”‚   โ””โ”€โ”€ errors.ts         # Custom error classes
โ””โ”€โ”€ types/
    โ”œโ”€โ”€ index.d.ts        # Global types
    โ””โ”€โ”€ api.types.ts      # API request/response types

Core Patterns

1. Entry Point yang Bersih

// src/index.ts - HANYA INI
import { app } from "./app"
import { env } from "./config/env"
import { logger } from "./utils/logger"

const server = Bun.serve({
  port: env.PORT,
  fetch: app.fetch,
})

logger.info(`๐Ÿš€ Server running on ${server.url}`)

2. Environment Validation (WAJIB)

// src/config/env.ts
import { z } from "zod"

const envSchema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  JWT_SECRET: z.string().min(32),
  REDIS_URL: z.string().url().optional(),
})

export const env = envSchema.parse(process.env)
export type Env = z.infer<typeof envSchema>

3. Layered Architecture

HTTP Request โ†’ Controller โ†’ Service โ†’ Repository โ†’ Database
                  โ†“            โ†“           โ†“
              Validation   Business    Data Access
                          Logic        (Drizzle)

4. Error Handling yang Proper

// src/utils/errors.ts
export class AppError extends Error {
  constructor(
    public message: string,
    public statusCode: number = 500,
    public code: string = "INTERNAL_ERROR"
  ) {
    super(message)
    Error.captureStackTrace(this, this.constructor)
  }
}

export class NotFoundError extends AppError {
  constructor(resource: string) {
    super(`${resource} not found`, 404, "NOT_FOUND")
  }
}

export class ValidationError extends AppError {
  constructor(message: string) {
    super(message, 400, "VALIDATION_ERROR")
  }
}

5. Response Standard

// src/utils/response.ts
export const ok = <T>(data: T) => ({ success: true, data })
export const created = <T>(data: T) => ({ success: true, data })
export const error = (message: string, code: string) => ({
  success: false,
  error: { message, code }
})

Docker Best Practices

Multi-stage Build (Production)

# Build stage
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production=false
COPY . .
RUN bun run build

# Production stage
FROM oven/bun:1-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production

# Security: Non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S bunjs -u 1001
USER bunjs

COPY --from=builder --chown=bunjs:nodejs /app/dist ./dist
COPY --from=builder --chown=bunjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=bunjs:nodejs /app/package.json ./

EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

CMD ["bun", "run", "dist/index.js"]

Docker Compose (Development)

Lihat assets/project-template/docker/docker-compose.yml

Debugging Mastery

Common Crash Points & Solutions

Issue Penyebab Solusi
Memory leak Uncleared intervals/listeners Cleanup di graceful shutdown
Connection pool exhausted Tidak release connection Gunakan using atau finally
Race condition Async tanpa proper await Promise.all dengan error handling
Uncaught Promise rejection Missing try-catch Global error handler

Debugging Tools

// Bun native debugger
bun --inspect src/index.ts

// Memory profiling
bun --smol src/index.ts  // Low memory mode

// Trace async operations
process.on("unhandledRejection", (reason, promise) => {
  logger.error({ reason, promise }, "Unhandled Rejection")
})

References (Detailed Guides)

Scripts

  • scripts/init-project.sh - Initialize new project dengan template
  • scripts/healthcheck.ts - Healthcheck endpoint template

Assets

  • assets/project-template/ - Full project boilerplate siap pakai

Checklist Sebelum Production

  • [ ] Environment variables validated dengan Zod
  • [ ] Graceful shutdown implemented
  • [ ] Health check endpoint /health
  • [ ] Structured logging dengan Pino
  • [ ] Error handling global
  • [ ] Rate limiting
  • [ ] CORS configured
  • [ ] Security headers (helmet)
  • [ ] Database connection pooling
  • [ ] Docker multi-stage build
  • [ ] CI/CD pipeline
  • [ ] Monitoring & alerting ready

# Supported AI Coding Agents

This skill is compatible with the SKILL.md standard and works with all major AI coding agents:

Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.