Ccmmutty logo
Commutty IT
0 pv3 min read

データ取得用の React Hooks を作りました

https://cdn.magicode.io/media/notebox/b8bb08e4-a043-4da1-95bf-026c32017167.jpeg
ソース: hyori/github
READMEと合わせて使い方を記載します。
大まかな手順は、
  1. 型ジェネレータをつくる
  2. BE,FEの順でジェネレータを呼び出す
これだけです。
あとは、useApiQueryまたはuseApiMutationを適宜呼び出すだけの簡単なお仕事となっています。

型ジェネレータをつくる

openapi-typescriptの一例です。
// openapi-typescript.js
import fs from "node:fs"
import openapiTS from "openapi-typescript"

const ref = "localhost:backend-path" // BE の OpenAPI 仕様書(通常は JSON 形式)のエンドポイントのパスを指定
const output = "./src/schema.gen.ts" // FE の 好きな場所を指定

const types= await openapiTS(ref, {
  transform: (schemaObject) => {
    if ("format" in schemaObject && schemaObject.format === "binary"){
      return schemaObject.nullable ?? "File | null " : "File";
    }
  },
  alphabetize: true,
});

fs.writeFileSync(output, types);
const ref = "localhost:backend-path"の部分はバックエンドのOpenAPI 仕様書生成エンドポイントを指定してください。
Python, Ruby, Rust, Javaでは OpenAPI があることを確認しています。

BE,FEの順でジェネレータを呼び出す

バックエンドの OpenAPI が生成されていることを確認した後、以下を実行する
pnpm node openapi-typescript.js
上記 output で指定した gen.ts が作成されていればOKです。
/**
 * This file was auto-generated by openapi-typescript.
 * Do not make direct changes to the file.
 */


export interface paths {
}

export type webhooks = Record<string, never>;

export interface components {
  schemas: {
  };
  responses: never;
  parameters: never;
  requestBodies: never;
  headers: never;
  pathItems: never;
}

export type $defs = Record<string, never>;

export type external = Record<string, never>;

export interface operations {
}

// ...
以下、手順はREADMEを見ていただければと思います。
本日は以上になります。

Discussion

コメントにはログインが必要です。