@gateweb/zod-schema
v1.0.0
Published
Zod schema for GateWeb
Readme
@gateweb/zod-schema
@gateweb/zod-schema,封裝常用表單欄位規則,並內建可與 i18n 翻譯函式整合的錯誤訊息產生方式。
- 支援:字串、陣列、Email、日期 Timestamp、統一編號、檔案...等常見欄位
- 友善 i18n:所有錯誤訊息可透過自帶的
TranslateFn組合 - 型別安全:以 Zod 為核心,完整 TypeScript 推導
- 實用工具:提供
extractValidationResult、extractObjectValidationResult便於測時取得錯誤訊息
Installation
# With pnpm (recommended)
pnpm add @gateweb/zod-schema
# With npm
npm install @gateweb/zod-schema
# With yarn
yarn add @gateweb/zod-schemaUsage
Quick start
import { z } from 'zod';
import { createStringSchema } from '@gateweb/zod-schema';
import { useTranslate } from 'your-i18n-lib'; // 假設你有一個 i18n 函式
const t = useTranslate();
const stringSchema = createStringSchema(t);
const nameSchema = stringSchema({ required: true, maxLength: 50, fieldName: '姓名' });
stringSchema.parse('測試名稱'); // 成功
stringSchema.parse(''); // 失敗,拋出錯誤訊息 "notice: 所有的 schema creator 都需要傳入一個
TranslateFn函式作為參數。
With i18n
- 本套件不綁定特定 i18n 套件,只要提供
TranslateFn簽名(key: string, options?: any) => string即可。 - 你可以將現有的
t()直接傳入,例如createStringSchema(t)。 - 未提供
fieldName時,部分 Schema 會使用預設欄位名稱(如Email、日期等)。
Type Inference
- 所有 Schema 皆使用 Zod,支援
z.infer<typeof schema>自動推導。 - 範例:
const imageInfo = createImageInfoSchema(t)();
type ImageInfo = z.infer<ReturnType<typeof imageInfo>>; // { image: File | string | null; id: number }API
詳見 API 文件
Contributing
Contributions are welcome! To ensure a smooth development process, please follow these steps:
Fork & Clone: Fork the repository and clone it to your local machine.
Set Up: This project uses
pnpmas the package manager. Install dependencies with:pnpm installDevelop: Create a new branch for your feature or bug fix.
Test: Write tests for your changes and ensure all existing tests pass.
# Run all tests pnpm test # Run tests in watch mode pnpm test:watchSubmit a Pull Request: Push your changes to your fork and open a pull request to the
mainbranch. Your code will be automatically linted and formatted upon commit.
Publishing (For Maintainers)
Manual Release
- Update the version in
package.json. - Install dependencies and build the package:
pnpm install && pnpm build - Log in to npm:
pnpm login - Publish the package:
pnpm publish --access public --no-git-checks
Automatic Release
When a pull request is merged into the main branch, the release GitHub Action will automatically bump the version, create a changelog, and publish the new version to npm. The version bump follows Semantic Versioning based on the commit messages (e.g., feat: for minor, fix: for patch).
