簡體   English   中英

如何從 Typescript 模式創建 GraphQL 類型 SDK?

[英]How to create a GraphQL typed SDK from a Typescript schema object?

我有一個代碼優先的 GraphQL API ,其中 GraphQLSchema 是這樣創建的:

import { GraphQLSchema } from 'graphql';
import { mutationType } from './mutation';
import { queryType } from './query';

const schema = new GraphQLSchema({
  query: queryType,
  mutation: mutationType,
});

export { schema };

我知道如何使用printSchema(schema)生成用模式定義語言 (SDL) 編寫的模式。

現在我需要一個 SDK 來提供給我的 API 的客戶。 我的問題是我找不到任何用於從模式中生成類型化 SDK 的庫。

我發現的諸如graphql-requesturqlapollo-client之類的庫使您無需任何類型的語法檢查即可編寫整個查詢。

import { gql, GraphQLClient } from 'graphql-request'

const query = gql`               //
  {                              //
    Movie(title: "Inception") {  // I can write whatever I want
      releaseDate                // here and no transpilation
      actors {                   // errors will appear.
        name                     // I have no autocompletion
      }                          // whatsoever.
    }                            //
  }                              //
`
const client = new GraphQLClient('https://api.graph.cool/simple/v1/movies', { headers: {} })
client.request(query, variables).then((data) => console.log(data))

我希望能夠做類似const client = new GraphQLClient(endpoint, schema, options); . 然后像這樣使用它await client.movie(title)({releaseDate: true, actors: {name: true}}); . 不一定使用那種語法,但我希望這能讓你明白這一點。 如果我寫rleaseDate我只想在我的 IDE 下有一條紅線,如果我運行tsc則會出現編譯錯誤。

我找到了 graphql-code-generator ,我發現它可以使用printSchema(schema)生成的模式生成不同的東西。 但是對於可以生成我想要的 SDK 的 typescript-graphql-request 插件,看來我需要自己編寫一個 operation.graphql 文件,這是我要避免的第一件事。 正如我所說,API 是代碼優先的,一切都在我開始討論的模式中。 我不想在那個 operation.graphql 文件中找到第二個事實來源。

我想要的存在嗎?

好吧:所以我找到了我要找的東西: graphql-zeus

命令zeus [path to SDL file] --typescript --node生成一個 SDK 我可以提供給將使用 API 的客戶端,他們可以使用 ZF20E3C5E54C0AB3D375D660B3F89FZ,例如:

import { Chain } from "[SDK generated]";

Chain(`example.com/graphql`, {
  headers: {
    'Authorization': 'Bearer 00112233445566778899',
    'Content-Type': 'application/json',
  },
})('mutation')({
    createUser: [{
      username: newUsername,
      biography: newBio,
      picture: newPicture,
    },
  { id: true, username: true }]
})
  .catch(error => {
     // Do something
});

mutation ,操作createUser和它的參數被輸入。 這意味着我會收到翻譯錯誤,IDE 會告訴我可以在每個字段中輸入什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM