0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

zodベースでschemaを作成できるzgok-api

Last updated at Posted at 2024-08-15

zodベースでschemaを作成できるzgok-apiフレームワークを作成しました。

  • フロントエンド・バックエンドをTypeScriptで高速開発
  • Zodでスキーマを定義することで、フロント・バックのクライアントが自動生成されます
  • リクエスト送受信時にはZodによるバリデーションが実施され、安全が保たれます
  • TypeScriptのIDE補完ききます

schema作成

こんな感じで作成します。
front / backend双方から参照可能な位置に保存してください。

schema.ts
import { z } from "zod";
import { postFunction, getFunction, patchFunction } from "@zgok-api/zgok-core";

export const SampleSchema = {
  dir1: {
    hoge1: postFunction({
      req: z.object({ id: z.number() }),
      res: z.object({ name1: z.string() }),
    }),
    hoge2: getFunction({
      req: z.object({ id: z.number() }),
      res: z.object({ name2: z.string() }),
    }),
  },
  dir2: {
    moge: patchFunction({
      req: z.object({ key: z.string() }),
      res: z.object({ kind: z.object({ name: z.string() }) }),
    }),
  },
};

backend側

npm install zgok-express

先ほどのSchemaをZgokExpressに渡すと、handler functionとrouteが生成出来るようになります。
以下の処理では post "/api/dir1/hoge1" が生成されます。

.ts
const router = express.Router();
import { ZgokExpress } from "@zgok-api/zgok-express";

const zgokExpress = ZgokExpress(SampleSchema);
router.use(
  zgokExpress.dir1.hoge1(async (req, res) => {
    console.log("hoge3 zbody", req.zbody);
    return { name3: `${req.zbody.id}さん` };
  })
);
app.use("/api", router);

front側

npm install zgok-express

先ほど作成したSchemaを、ZgokAxiosに渡してクライアントを生成します。

.ts
import { ZgokAxios } from "@zgok-api/zgok-axios";

export const zgokAxios = ZgokAxios(
  Axios.create({ baseURL: "http://localhost:3000/api" }),
  SampleSchema
);

リクエストを送ると、expressで作成された post "/api/dir1/hoge1" へリクエストが送られます。

.ts
const hoge1 = async () => {
  const res = await zgokAxios.dir1.hoge1({ id: 1 });
  console.log("res", res);
};

その他

zgokDate

レスポンスにDateが含まれている場合、JSONの仕様上、文字列として返却されます。
そのままzodで検証すると型エラーとなってしまいます。
zodDateを使うと、レスポンスを自動的にDateへ変換します。

.ts
import { zgokDate } from "@zgok-api/zgok-core";

...

hoge3: postFunction({
  req: z.object({ id: z.number(), date1: zgokDate() }),
  res: z.object({ name3: z.string(), date2: zgokDate() }),
}),
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?