code-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Documentation
代码文档
README Structure
README文档结构
Standard README Template
标准README模板
markdown
undefinedmarkdown
undefinedProject Name
Project Name
Brief description of what this project does.
Brief description of what this project does.
Quick Start
Quick Start
```bash
npm install
npm run dev
```
```bash
npm install
npm run dev
```
Installation
Installation
Detailed installation instructions...
Detailed installation instructions...
Usage
Usage
```typescript
import { something } from 'project';
// Example usage
const result = something.doThing();
```
```typescript
import { something } from 'project';
// Example usage
const result = something.doThing();
```
API Reference
API Reference
functionName(param: Type): ReturnType
functionName(param: Type): ReturnTypefunctionName(param: Type): ReturnType
functionName(param: Type): ReturnTypeDescription of what the function does.
Parameters:
- - Description of parameter
param
Returns: Description of return value
Example:
```typescript
const result = functionName('value');
```
Description of what the function does.
Parameters:
- - Description of parameter
param
Returns: Description of return value
Example:
```typescript
const result = functionName('value');
```
Configuration
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
| | | What it does |
| Option | Type | Default | Description |
|---|---|---|---|
| | | What it does |
Contributing
Contributing
How to contribute...
How to contribute...
License
License
MIT
undefinedMIT
undefinedAPI Documentation
API文档
JSDoc/TSDoc Style
JSDoc/TSDoc 风格
typescript
/**
* Creates a new user account.
*
* @param userData - The user data for account creation
* @param options - Optional configuration
* @returns The created user object
* @throws {ValidationError} If email is invalid
* @example
* ```ts
* const user = await createUser({
* email: 'user@example.com',
* name: 'John'
* });
* ```
*/
async function createUser(
userData: UserInput,
options?: CreateOptions
): Promise<User> {
// Implementation
}
/**
* Configuration options for the API client.
*/
interface ClientConfig {
/** The API base URL */
baseUrl: string;
/** Request timeout in milliseconds @default 5000 */
timeout?: number;
/** Custom headers to include in requests */
headers?: Record<string, string>;
}typescript
/**
* Creates a new user account.
*
* @param userData - The user data for account creation
* @param options - Optional configuration
* @returns The created user object
* @throws {ValidationError} If email is invalid
* @example
* ```ts
* const user = await createUser({
* email: 'user@example.com',
* name: 'John'
* });
* ```
*/
async function createUser(
userData: UserInput,
options?: CreateOptions
): Promise<User> {
// Implementation
}
/**
* Configuration options for the API client.
*/
interface ClientConfig {
/** The API base URL */
baseUrl: string;
/** Request timeout in milliseconds @default 5000 */
timeout?: number;
/** Custom headers to include in requests */
headers?: Record<string, string>;
}OpenAPI/Swagger
OpenAPI/Swagger
yaml
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users:
post:
summary: Create a user
description: Creates a new user account
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserInput'
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid input
components:
schemas:
UserInput:
type: object
required:
- email
- name
properties:
email:
type: string
format: email
name:
type: string
User:
type: object
properties:
id:
type: string
email:
type: string
name:
type: string
createdAt:
type: string
format: date-timeyaml
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users:
post:
summary: Create a user
description: Creates a new user account
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserInput'
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid input
components:
schemas:
UserInput:
type: object
required:
- email
- name
properties:
email:
type: string
format: email
name:
type: string
User:
type: object
properties:
id:
type: string
email:
type: string
name:
type: string
createdAt:
type: string
format: date-timeInline Comments
内联注释
When to Comment
何时添加注释
typescript
// GOOD: Explain WHY, not WHAT
// Use binary search because the list is always sorted and
// can contain millions of items - O(log n) vs O(n)
const index = binarySearch(items, target);
// GOOD: Explain complex business logic
// Users get 20% discount if they've been members for 2+ years
// AND have made 10+ purchases (per marketing team decision Q4 2024)
if (user.memberYears >= 2 && user.purchaseCount >= 10) {
applyDiscount(0.2);
}
// GOOD: Document workarounds
// HACK: Safari doesn't support this API, fallback to polling
// TODO: Remove when Safari adds support (tracking: webkit.org/b/12345)
if (!window.IntersectionObserver) {
startPolling();
}typescript
// GOOD: Explain WHY, not WHAT
// Use binary search because the list is always sorted and
// can contain millions of items - O(log n) vs O(n)
const index = binarySearch(items, target);
// GOOD: Explain complex business logic
// Users get 20% discount if they've been members for 2+ years
// AND have made 10+ purchases (per marketing team decision Q4 2024)
if (user.memberYears >= 2 && user.purchaseCount >= 10) {
applyDiscount(0.2);
}
// GOOD: Document workarounds
// HACK: Safari doesn't support this API, fallback to polling
// TODO: Remove when Safari adds support (tracking: webkit.org/b/12345)
if (!window.IntersectionObserver) {
startPolling();
}When NOT to Comment
何时无需添加注释
typescript
// BAD: Stating the obvious
// Increment counter by 1
counter++;
// BAD: Explaining clear code
// Check if user is admin
if (user.role === 'admin') { ... }
// BAD: Outdated comments (worse than no comment)
// Returns the user's full name <-- Actually returns email now!
function getUserIdentifier(user) {
return user.email;
}typescript
// BAD: Stating the obvious
// Increment counter by 1
counter++;
// BAD: Explaining clear code
// Check if user is admin
if (user.role === 'admin') { ... }
// BAD: Outdated comments (worse than no comment)
// Returns the user's full name <-- Actually returns email now!
function getUserIdentifier(user) {
return user.email;
}Architecture Documentation
架构文档
ADR (Architecture Decision Record)
ADR(架构决策记录)
markdown
undefinedmarkdown
undefinedADR-001: Use PostgreSQL for Primary Database
ADR-001: Use PostgreSQL for Primary Database
Status
Status
Accepted
Accepted
Context
Context
We need a database for storing user data and transactions.
Options considered: PostgreSQL, MySQL, MongoDB, DynamoDB.
We need a database for storing user data and transactions.
Options considered: PostgreSQL, MySQL, MongoDB, DynamoDB.
Decision
Decision
Use PostgreSQL with Supabase hosting.
Use PostgreSQL with Supabase hosting.
Rationale
Rationale
- Strong ACID compliance needed for financial data
- Team has PostgreSQL experience
- Supabase provides auth and realtime features
- pgvector extension for future AI features
- Strong ACID compliance needed for financial data
- Team has PostgreSQL experience
- Supabase provides auth and realtime features
- pgvector extension for future AI features
Consequences
Consequences
- Need to manage schema migrations
- May need read replicas for scale
- Team needs to learn Supabase-specific features
undefined- Need to manage schema migrations
- May need read replicas for scale
- Team needs to learn Supabase-specific features
undefinedComponent Documentation
组件文档
markdown
undefinedmarkdown
undefinedAuthentication Module
Authentication Module
Overview
Overview
Handles user authentication using JWT tokens with refresh rotation.
Handles user authentication using JWT tokens with refresh rotation.
Flow
Flow
- User submits credentials to
/auth/login - Server validates and returns access + refresh tokens
- Access token used for API requests (15min expiry)
- Refresh token used to get new access token (7d expiry)
- User submits credentials to
/auth/login - Server validates and returns access + refresh tokens
- Access token used for API requests (15min expiry)
- Refresh token used to get new access token (7d expiry)
Dependencies
Dependencies
- - Token generation/validation
jsonwebtoken - - Password hashing
bcrypt - - Refresh token storage
redis
- - Token generation/validation
jsonwebtoken - - Password hashing
bcrypt - - Refresh token storage
redis
Configuration
Configuration
- - Secret for signing tokens
JWT_SECRET - - Access token lifetime
ACCESS_TOKEN_EXPIRY - - Refresh token lifetime
REFRESH_TOKEN_EXPIRY
undefined- - Secret for signing tokens
JWT_SECRET - - Access token lifetime
ACCESS_TOKEN_EXPIRY - - Refresh token lifetime
REFRESH_TOKEN_EXPIRY
undefinedDocumentation Principles
文档编写原则
- Write for your audience - New devs vs API consumers
- Keep it close to code - Docs in same repo, near relevant code
- Update with code - Stale docs are worse than none
- Examples over explanations - Show, don't just tell
- Progressive disclosure - Quick start first, details later
- 为目标受众编写 - 面向新开发者或API使用者
- 贴近代码存放 - 文档与代码存放在同一仓库,靠近相关代码
- 随代码更新 - 过时的文档不如没有文档
- 示例优先于解释 - 展示而非仅说明
- 渐进式披露 - 先提供快速入门,再展示详细内容