使用graphql-codegen为Kibela API生成类型定义文件

我想做的事情

我希望用环境变量管理以下的变量。

    • AuthorizationヘッダーのBearerトークン

 

    サブドメインのチーム名(https://XXXX.kibe.la/api/v1)

要做的事情 zuò de

安装与 graphql-codegen 相关的 npm 包裹

npm i -D @graphql-codegen/cli @graphql-codegen/import-types-preset @graphql-codegen/typescript @graphql-codegen/typescript-operations

創建 codegen 使用設定檔案。

require("dotenv").config();

module.exports = {
  schema: [
    {
      [`https://${process.env.KIBELA_TEAM_NAME}.kibe.la/api/v1`]: {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.KIBELA_API_TOKEN}`,
        },
      },
    },
  ],
  overwrite: true,
  generates: {
    "./@types/kibela.d.ts": {
      plugins: ["typescript"],
    },
  },
};

当你运行 npx graphql-codegen,会在 @types/ 中生成一个 kibela.d.ts 文件。

生成的类型定义文件的使用示例↓

import nodeFetch from "node-fetch";
import { print as printGql } from "graphql/language/printer";
import { ASTNode } from "graphql/language/ast";
import gql from "graphql-tag";
import type { User } from "../@types/kibela.d";

const callAPI = async (query: ASTNode): Promise<any> => {
  const response = await nodeFetch(`https://${process.env.KIBELA_TEAM_NAME}.kibe.la/api/v1`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.KIBELA_API_TOKEN}`,
      "Content-Type": "application/json",
      Accept: "application/json",
      "User-Agent": "HogeHoge",
    },
    body: JSON.stringify({
      query: printGql(query),
      variables: {},
    }),
  });

  if (!response.ok) {
    const body = await response.text();
    throw new Error(`not ok: ${response.statusText}\n${body}`);
  }
  const result = await response.json();
  return result.data;
};

export const getUsers = async (): Promise<User[]> => {
  const query = gql`
    query {
      group(id: "${process.env.KIBELA_HOME_ID}") {
        users(first: 100) {
          nodes {
            id
            realName
          }
        }
      }
    }
  `;

  const data = await callAPI(query);
  return data.group.users.nodes;
};
广告
将在 10 秒后关闭
bannerAds