import { inputObjectType, FieldResolver, mutationField, arg, objectType, } from '@nexus/schema'; import { authenticateQuery } from '../../../schema/authenticate-query'; import { AuthenticationError, UserInputError } from 'apollo-server-micro'; import { Recipe, recipeSchema } from '../../recipe'; import { isManualRecipeCollection } from '../utils'; export const AddRecipesToCollectionInputType = inputObjectType({ name: 'AddRecipesToCollectionInput', definition(t) { t.id('recipeCollectionId', { required: true }); t.list.id('recipes', { description: 'Array of Recipe IDs', required: true, }); t.int('order', { description: 'The index to place the ' }); }, }); export const AddRecipesToCollectionPayload = objectType({ name: 'AddRecipesToCollectionPayload', definition(t) { t.field('recipeCollection', { type: 'ManualRecipeCollection', description: 'The Updated Collection', }); t.list.id('addedRecipes', { description: 'Array of Recipe IDs successfully added to the collection', }); t.list.id('rejectedRecipes', { description: 'Array of Recipe IDs not able to be added by to the collection', }); }, }); export const addRecipesToCollection: FieldResolver< 'Mutation', 'addRecipesToCollection' > = 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 for Smart Collections' ); } const addedRecipes: string[] = []; const rejectedRecipes: string[] = []; const recipeDocs = await Recipe.find({ _id: { $in: recipes, }, }).exec(); recipes.forEach(async id => { const recipe = recipeDocs.find(r => { return r.id === id; }); try { if (!recipe) { throw 'Recipe doesnt exist or you dont have permission to add it'; } if (!recipe.ownerId.equals(user.id)) { throw 'Recipe doesnt exist or you dont have permission to add it'; } await collection.addRecipe(recipe); addedRecipes.push(id); } catch (e) { rejectedRecipes.push(id); } }); await collection.save(); await collection.populate('nodes.recipe').execPopulate(); return { addedRecipes, rejectedRecipes, recipeCollection: collection, }; }; export const AddRecipesToCollectionMF = mutationField( 'addRecipesToCollection', { type: 'AddRecipesToCollectionPayload', args: { input: arg({ type: 'AddRecipesToCollectionInput', }), }, resolve: addRecipesToCollection, } );