import { inputObjectType, FieldResolver, mutationField, arg, objectType, } from '@nexus/schema'; import { AuthenticationError, UserInputError } from 'apollo-server-micro'; import { authenticateQuery } from '../../../schema/authenticate-query'; import { isManualRecipeCollection } from '../utils'; export const RemoveRecipesFromCollectionInput = inputObjectType({ name: 'RemoveRecipesFromCollectionInput', definition(t) { t.id('recipeCollectionId', { required: true }); t.list.id('recipes', { description: 'Array of Recipe IDs', required: true, }); }, }); export const RemoveRecipesFromCollectionPayload = objectType({ name: 'RemoveRecipesFromCollectionPayload', definition(t) { t.field('recipeCollection', { type: 'ManualRecipeCollection', description: 'The Updated Collection', }); t.list.id('removedRecipes', { description: 'Array of Recipe IDs successfully removed from the collection', }); t.list.id('rejectedRecipes', { description: 'Array of Recipe IDs not able to be deleted from to the collection', }); }, }); export const removeRecipesFromCollection: FieldResolver< 'Mutation', 'removeRecipesFromCollection' > = async (root, args, ctx, info) => { const { user, abilities } = authenticateQuery(ctx); const { recipeCollectionId, recipes } = args.input; const collection = await user .getRecipeCollections() .accessibleBy(abilities) .findOne({ _id: recipeCollectionId }) .exec(); if (collection === null) { throw new AuthenticationError( 'You do not have permission to update this Collection' ); } if (!isManualRecipeCollection(collection)) { throw new UserInputError( 'This mutation is not allowed on Smart Collections' ); } const removedRecipes: string[] = []; const rejectedRecipes: string[] = []; recipes.forEach(async id => { try { await collection.removeRecipe(id); removedRecipes.push(id); } catch (e) { rejectedRecipes.push(id); } }); await collection.save(); await collection.populate('nodes.recipe').execPopulate(); return { removedRecipes, rejectedRecipes, recipeCollection: collection, }; }; export const RemoveRecipesFromCollectionMF = mutationField( 'removeRecipesFromCollection', { type: 'RemoveRecipesFromCollectionPayload', args: { input: arg({ type: 'RemoveRecipesFromCollectionInput', }), }, resolve: removeRecipesFromCollection, } );