1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Zod入門

1
Posted at

はじめに

本記事の目的は、この記事を読んだ初学者の方が、Zodを使われたコードを見て「何となくやってることは分かるな~」となることです。

Zodとは

ブラウザから受け取ったデータが、定められたルールに合っているかを確認するライブラリ。いわゆるバリデーションチェックです。フォームに入力された値や、APIから受け取ったデータの検証に使えます。

実際に使われている所を見てみましょう。

👇例

import { z } from "zod";

const nameSchema = z.string();

nameSchema.parse("たいち"); // 成功
nameSchema.parse(123); // 失敗

ここでは、zというZodのルールを作る機能を持ったオブジェクトを使い、z.string()でstring型かどうかを確認するというルールを、.parse()で受け取ったデータがルールに合うか確認し、成功なら値を返し、失敗ならエラーを投げます。

z.string()が「string型なら合格」というルールを作り、それをnameSchemaに入れることで、名前を付けて後から再利用できるようにしています。

parseとsafeParse

先ほどでてきたparseの役割は、スキーマのルールに従って、渡されたデータを検証することでした。

これと似たような使い方をできるZodのメソッドとしてsafeParseがあります。
parseとの違いは結果の返し方です。

同じ「string型なら合格」というルールで、成功と失敗を比べてみましょう。

import { z } from "zod";

const nameSchema = z.string();

まずはparseの結果の返し方を見てみます。
parseは成功した値を直接返します。

👇成功の場合

try {
    const result = nameSchema.parse("たいち");
    console.log(result); // "たいち"と出力される
} catch (error) {
    console.log(error.issues); // 実行されない
}

👇失敗の場合

try {
  const result = nameSchema.parse(123);
  console.log(result); // 実行されない
} catch (error) {
  console.log(error.issues); // 検証エラーの一覧
}

「検証エラーの一覧」とは、どの項目が、どのルールに違反したかを並べた配列です。エラーの種類だったりエラーの説明文が書かれています。

※ TypeScriptの設定によっては、error.issuesを読み取る前に、エラーの種類を確認する処理が必要です。

失敗するとZodが自動でエラーをthrowするため、resultには結果は入らず、catchがエラーを受け止めます。

次にsafeParseの結果の返し方です。
safeParseは成功・失敗を表すオブジェクトを返します。

👇成功の場合

const result = nameSchema.safeParse("たいち");

if (result.success) {
    console.log("成功:", result.data); 
} else {
    console.log("失敗:", result.error.issues);
}

出力:

成功:たいち

成功すると{ success: true ,data: 値 }を持つオブジェクトを返します。今回の場合successがtrueなのでif側の処理が実行され、result.dataが出力されます。

👇失敗の場合

const result = nameSchema.safeParse(123);

if (result.success) {
    console.log("成功:", result.data);
} else {
    console.log("失敗:", result.error.issues);
}

出力:

失敗:[string型でないことを示すエラー情報の配列]

失敗すると{ success: false, error: エラー } を持つオブジェクトを返します。
result.error.issuesの中身はこんな感じ👇です。

{
  success: false,
  error: {                  
    issues: [               // 違反の情報を入れた配列
      {
        code: "invalid_type",
        expected: "string",
        path: [],
        message: "Invalid input: expected string, received number"
      }
    ]
  }
};

まとめると

parse safeParse
成功時 値を直接返す オブジェクトを返す
失敗時 エラーオブジェクトを投げる オブジェクトを返す

といった感じです。

雑感

初めてZodと邂逅した時、import文に一文字だけ書かれているzのインパクトが凄かったな~。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?