簡體   English   中英

Graphql apollo 服務器解析器 arguments 類型

[英]Graphql apollo server resolvers arguments types

類型腳本顯示錯誤,未提及每個 arguments 的參數類型:

  Mutation: {
    createUser: (parent, args, context, info) =>{

    }

我可以使用任何類型來解決,但正確的類型是什么?

  Mutation: {
    createUser: (parent: any, args: any, context: any, info: any) =>{

    }

在此處輸入圖像描述

如果在tsconfig.json中啟用所有嚴格的類型檢查選項,則應為所有內容添加 TS 類型。

我們來看看解析器的類型。

export declare type IFieldResolver<TSource, TContext, TArgs = Record<string, any>> = (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo & {
 mergeInfo: MergeInfo;
}) => any;

旋轉變壓器 arguments:

parent - 對於沒有父級的頂級字段的解析器(例如QueryMutation的字段),此值為undefined 所以 TS 類型是undefined

args - 從類型中可以看出,它必須滿足泛型約束Record<string, any>中的類型參數。 由於實際參數是從 Graphql 客戶端傳遞的,因此我們需要為每個解析器定義Args類型/接口。

context - 這是一個通用參數,我們需要自己定義應用程序上下文接口。

info - TS 類型已經存在GraphQLResolveInfo & { mergeInfo: MergeInfo }

一個工作示例:

例如

import express from 'express';
import { ApolloServer, gql, MergeInfo } from 'apollo-server-express';
import { GraphQLResolveInfo } from 'graphql';

const app = express();

const typeDefs = gql`
  type User {
    email: String!
  }
  type Query {
    user: User
  }
  type Mutation {
    createUser(email: String!, password: String!): Boolean
  }
`;

export declare type IFieldResolver<TSource, TContext, TArgs = Record<string, any>> = (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo & {
 mergeInfo: MergeInfo;
}) => any;

type CreateUserArgs = {
  email: string;
  password: string;
};

interface AppContext {
  userService: UserService;
}

const resolvers = {
  Query: {},
  Mutation: {
    createUser: (
      parent: undefined,
      args: CreateUserArgs,
      context: AppContext,
      info: GraphQLResolveInfo & { mergeInfo: MergeInfo },
    ) => {
      console.log(parent);
      return context.userService.createUser(args.email, args.password);
    },
  },
};

interface UserService {
  createUser(email: string, password: string): boolean;
}
class UserServiceImpl {
  createUser(email: string, password: string) {
    return true;
  }
}
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: {
    userService: new UserServiceImpl(),
  },
});
server.applyMiddleware({ app, path: '/graphql' });
app.listen(8080, () => console.log('Apollo server started at http://localhost:8080'));

package 版本:

"typescript": "^3.9.6",
"apollo-server": "^2.15.1",
"graphql": "^14.6.0",

GraphQL 在客戶端查詢:

mutation{
  createUser(email: "teresa@gmail.com", password: "1234")
}

回復:

{
  "data": {
    "createUser": true
  }
}

登錄服務器端:

Apollo server started at http://localhost:8080
undefined

暫無
暫無

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

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