import { inputObjectType, mutationField, arg } from '@nexus/schema'; import { ForbiddenError } from 'apollo-server-micro'; import { authenticateQuery } from '../../../schema/authenticate-query'; import { IngredientItemType, IngredientInputType } from '.'; import { Recipe } from '../../../app/recipe'; export const AddIngredientInputType = inputObjectType({ name: 'AddIngredientInput', definition(t) { t.id('recipeId', { required: true, description: 'ID of the recipe you are adding to', }); t.field('ingredient', { type: IngredientInputType, required: true }); t.int('order'); t.id('groupId'); }, }); /** * Fetch a single Recipe */ export const addIngredientMF = mutationField('addIngredient', { type: 'IngredientItem', args: { input: arg({ type: AddIngredientInputType, description: 'Recipe Details' }), }, resolve: async (root, args, ctx, info) => { const { abilities } = authenticateQuery(ctx); const { order, groupId, ingredient, recipeId } = args.input; // find recipe const recipe = await Recipe.findById(recipeId).accessibleBy(abilities); if (recipe == null) { throw new ForbiddenError( 'You do not have access to this recipe, or it does not exist' ); } if (!recipe.ingredientList) { recipe.set('ingredientList', {}); } const newIngredient = recipe.ingredientList.addIngredient(ingredient, { order, groupId, }); await recipe.save(); return newIngredient; }, });