LoginSignup
1
1

More than 3 years have passed since last update.

graphql-codegenでKibelaAPI用型定義ファイルを生成する

Last updated at Posted at 2021-02-19

やりたいこと

以下の変数を環境変数で管理したい

やること

graphql-codegen周りのnpmパッケージをインストール

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

codegen用設定ファイルを作成

codegen.js
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が生成されます。

生成した型定義ファイルの使用例↓

src/kibela.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;
};
1
1
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
1
1