I'm testing my GraphQL API, but I would like to clean it up a little bit. It's worth noting I'm using chai-http
for the network requests. Here's what I'm currently doing (which works):
let createUser = (()=> {
return new Promise((resolve, reject) => {
chai.request(server)
.post('/api/graphql/')
.set('content-type', 'application/json')
.send({ 'query' :
'mutation users { \
user : addUser(inputs: { \
firstName: \"Test\", \
lastName: \"User\", \
email: \"[email protected]\", \
}) { \
id, \
firstName \
} \
}'
})
.end((err, res) => {
if (err) { reject(err) }
let data = res.body.data;
let user = data.user;
resolve(user);
})
});
});
However, I would like to clean it up a bit and do something like this:
let createUser = (() => {
let newUser = {
firstName: 'Test',
lastName: 'User',
email: '[email protected]'
};
return new Promise((resolve, reject) => {
chai.request(server)
.post('/api/graphql/')
.set('content-type', 'application/json')
.send({ 'query' :
'mutation users { \
user : addUser(inputs: ' + JSON.stringify(newUser) + ') { \
id, \
firstName \
} \
}'
})
.end((err, res) => {
if (err) { reject(err) }
let data = res.body.data;
let user = data.user;
resolve(user);
})
});
});
However, this style does of placing the object inputs does not work and returns a bad request error. Here is what part of the returned error object reads:
Any ideas why this doesn't work? Thanks in advance!
Looks like there's an issue with your JSON input there. It could be some combination of your line breaks and your quotes that's not getting parse properly on the server.
However, I still wouldn't recommend in-lining your variables like that in your GraphQL query. You should do something like this instead:
let createUser = (() => {
let newUser = {
firstName: 'Test',
lastName: 'User',
email: '[email protected]'
};
return new Promise((resolve, reject) => {
chai.request(server)
.post('/api/graphql/')
.set('content-type', 'application/json')
.send({
'query' : 'mutation users ($input: CreateUserInput!) { \
user : addUser(inputs: $input) { \
id, \
firstName \
} \
}',
'variables' : {
'input': newUser
}
})
.end((err, res) => {
if (err) { reject(err) }
let data = res.body.data;
let user = data.user;
resolve(user);
})
});
});
You can check out another simple example here as to how you can execute a mutation on Scaphold to create a user with query
and variables
split out.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With