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 https://localhost:${port}`)
})
in https://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 !