![見出し画像](https://assets.st-note.com/production/uploads/images/92556295/rectangle_large_type_2_008f5af32f21fa3ccf15156b9c3726e3.png?width=1200)
zodライブラリを使ったuseCludeフックをnpmで公開してみました
こんにちわ。nap5です。今回は小ネタです。
zodライブラリを使ったuseCludeフックをnpmで公開してみましたので、紹介です。
前回の記事と関連しています。
レポジトリはこちらになります。
npmライブラリはこちらになります。
Githubのレポジトリのexample系のディレクトリにサンプル置いています。
typescriptなnextjsのサンプルも置いています。
シンプルな使い方としては以下になります。
まずはプロジェクトディレクトリを作成して
$ cd ~/wrksp
$ mkdir -p a
$ cd a
$ yarn init -y
$ yarn add @nap5/use-clude zod
$ mkdir -p data
$ touch data/bebop.json
$ touch index.js
data/bebop.jsonにテストデータを用意して
[
{
"id": "p9z7aek9fi",
"name": "Landon Glover",
"age": 38,
"blogs": []
},
{
"id": "pga7t8prpl",
"name": "Jack Jackson",
"age": 38,
"blogs": [
{
"id": "1",
"title": "AAA"
},
{
"id": "2",
"title": "BBB"
},
{
"id": "3",
"title": "CCC"
}
]
},
{
"id": "tcz4kesu6p",
"name": "Grace Dennis",
"age": 44,
"blogs": [
{
"id": "4",
"title": "DDD"
}
]
}
]
package.jsonでモジュールハンドリングして
{
"type": "module",
"dependencies": {
"@nap5/use-clude": "^1.0.0",
"zod": "^3.19.1"
}
}
index.jsに実行内容を記載します。
import { z } from "zod";
import { useClude } from "@nap5/use-clude";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data/bebop.json");
const userShape = {
id: z.string(),
name: z.string(),
age: z.number(),
blogs: z
.object({
id: z.string(),
title: z.string(),
})
.array(),
};
const { exclude, include } = useClude(userShape);
console.log(
JSON.stringify(
data.map((item) => include("blogs").parse(item)),
null,
2
)
);
console.log(
JSON.stringify(
data.map((item) => exclude("name", "age").parse(item)),
null,
2
)
);
以下が実行結果になります。
$ time node index.js
[
{
"blogs": []
},
{
"blogs": [
{
"id": "1",
"title": "AAA"
},
{
"id": "2",
"title": "BBB"
},
{
"id": "3",
"title": "CCC"
}
]
},
{
"blogs": [
{
"id": "4",
"title": "DDD"
}
]
}
]
[
{
"id": "p9z7aek9fi",
"blogs": []
},
{
"id": "pga7t8prpl",
"blogs": [
{
"id": "1",
"title": "AAA"
},
{
"id": "2",
"title": "BBB"
},
{
"id": "3",
"title": "CCC"
}
]
},
{
"id": "tcz4kesu6p",
"blogs": [
{
"id": "4",
"title": "DDD"
}
]
}
]
real 0m0.040s
user 0m0.042s
sys 0m0.014s
簡単ですが、以上です。