typed-service-contracts

typed-service-contracts

熱門

使用「Spec and Handler」模式建立健全且型別安全之 TypeScript 服務的架構標準。適用於建置 CLI 工具、函式庫或複雜的業務邏輯。

2.8萬星標
2285分支
更新於 2026/10/1
SKILL.md
唯讀
名稱
typed-service-contracts
描述

使用「Spec and Handler」模式建立健全且型別安全之 TypeScript 服務的架構標準。適用於建置 CLI 工具、函式庫或複雜的業務邏輯。

Typed Service Contracts(Spec & Handler 模式)

本 Skill 定義了一套以 契約式設計(Design by Contract, DbC) 原則為後盾的 垂直切片架構(Vertical Slice Architecture)。它將應用程式邏輯視為經過嚴格定義的工作單元(Unit of Work),其中輸入資料會經過解析(而非僅僅驗證),且錯誤會被視為數值(Result Pattern)而非例外狀況。

何時使用本 Skill

  • 建置 CLI 工具或函式庫: 當您需要在使用者輸入與系統邏輯之間建立嚴格邊界時。
  • 複雜的驗證情境: 當輸入資料需要先進行轉換(Parsing)才能使用時(例如:確保字串為有效的檔案路徑)。
  • 高可靠性需求: 當您無法承受未處理的執行階段例外狀況(Unhandled Runtime Exceptions),且需要完整的錯誤處理時。
  • 著重測試架構: 當您希望將資料驗證測試與業務邏輯測試相互分離時。

架構元件

1. Spec (spec.ts)

即「契約(Contract)」或「連接埠(Port)」。它定義了 內容(What)。必須包含:

  • Input Schema: 將原始輸入解析為有效 DTO 的 Zod schema。
  • Output Schema: 定義成功時資料結構的 Zod schema。
  • Error Schema: 具體失敗模式的辨識聯集(Discriminated Union,非泛用錯誤)。
  • Result Type: 由 Success | Failure 組成的 DiscriminatedUnion。
  • Interface: 能力定義(例如 interface ConfigureSpec)。

2. Handler (handler.ts)

即「實作(Implementation)」或「轉接器(Adapter)」。它定義了 作法(How)。必須符合以下條件:

  • 實作在 Spec 中定義的 Interface。
  • 為處理副作用(Side Effects,如檔案系統、API 呼叫)的「非純粹(Impure)」類別。
  • 絕不拋出(NEVER throw) 例外。必須擷取內部錯誤並將其映射至 Result 型別。

如何使用

步驟 1:定義契約 (spec.ts)

請參考以下範本來定義邊界。

import { z } from 'zod';

// 1. 驗證輔助函式 (可重用的 Refinements)
export const SafePathSchema = z.string()
  .min(1)
  .refine(p => !p.includes('..'), "No traversal allowed");

// 2. 輸入 (Command) - "Parse, don't validate"
export const MyTaskInputSchema = z.object({
  path: SafePathSchema,
  force: z.boolean().default(false),
});
export type MyTaskInput = z.infer<typeof MyTaskInputSchema>;

// 3. 錯誤碼 (列舉完整可能性)
export const MyTaskErrorCode = z.enum([
  'FILE_NOT_FOUND',
  'PERMISSION_DENIED', 
  'UNKNOWN_ERROR'
]);

// 4. 結果 (Monad)
export const MyTaskSuccess = z.object({
  success: z.literal(true),
  data: z.string(), // 輸出的有效載荷 (payload)
});

export const MyTaskFailure = z.object({
  success: z.literal(false),
  error: z.object({
    code: MyTaskErrorCode,
    message: z.string(),
    suggestion: z.string().optional(),
    recoverable: z.boolean(),
  })
});

export type MyTaskResult = 
  | z.infer<typeof MyTaskSuccess> 
  | z.infer<typeof MyTaskFailure>;

// 5. 介面 (能力定義)
export interface MyTaskSpec {
  execute(input: MyTaskInput): Promise<MyTaskResult>;
}

步驟 2:實作 Handler (handler.ts)

請參考以下範本來實作邏輯。

import { MyTaskSpec, MyTaskInput, MyTaskResult } from './spec.js';
import * as fs from 'fs';

export class MyTaskHandler implements MyTaskSpec {
  async execute(input: MyTaskInput): Promise<MyTaskResult> {
    try {
      // 1. 業務邏輯
      if (!fs.existsSync(input.path)) {
        // 2. 明確返回錯誤 (不拋出例外)
        return {
          success: false,
          error: {
            code: 'FILE_NOT_FOUND',
            message: `Path does not exist: ${input.path}`,
            recoverable: true
          }
        };
      }

      // 3. 成功返回
      return {
        success: true,
        data: 'Operation complete'
      };

    } catch (error) {
      // 4. 安全網:擷取未知的執行階段錯誤
      return {
        success: false,
        error: {
          code: 'UNKNOWN_ERROR',
          message: error instanceof Error ? error.message : String(error),
          recoverable: false
        }
      };
    }
  }
}

步驟 3:測試策略

切勿撰寫單體式(Monolithic)測試。請將測試拆分為 契約測試(Contract Tests) 與 邏輯測試(Logic Tests)。

A. 契約測試 (Schema)

測試「保全人員」。確保無效資料在到達 Handler 之前就被拒絕。

  • 重點: 邊界條件(Edge cases)、驗證規則、Zod refinements。
  • 風格: 資料驅動(Table tests)。
// spec.test.ts
import { MyTaskInputSchema } from './spec';

const invalidCases = [
  { val: '../etc/passwd', err: 'No traversal allowed' },
  { val: '', err: 'min(1)' },
];

test.each(invalidCases)('validates paths', ({ val, err }) => {
  const result = MyTaskInputSchema.safeParse({ path: val });
  expect(result.success).toBe(false);
});

B. 邏輯測試 (Handler)

測試「主廚」。模擬外部相依性(fs、網路)並斷言 Result 物件。

  • 重點: 業務邏輯流程、錯誤映射、成功狀態。
  • 風格: 使用 Mock 的單元測試或情境執行器(Scenario Runners)。
// handler.test.ts
import { MyTaskHandler } from './handler';
import { vi } from 'vitest'; // 或 jest

test('returns FILE_NOT_FOUND if path missing', async () => {
  // MOCK
  vi.mocked(fs.existsSync).mockReturnValue(false);
  
  // 執行
  const handler = new MyTaskHandler();
  const result = await handler.execute({ path: '/fake' });

  // 斷言 (檢查 Result 物件)
  expect(result.success).toBe(false);
  if (!result.success) {
    expect(result.error.code).toBe('FILE_NOT_FOUND');
  }
});