[英]Cannot query field \"addWorkout\" on type \"Mutation\
I am fairly new to GraphQL, my previous question was regarding some reference error I was getting which I eventually resolved, however, now I am getting this error.我对 GraphQL 相当陌生,我之前的问题是关于我最终解决的一些参考错误,但是,现在我遇到了这个错误。 It seems that I cannot add a workout as it doesn't recognize that it is a mutation field within the schema.似乎我无法添加锻炼,因为它无法识别它是模式中的突变字段。
I keep getting the error of我不断收到错误
Cannot query field \"addWorkout\" on type \"Mutation\
Anyway, on app.js, this is my code无论如何,在 app.js 上,这是我的代码
const express = require("express")
const app = express();
const userSchema = require("./graph-schema/userQueries")
const workoutSchema = require("./graph-schema/workoutQueries")
const mealSchema = require("./graph-schema/mealQueries")
const mongoose = require("mongoose")
const {mergeSchemas} = require("graphql-tools")
//connect to mongoDB atlase database
mongoose.connect("mongodb+srv://Zubair97:superman2008@cluster0-epauj.mongodb.net/test?retryWrites=true&w=majority")
mongoose.connection.once("open", () => {
console.log("Connected to database")
})
const combinedSchemas = mergeSchemas({
schemas: [
userSchema,
mealSchema,
workoutSchema
],
})
//this module allows express to communicate with graphql ;
//we use it as a single endpoint
const graphqlHTTP = require("express-graphql")
app.use("/graphql" , graphqlHTTP({
schema: combinedSchemas,
graphiql: true
}))
app.listen(4000, () => {
console.log(`Listening on port 4000`)
})
The workout queries and mutations are defined in a file called workoutQueries.js, which I have exported, you can see that I have addWorkout defined in the resolvers锻炼查询和突变在我导出的一个名为 trainingQueries.js 的文件中定义,您可以看到我在解析器中定义了 addWorkout
const graphql = require("graphql")
const {WorkoutType} = require("./schema")
const Workout = require("../models/Workout.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;
const WorkoutQuery = new GraphQLObjectType({
name: "WorkoutQuery",
fields: () => ({
workout: {
type: WorkoutType,
args: {id: {type: GraphQLID}},
resolve(parent, args){
//returns the workout instance from the database
return Workout.findById(args.id)
}
},
workouts: {
type: new GraphQLList(WorkoutType),
resolve(parent, args){
//returns all workouts from the databse
return Workout.find({})
}
}
})
})
const WorkoutMutation = new GraphQLObjectType({
name: "WorkoutMutation",
addWorkout: {
type: WorkoutType,
args: {
name: {type: GraphQLString},
reps: {type: GraphQLInt},
sets: {type: GraphQLInt},
burnedCalories: {type: GraphQLInt},
userId: {type: GraphQLID},
},
resolve(parent, args){
let workout = new Workout({
name: args.name,
reps: args.reps,
sets: args.sets,
burnedCalories: args.burnedCalories,
userId: args.userId
})
return workout.save();
}
},
})
module.exports = new GraphQLSchema({
query: WorkoutQuery,
mutation: WorkoutMutation
})
Also, this issue is occurring even if I try to add a meal, the queries and mutations are defined at a file called mealQueries.js, which I have exported此外,即使我尝试添加餐点,也会发生此问题,查询和突变是在名为 mealQueries.js 的文件中定义的,我已导出该文件
const graphql = require("graphql")
const {MealType, NutritionType} = require("./schema")
const Meal = require("../models/Meal.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;
const MealQuery = new GraphQLObjectType({
name: "MealQueries",
fields: () => ({
meal: {
type: MealType,
args: {id: {type: GraphQLID}},
resolve(parent, args){
return Meal.findById(args.id)
}
},
meals: {
type: new GraphQLList(MealType),
resolve(parent, args){
return Meal.find({})
}
}
})
})
const MealMutation = new GraphQLObjectType({
name: "MealMutation",
addMeal: {
type: MealType,
args: {
name: {type: GraphQLString},
servings: {type: GraphQLInt},
calories: {type: GraphQLInt},
nutrition: {type: NutritionType},
userId: {type: GraphQLID}
},
resolve(parent, args){
let meal = new Meal({
userId: args.userId,
name: args.name,
servings: args.servings,
calories: args.calories,
nutrition: {
carbohydrates: args.nutrition.carbohydrates,
fats: args.nutrition.fats,
proteins: args.nutrition.proteins
}
})
return meal.save();
}
}
})
module.exports = new GraphQLSchema({
query: MealQuery,
mutation: MealMutation
})
I have no issue in creating a user and authenticating a user, the queries and mutation for that are defined in userQueries.js我在创建用户和验证用户时没有问题,在 userQueries.js 中定义了查询和变异
const graphql = require("graphql")
const User = require("../models/User.js")
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const {AuthType, UserType} = require("./schema")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;
const UserQuery = new GraphQLObjectType({
name: "UserQuery",
fields: () => ({
user: {
type: UserType,
args: {id: {type: GraphQLID}},
resolve(parent, args){
//returns the user from the database
return User.findById(args.id)
}
},
login: {
type: AuthType,
args: {email: {type: GraphQLString}, password: {type: GraphQLString}},
resolve(parent, {email, password}){
return User.findOne({email: email}).then((user) => {
const isEqual = bcrypt.compare(password, user.password)
if (!isEqual) {
throw new Error('Password is incorrect!');
}
const token = jwt.sign({
userId: user.id,
email: user.email},
"a_super_secret",
{expiresIn: "1h"}
)
return {token: token, userId: user.id}
})
}
}
})
})
const UserMutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addUser: {
type: UserType,
args: {
name: {type: GraphQLString},
email: {type: GraphQLString},
password: {type: GraphQLString}
},
async resolve(parent, args){
const existingUser = await User.findOne({email: args.email})
if (!existingUser){
const error = new Error("User already exists");
}
const encryptedPassword = await bcrypt.hash(args.password, 12)
let user = new User({
name: args.name,
email: args.email,
password: encryptedPassword
})
const createdUser = user.save();
return createdUser
}
}
}
})
module.exports = new GraphQLSchema({
query: UserQuery,
mutation: UserMutation,
})
I have also defined the UserType, AuthType, MealType, NutritionType and WorkoutType in a file called schema.js我还在一个名为 schema.js 的文件中定义了 UserType、AuthType、MealType、NutritionType 和 WorkoutType
const graphql = require("graphql")
const Workout = require("../models/Workout.js")
const User = require("../models/User.js")
const Meal = require("../models/Meal")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;
//describes what attributes and its types, a User has in each query
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
email: {type: GraphQLString},
password: {type: GraphQLString},
workouts: {
type: new GraphQLList(WorkoutType),
resolve(parent, args){
//returns all the workouts created by a user
return Workout.findById({userId: parent.id})
}
},
meals: {
type: new GraphQLList(MealType),
resolve(parent, args){
//returns all the meals created by a user
return Meal.findById({userId: parent.id})
}
}
})
})
const NutritionType = new GraphQLObjectType({
name: "Nutrition",
fields: () => ({
carbohydrates: {type: GraphQLInt},
fats: {type: GraphQLInt},
proteins: {type: GraphQLInt}
})
})
const WorkoutType = new GraphQLObjectType({
name: "Workout",
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
reps: {type: GraphQLInt},
burnedCalories: {type: GraphQLInt},
sets: {type: GraphQLInt},
user: {
type: UserType,
resolve(parent, args){
//returns the user from the database that created the workout instance
return User.findById(parent.userId)
}
}
})
})
const AuthType = new GraphQLObjectType({
name: "Authentication",
fields: () => ({
token: {type: GraphQLString},
userId: {type: GraphQLString}
})
})
const MealType = new GraphQLObjectType({
name: "Meal",
fields: () => ({
id: {type: GraphQLID},
calories: {type: GraphQLInt},
servings: {type: GraphQLInt},
nutrition: {type: NutritionType},
user: {
type: UserType,
resolve(parent, args){
//returns the user from the database that created the meal instance
return User.findById(parent.userId)
}
}
})
})
module.exports = {
AuthType,
WorkoutType,
UserType,
MealType,
NutritionType
}
I suspect the error I am getting is due to mergeSchema object from graphql-tools, maybe it cannot merge the GraphQLSchema types properly?我怀疑我得到的错误是由于来自 graphql-tools 的 mergeSchema 对象,也许它无法正确合并 GraphQLSchema 类型? I am not sure.我不确定。 Any help is appreciated!任何帮助表示赞赏!
mergeSchemas
is intended to be used with schema stitching . mergeSchemas
旨在与模式拼接一起使用。 It should not be used just to modularize your single schema, which is what you're trying to do here.它不应该仅仅用于模块化您的单一架构,这正是您在这里尝试做的。
You should only create a single GraphQLSchema
object, a single GraphQLObjectType
for your query root type and a single GraphQLObjectType
for your mutation root type.您应该只创建一个单一的GraphQLSchema
对象,单个GraphQLObjectType
您所查询的根型和单一GraphQLObjectType
为您的突变根类型。 If you want the fields for a specific type, like your Mutation
type, to be spread across multiple modules, then you should export just those fields , not an entire type or schema.如果您希望特定类型的字段(例如Mutation
类型)分布在多个模块中,那么您应该只导出这些字段,而不是整个类型或模式。
module.exports = {
queries: {
workout: { ... },
workouts: { ... },
},
mutations: {
addWorkout: { ... },
},
}
Whatever file you create your schema in can then import these fields from multiple modules and combine them into an individual schema.无论您在哪个文件中创建架构,都可以从多个模块导入这些字段并将它们组合成单个架构。
const query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
...require('moduleA').queries,
...require('moduleB').queries,
...require('moduleC').queries,
}),
})
const mutation = new GraphQLObjectType({ ... })
const schema = new GraphQLSchema({ query, mutation })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.