記事

バックエンドから生成されたswaggerの型に寄せないで、フロントで書いた型とバックエンドの型を緩衝材となるような層を作りたい

#tech

appRouter

  • app
    • ルーティングだけを担当する
  • feature
    • ルーティングからきたコンポーネントをレンダリング
    • component
    • hooks
    • type
      • ここでフロントで描画するための型を配置する
      • frontendType
        • viewでレンダリングに必要な型をここから引っ張ってくる
      • backendType
        • バックエンドから必要な型をとってくる
      • adapters
        • frontendTypeとbackendTypeを繋ぎ込み
          • import { BackendType } from '../types/backendType';
            import { FrontendType } from '../types/frontendType';
            
            // viewで使うためのデータに変換するから,返り値がFrontendTypeになる
            export const userAdapter = (data: BackendType): FrontendType => {
              return {
                id: data.id,
                name: data.name,
                description: data.description,
                image: data.image,
                link: data.link,
              };
            };
            // こんな感じの関数を書く

でも、frontTypeとbackendTypeの繋ぎ込みはどうやるのか??

  • 解決済み

orvalで生成したhooksのdataにフロントエンドの型を当てるには?

  • import {
      useTechnicalInformationControllerGetAuthorTechnicalInformation,
      useTechnicalInformationControllerGetTechnicalInformation,
      useTechnicalInformationControllerGetTechnicalInformations,
    } from '@/api-client/client/technical-information/technical-information';
    import { BackendType } from '../types/backendType';
    
    export const useInfoSearch = () => {
      const { data, isLoading, isError } =
        useTechnicalInformationControllerGetTechnicalInformations<{
        // ここに書けば,dataがその型になる
          data: Array<{
            id: string;
            name: string;
            description: string;
            image: string;
            link: string;
          }>;
        }>();
      console.log(data?.data);
      return {
        technicalInformationList: data?.data,
        isLoading,
        isError,
      };
    };
    // こうやってしまうと、API側の型を全て握り潰すので良くないか??
  • 結局は、API側の型とフロントの方が大幅に異なると、ダメなので、その時は諦めて、フロントエンドの型を諦める

https://github.com/reflllc/sekine-fe/pull/224/files

  • ここに作ってみた

でもこれって、バックエンドがある状態で作ってしまった

よくあるのは、UIを作って、

© 2026 Shotaro Kinjo