[英]Graphql apollo server resolvers arguments types
如果在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
- 对于没有父级的顶级字段的解析器(例如Query
、 Mutation
的字段),此值为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.