This guide defines the coding standards and best practices for the Yemaya project. Following these guidelines ensures consistency across the codebase and makes code reviews more efficient.
Table of Contents#
- General Principles
- TypeScript Guidelines
- React Guidelines
- API Guidelines
- Database Guidelines
- Testing Guidelines
- Git Workflow
General Principles#
Clarity Over Cleverness#
Write code that is easy to understand. Future maintainers (including yourself) will thank you.
// Bad - clever but unclear
const r = a.reduce((p, c) => (c.s ? [...p, c] : p), []);
// Good - clear and readable
const activeItems = items.filter((item) => item.isActive);
Single Responsibility#
Functions and classes should do one thing well.
// Bad - function does too much
async function processUser(userId: string) {
const user = await db.user.findUnique({ where: { id: userId } });
const orders = await db.order.findMany({ where: { userId } });
await sendEmail(user.email, formatOrderSummary(orders));
await updateLastActivity(userId);
return { user, orders };
}
// Good - separated concerns
async function getUser(userId: string) {
return db.user.findUnique({ where: { id: userId } });
}
async function getUserOrders(userId: string) {
return db.order.findMany({ where: { userId } });
}
async function sendOrderSummary(user: User, orders: Order[]) {
const summary = formatOrderSummary(orders);
await sendEmail(user.email, summary);
}
Explicit Over Implicit#
Be explicit about types, return values, and error handling.
// Bad - implicit
function process(data) {
return data.map((x) => x.value);
}
// Good - explicit
function extractValues(items: Item[]): number[] {
return items.map((item) => item.value);
}
Fail Fast#
Validate inputs early and fail with clear error messages.
// Good - validate early
function createProject(input: CreateProjectInput): Project {
if (!input.name || input.name.length === 0) {
throw new ValidationError('Project name is required');
}
if (input.name.length > 100) {
throw new ValidationError('Project name must be 100 characters or less');
}
// ... proceed with creation
}
TypeScript Guidelines#
Use Strict Mode#
All packages use strict TypeScript:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
Type Definitions#
Prefer Interfaces for Object Shapes#
// Good
interface User {
id: string;
name: string;
email: string;
}
// Use type for unions, intersections, and mapped types
type UserRole = 'admin' | 'editor' | 'viewer';
type UserWithRole = User & { role: UserRole };
Avoid any#
Use unknown when type is truly unknown, then narrow with type guards.
// Bad
function processData(data: any) {
return data.value;
}
// Good
function processData(data: unknown): number {
if (isValidData(data)) {
return data.value;
}
throw new Error('Invalid data format');
}
function isValidData(data: unknown): data is { value: number } {
return (
typeof data === 'object' &&
data !== null &&
'value' in data &&
typeof (data as any).value === 'number'
);
}
Use Generics Appropriately#
// Good - generic provides type safety
function first<T>(items: T[]): T | undefined {
return items[0];
}
// Usage is type-safe
const user = first(users); // type: User | undefined
const name = first(names); // type: string | undefined
Null Handling#
Use Optional Chaining and Nullish Coalescing#
// Good
const userName = user?.profile?.name ?? 'Anonymous';
// Avoid
const userName =
user && user.profile && user.profile.name ? user.profile.name : 'Anonymous';
Be Explicit About Nullable Types#
// Good - explicitly nullable
interface UserQuery {
id: string;
includeDeleted?: boolean; // optional
}
function findUser(id: string): User | null {
// explicitly returns null if not found
}
Enums and Constants#
Prefer const objects over enums#
// Preferred
export const ProjectStatus = {
DRAFT: 'draft',
ACTIVE: 'active',
ARCHIVED: 'archived',
} as const;
export type ProjectStatus = (typeof ProjectStatus)[keyof typeof ProjectStatus];
// Usage
const status: ProjectStatus = ProjectStatus.ACTIVE;
Use UPPER_SNAKE_CASE for constants#
const MAX_RETRIES = 3;
const DEFAULT_PAGE_SIZE = 20;
const API_BASE_URL = 'https://api.yemaya.io';
Imports#
Order imports consistently#
// 1. Node built-ins
import { readFile } from 'fs/promises';
import path from 'path';
// 2. External packages
import { z } from 'zod';
import { Hono } from 'hono';
// 3. Internal packages (@yemaya/*)
import { db } from '@yemaya/database';
import { ApiError } from '@yemaya/core';
// 4. Relative imports
import { UserService } from './user-service';
import { validateEmail } from '../utils';
// 5. Type imports (separate if needed)
import type { User, Project } from '@yemaya/types';
Use path aliases#
// Good - using aliases
import { Button } from '@/components/Button';
import { useAuth } from '@/hooks/useAuth';
// Avoid - deep relative paths
import { Button } from '../../../../components/Button';
Function Patterns#
Use async/await over raw promises#
// Good
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new ApiError('USER_FETCH_FAILED', 'Failed to fetch user');
}
return response.json();
}
// Avoid
function fetchUser(id: string): Promise<User> {
return fetch(`/api/users/${id}`).then((response) => {
if (!response.ok) {
throw new ApiError('USER_FETCH_FAILED', 'Failed to fetch user');
}
return response.json();
});
}
Use arrow functions for callbacks#
// Good
const activeUsers = users.filter((user) => user.isActive);
const names = users.map((user) => user.name);
// Use function declarations for top-level functions
export function processUsers(users: User[]): ProcessedUser[] {
return users.map(transformUser);
}
React Guidelines#
Component Structure#
// components/UserCard/UserCard.tsx
// 1. Imports
import { type ComponentProps } from 'react';
import { cn } from '@/utils/cn';
// 2. Types
interface UserCardProps {
user: User;
variant?: 'compact' | 'full';
onSelect?: (user: User) => void;
}
// 3. Component
export function UserCard({
user,
variant = 'full',
onSelect,
}: UserCardProps) {
// 3a. Hooks
const { isAdmin } = useAuth();
const [isExpanded, setIsExpanded] = useState(false);
// 3b. Derived state
const displayName = user.name || user.email;
// 3c. Event handlers
const handleClick = useCallback(() => {
onSelect?.(user);
}, [user, onSelect]);
// 3d. Effects
useEffect(() => {
// ...
}, []);
// 3e. Early returns for loading/error states
if (!user) {
return null;
}
// 3f. Render
return (
<div className={cn('user-card', variants[variant])}>
{/* ... */}
</div>
);
}
// 4. Display name (for debugging)
UserCard.displayName = 'UserCard';
Hooks#
Custom hooks start with use#
// hooks/useProjects.ts
export function useProjects(options?: UseProjectsOptions) {
const query = useQuery({
queryKey: ['projects', options],
queryFn: () => fetchProjects(options),
});
return {
projects: query.data ?? [],
isLoading: query.isLoading,
error: query.error,
refetch: query.refetch,
};
}
Extract complex logic into hooks#
// Bad - too much logic in component
function ProjectList() {
const [projects, setProjects] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [page, setPage] = useState(1);
// ... 50 more lines of data fetching logic
return <div>...</div>;
}
// Good - logic extracted to hook
function ProjectList() {
const { projects, isLoading, error, loadMore } = useProjects();
if (isLoading) return <Skeleton />;
if (error) return <ErrorMessage error={error} />;
return (
<div>
{projects.map(project => (
<ProjectCard key={project.id} project={project} />
))}
<Button onClick={loadMore}>Load More</Button>
</div>
);
}
State Management#
Use appropriate state solution#
| Scope | Solution |
|---|---|
| Component local | useState |
| Shared between siblings | Lift state up |
| Global client state | Zustand |
| Server state | TanStack Query |
| Form state | React Hook Form |
| URL state | React Router |
Avoid prop drilling#
// Bad - drilling through many levels
<App user={user}>
<Layout user={user}>
<Sidebar user={user}>
<UserMenu user={user} />
</Sidebar>
</Layout>
</App>
// Good - use context or store
<AuthProvider>
<App>
<Layout>
<Sidebar>
<UserMenu /> {/* gets user from useAuth() */}
</Sidebar>
</Layout>
</App>
</AuthProvider>
Styling#
Use Tailwind CSS with cn utility#
import { cn } from '@/utils/cn';
function Button({ variant, size, className, ...props }) {
return (
<button
className={cn(
// Base styles
'inline-flex items-center justify-center rounded-md font-medium',
'focus-visible:outline-none focus-visible:ring-2',
'disabled:pointer-events-none disabled:opacity-50',
// Variant styles
{
'bg-primary text-primary-foreground hover:bg-primary/90':
variant === 'primary',
'bg-secondary text-secondary-foreground hover:bg-secondary/80':
variant === 'secondary',
},
// Size styles
{
'h-8 px-3 text-sm': size === 'sm',
'h-10 px-4': size === 'md',
'h-12 px-6 text-lg': size === 'lg',
},
// Custom className
className
)}
{...props}
/>
);
}
Use CSS variables for theming#
:root {
--color-primary: 220 90% 56%;
--color-background: 0 0% 100%;
--color-foreground: 222 47% 11%;
}
.dark {
--color-primary: 217 91% 60%;
--color-background: 222 47% 11%;
--color-foreground: 210 40% 98%;
}
API Guidelines#
Route Design#
Use resource-based URLs#
// Good
GET /projects // List projects
POST /projects // Create project
GET /projects/:id // Get project
PATCH /projects/:id // Update project
DELETE /projects/:id // Delete project
GET /projects/:id/members // List project members
// Avoid
GET /getProjects
POST /createProject
GET /getProjectById/:id
Use appropriate HTTP methods#
| Method | Use |
|---|---|
| GET | Retrieve resources |
| POST | Create resources, actions |
| PATCH | Partial updates |
| PUT | Full replacement |
| DELETE | Remove resources |
Request/Response#
Use Zod schemas#
import { z } from '@hono/zod-openapi';
const CreateProjectSchema = z.object({
name: z
.string()
.min(1, 'Name is required')
.max(100, 'Name must be 100 characters or less'),
description: z.string().max(1000).optional(),
type: z.enum(['film', 'game', 'animation', 'mixed']),
visibility: z.enum(['private', 'team', 'public']).default('private'),
});
type CreateProjectInput = z.infer<typeof CreateProjectSchema>;
Consistent response format#
// Success with data
{
"success": true,
"data": { ... }
}
// Success with message
{
"success": true,
"message": "Project deleted successfully"
}
// Error
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input",
"details": {
"name": ["Name is required"]
}
}
}
Error Handling#
Use custom error classes#
// errors/api-error.ts
export class ApiError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500,
public details?: Record<string, unknown>
) {
super(message);
this.name = 'ApiError';
}
static badRequest(
code: string,
message: string,
details?: Record<string, unknown>
) {
return new ApiError(code, message, 400, details);
}
static unauthorized(message = 'Unauthorized') {
return new ApiError('UNAUTHORIZED', message, 401);
}
static forbidden(message = 'Forbidden') {
return new ApiError('FORBIDDEN', message, 403);
}
static notFound(resource: string) {
return new ApiError('NOT_FOUND', `${resource} not found`, 404);
}
}
Handle errors at boundaries#
// Hono error handler
app.onError((err, c) => {
if (err instanceof ApiError) {
return c.json(
{
success: false,
error: {
code: err.code,
message: err.message,
details: err.details,
},
},
err.statusCode
);
}
// Log unexpected errors
console.error('Unexpected error:', err);
return c.json(
{
success: false,
error: {
code: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
},
},
500
);
});
Database Guidelines#
Schema Design#
Use UUIDs for primary keys#
model Project {
id String @id @default(uuid())
name String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Include audit fields#
model Project {
id String @id @default(uuid())
name String
// Audit fields
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime? // Soft delete
// Relationships
createdBy User @relation("CreatedProjects", fields: [createdById], references: [id])
createdById String
}
Queries#
Use select to limit fields#
// Good - only fetch needed fields
const users = await db.user.findMany({
select: {
id: true,
name: true,
email: true,
},
});
// Avoid - fetching everything
const users = await db.user.findMany();
Use transactions for related operations#
await db.$transaction(async (tx) => {
const project = await tx.project.create({
data: { name, ownerId },
});
await tx.projectMember.create({
data: {
projectId: project.id,
userId: ownerId,
role: 'owner',
},
});
await tx.activityLog.create({
data: {
type: 'project.created',
projectId: project.id,
userId: ownerId,
},
});
return project;
});
Testing Guidelines#
Test Structure#
import { describe, it, expect, beforeEach, vi } from 'vitest';
describe('UserService', () => {
// Setup
let service: UserService;
let mockDb: MockDatabase;
beforeEach(() => {
mockDb = createMockDatabase();
service = new UserService(mockDb);
});
// Group related tests
describe('createUser', () => {
it('should create user with valid input', async () => {
// Arrange
const input = { email: 'test@example.com', name: 'Test' };
// Act
const user = await service.createUser(input);
// Assert
expect(user).toMatchObject({
email: 'test@example.com',
name: 'Test',
});
expect(user.id).toBeDefined();
});
it('should throw on duplicate email', async () => {
// Arrange
await service.createUser({ email: 'test@example.com', name: 'Test' });
// Act & Assert
await expect(
service.createUser({ email: 'test@example.com', name: 'Another' })
).rejects.toThrow('Email already registered');
});
});
});
Naming Tests#
Use descriptive test names that explain the behavior:
// Good
it('should return empty array when no projects exist', () => {});
it('should throw ValidationError when name exceeds 100 characters', () => {});
it('should send email notification after user registration', () => {});
// Bad
it('test1', () => {});
it('works', () => {});
it('handles error', () => {});
Mocking#
import { vi } from 'vitest';
// Mock modules
vi.mock('@yemaya/database', () => ({
db: {
user: {
findUnique: vi.fn(),
create: vi.fn(),
},
},
}));
// Mock functions
const mockSendEmail = vi.fn();
vi.mock('./email-service', () => ({
sendEmail: mockSendEmail,
}));
// Reset between tests
beforeEach(() => {
vi.clearAllMocks();
});
Git Workflow#
Commit Messages#
Follow Conventional Commits:
<type>(<scope>): <description>
[optional body]
[optional footer]
Types: feat, fix, docs, style, refactor, test, chore
Examples:
feat(api): add project archiving endpoint
fix(web): resolve login redirect loop
Fixes #456
docs(readme): update installation instructions
refactor(database): extract query builders into separate module
test(auth): add integration tests for OAuth flow
chore(deps): upgrade vitest to v1.0
Branch Strategy#
main
├── develop
│ ├── feature/add-user-avatars
│ ├── feature/project-templates
│ └── fix/upload-memory-leak
└── release/v1.2.0
Tooling#
ESLint#
We use ESLint with custom rules. Run:
pnpm lint # Check
pnpm lint:fix # Auto-fix
Prettier#
Code formatting is handled by Prettier:
pnpm format # Format all files
TypeScript#
Type checking:
pnpm typecheck # Check all packages
Pre-commit Hooks#
Husky runs checks before commits:
- Lint staged files
- Type check
- Run affected tests
Questions?#
If you're unsure about a style decision:
- Check existing code for patterns
- Ask in the Discord #development channel
- Open a discussion on GitHub
Remember: consistency is more important than any specific rule. When in doubt, match the surrounding code.