Async mutations - resolvers.js
GraphQL Essential Training
by Andrey Aires
JavaScript
import { Widgets } from './dbConnectors';
const resolvers = {
getProduct: async({id}) => {
try {
//Read Product
const productList = await Widgets.findById({_id: id}).exec()
return productList;
} catch (err) {
console.log(err);
}
},
getAllProducts: async () => {
try {
//Read Product
const productList = await Widgets.find()
return productList;
} catch (err) {
console.log(err);
}
},
createProduct: async ({input}) => {
const newWidget = new Widgets({
name: input.name,
description: input.description,
price: input.price,
soldout: input.soldout,
inventory: input.inventory,
stores: input.stores
});
newWidget.id = newWidget._id;
try {
//Create Product
const result = await newWidget.save()
return result;
} catch (err) {
console.log(err);
}
},
updateProduct: async ({input}) => {
try {
//Update Product
const result = await Widgets.findOneAndUpdate({ _id: input.id }, input, { new: true }).exec()
return result;
} catch (err) {
console.log(err);
}
},
deleteProduct: async ({id}) => {
try {
//Delete Product
const result = await Widgets.deleteOne({_id: id})
return 'Successfully Deleted Product ID: ' + id ;
} catch (err) {
console.log(err);
}
}
};
export default resolvers;