Learning graphql, cannot get mutation to work yet, get lost on the online examples.
import express from 'express'
import cors from 'cors'
import { graphqlHTTP } from 'express-graphql'
import { makeExecutableSchema } from '@graphql-tools/schema'
const app = express()
const port = 4000
// In-memory data store
const data = {
warriors: [
{ id: '001', name: 'Jaime' },
{ id: '002', name: 'Jorah' },
],
}
// Schema
const typeDefs = `
type Warrior {
id: ID!
name: String!
}
type Query {
warriors: [Warrior]
}
type Mutation {
addUser(name: String!): Warrior!
}
`
// Resolver for warriors
const resolvers = {
Query: {
warriors: (obj, args, context) => context.warriors,
},
Mutation: {
//addUser: (parent: unknown, args: {name: String}) => {
addUser: (name) => {
console.log('------ 1 ----------');
const id = String(data.warriors.length + 1);
const warrior = {id, name};
console.dir(warrior);
console.log('------ 3 ----------');
data.warriors.push(warrior);
return data.warriros;
},
},
}
const executableSchema = makeExecutableSchema({
typeDefs,
resolvers,
})
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// Entrypoint
app.use(
'/graphql',
graphqlHTTP({
schema: executableSchema,
context: data,
graphiql: true,
})
)
app.listen(port, () => {
console.log(`Running a server at http://localhost:${port}`)
})
in http://localhost:4000/graphql i tried to run this, but the name passed in is always undefined
mutation {
addUser(name: "ccc") {
id
}
}
Any suggestions pls ? Thx !
Updated answer from below
// Resolver for warriors
const resolvers = {
Query: {
warriors: (obj, args, context) => context.warriors,
},
Mutation: {
addUser: (_, {name}) => {
const id = String(data.warriors.length + 1);
const warrior = {id, name};
data.warriors.push(warrior);
return warrior;
},
},
}
You need to deconstruct the args to get your name
variable. Right now you are treating the parent
argument of the mutation as name
and the parent arg is undefined.
The function signature is:
myMutation: (parent,args,context,info) =>
So try:
Mutation: {
addUser: (_, { name }) => {
const id = String(data.warriors.length + 1);
const warrior = {id, name};
data.warriors.push(warrior);
return warrior;
},
}
Also your mutation expects a single Warrior
type as a result, not the whole array.