backend-patterns
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.
by Luohaothu★ 24 GitHub stars
Install backend-patterns in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
About this skill
後端開發模式
用於可擴展伺服器端應用程式的後端架構模式和最佳實務。
API 設計模式
RESTful API 結構
// ✅ 基於資源的 URL
GET /api/markets # 列出資源
GET /api/markets/:id # 取得單一資源
POST /api/markets # 建立資源
PUT /api/markets/:id # 替換資源
PATCH /api/markets/:id # 更新資源
DELETE /api/markets/:id # 刪除資源
// ✅ 用於過濾、排序、分頁的查詢參數
GET /api/markets?status=active&sort=volume&limit=20&offset=0
Repository 模式
// 抽象資料存取邏輯
interface MarketRepository {
findAll(filters?: MarketFilters): Promise<Market[]>
findById(id: string): Promise<Market | null>
create(data: CreateMarketDto): Promise<Market>
update(id: string, data: UpdateMarketDto): Promise<Market>
delete(id: string): Promise<void>
}
class SupabaseMarketRepository implements MarketRepository {
async findAll(filters?: MarketFilters): Promise<Market[]> {
let query = supabase.from('markets').select('*')
if (filters?.status) {
query = query.eq('status', filters.status)
}
if (filters?.limit) {
query = query.limit(filters.limit)
}
const { data, error } = await query
if (error) throw new Error(error.message)
return data
}
// 其他方法...
}
Service 層模式
// 業務邏輯與資料存取分離
class MarketService {
constructor(private marketRepo: MarketRepository) {}
async searchMarkets(query: string, limit: number = 10): Promise<Market[]> {
// 業務邏輯
const embedding = await generateEmbedding(query)
const results = await this.vectorSearch(embedding, limit)
// 取得完整資料
const markets = await this.marketRepo.findByIds(results.map(r => r.id))
// 依相似度排序
return markets.sort((a, b) => {
const scoreA = results.find(r => r.id === a.id)?.score || 0
const scoreB = results.find(r => r.id === b.id)?.score || 0
return scoreA - scoreB
})
}
private async vectorSearch(embedding: number[], limit: number) {
// 向量搜尋實作
}
}
Middleware 模式
// 請求/回應處理流水線
export function withAuth(handler: NextApiHandler): NextApiHandler {
return async (req, res) => {
const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) {
return res.status(401).json({ error: 'Unauthorized' })
}
try {
const user = await verifyToken(token)
req.user = user
return handler(req, res)
} catch (error) {
return res.status(401).json({ error: 'Invalid token' })
}
}
}
// 使用方式
export default withAuth(async (req, res) => {
// Handler 可存取 req.user
})
資料庫模式
查詢優化
// ✅ 良好:只選擇需要的欄位
const { data } = await supabase
.from('markets')
.select('id, name, status, volume')
.eq('status', 'active')
.order('volume', { ascending: false })
.limit(10)
// ❌ 不良:選擇所有欄位
const { data } = await supabase
.from('markets')
.select('*')
N+1 查詢問題預防
// ❌ 不良:N+1 查詢問題
const markets = await getMarkets()
for (const market of markets) {
market.creator = await getUser(market.creator_id) // N 次查詢
}
// ✅ 良好:批次取得
const markets = await getMarkets()
const creatorIds = markets.map(m => m.creator_id)
const creators = await getUsers(creatorIds) // 1 次查詢
const creatorMap = new Map(creators.map(c => [c.id, c]))
markets.forEach(market => {
market.creator = creatorMap.get(market.creator_id)
})
Transaction 模式
async function createMarketWithPosition(
marketData: CreateMarketDto,
positionData: CreatePositionDto
) {
// 使用 Supabase transaction
const { data, error } = await supabase.rpc('create_market_with_position', {
market_data: marketData,
position_data: positionData
})
if (error) throw new Error('Transaction failed')
return data
}
// Supabase 中的 SQL 函式
CREATE OR REPLACE FUNCTION create_market_with_position(
market_data jsonb,
position_data jsonb
)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
-- 自動開始 transaction
INSERT INTO markets VALUES (market_data);
INSERT INTO positions VALUES (position_data);
RETURN jsonb_build_object('success', true);
EXCEPTION
WHEN OTHERS THEN
-- 自動 rollback
RETURN jsonb_build_object('success', false, 'error', SQLERRM);
END;
$$;
快取策略
Redis 快取層
class CachedMarketRepository implements MarketRepository {
constructor(
private baseRepo: MarketRepository,
private redis: RedisClient
) {}
async findById(id: string): Promise<Market | null> {
// 先檢查快取
const cached = await this.redis.get(`market:${id}`)
if (cached) {
return JSON.parse(cached)
}
// 快取未命中 - 從資料庫取得
const market = await this.baseRepo.findById(id)
if (market) {
// 快取 5 分鐘
await this.redis.setex(`market:${id}`, 300, JSON.stringify(market))
}
return market
}
async invalidateCache(id: string): Promise<void> {
await this.redis.del(`market:${id}`)
}
}
Cache-Aside 模式
async function getMarketWithCache(id: string): Promise<Market> {
const cacheKey = `
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
FAQ
What does the backend-patterns skill do?
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.
How do I install the backend-patterns skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the backend-patterns skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…