【发布时间】:2022-01-05 00:10:51
【问题描述】:
我是新手,请耐心等待。我正在尝试这种突变
mutation{
createUser(userInput:{email:"test21m@g.com", password:"1223"}){
_id
email
}
}
但我收到此错误:
"message": "字段 "createUser" 不能有选择,因为类型 "[String]" 没有子字段。",
文件结构如下 schema.js
const {buildSchema} = require('graphql')
module.exports = buildSchema(`
type Booking{
_id: ID!
event:Event!
user: User!
createdAt: String!
updatedAt: String!
}
type Event {
_id:ID!
title:String!
description:String!
price:Float!
date:String!
creator:String!
}
type User{
_id: ID!
email: String!
password: String
createdEvents:[Event!]
}
type AuthData{
userId: ID!
token: String!
tokenExpiration: Int!
}
input EventInput {
title:String!
description:String!
price:Float!
date:String!
}
input UserInput{
email:String!
password:String!
}
type RootQuery {
events:[Event!]!
bookings: [Booking!]!
login(email: String!, password: String!): AuthData!
}
type RootMutation{
createEvent(eventInput : EventInput):[String]
createUser(userInput: UserInput):[String]
bookEvent(eventId: ID!): Booking!
cancelBooking(bookingId: ID!): Event!
}
schema {
query : RootQuery
mutation: RootMutation
}
`)
auth-resover.js
const bcrypt = require('bcryptjs')
const User = require('../../models/user')
const jwt = require('jsonwebtoken')
module.exports = {
// Create User Resolver __________________________________________________
createUser: async args =>{
try{
const existingUser = await User.findOne({email:args.userInput.email})
if(existingUser) throw new Error('User exists already.')
const hashedPassword = await bcrypt.hash(args.userInput.password, 12)
const user = new User({
email: args.userInput.email,
password: args.userInput.password
})
const result = await user.save()
return {...result._doc, password:null, _id: result.id}
}catch(err) { throw err }
},
// end of User Resolver __________________________________________________
//this name has to match the name in "type RootQuery" schema-index.js
login: async({email, password}) => {
const user = await User.findOne({email:email})
if(!user) throw new Error('Invalid Cridentials: user not found')
const isEqual = await bcrypt.compare(password, user.password)
if(!isEqual) throw new Error('Invalid Cridentials: password is incorrect')
const token = await jwt.sign(
{userId: user.id, email: user.email},
'superLongerSuperSecretKey',
{expriresIn:'1h'})
return {
userId: user.id,
token: token,
tokenExpiration: 1}
}
}
【问题讨论】:
标签: javascript graphql schema mutation resolver