index.ts:
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }: any) => ({ req, res })
});
UserSchema.ts
export const typeDefs = gql`
scalar TimeStamp
type Query {
getUser(id: Int!): User
}
type Mutation {
addUser(
name: String!
email: String
age: Int
register_at: TimeStamp!
): Boolean!
}
type User {
id: Int!
name: String!
email: String!
age: Int!
register_at: TimeStamp!
}
`;
UserResolver.ts
export const resolvers = {
TimeStamp: timeStamp,
Query: {
getUser: async (_: any, args: any) => {
const { id } = args;
return await User.findOne({ where: { id: id } });
}
},
Mutation: {
addUser: async (_: any, args: any) => {
const { name, email, age, register_at } = args;
try {
const user = User.create({
name,
email,
age,
register_at
});
await user.save();
return true;
} catch (error) {
return false;
}
}
}
};
我想知道如果我有额外的类型定义和解析器,例如
BookSchema.ts
和BookResolver.ts
,该如何初始化我的Apollo Server实例。
Query
或Mutation
)拆分成多个文件时才是必需的。您不能定义超过一次Query
,但可以添加extend
关键字将定义转换为扩展。 - Daniel Reardentype Query
没有字段 - 这样你就可以在所有其他文件中使用extend type Query
。我更新了最终的例子,加入了更多的细节。希望这有所帮助。 - Daniel Rearden