import { inputObjectType, FieldResolver, mutationField, arg } from '@nexus/schema'; import { Error } from 'mongoose'; import { ApolloError, AuthenticationError, UserInputError, } from 'apollo-server-micro'; import { authenticateQuery } from '../../../schema/authenticate-query'; import { isManualRecipeCollection } from '../utils'; export const UpdateRecipeInCollectionInput = inputObjectType({ name: 'UpdateRecipeInCollectionInput', definition(t) { t.id('recipeCollectionId', { required: true }); t.id('recipeId', { required: true }); t.int('order', { description: 'The new index of the recipe', }); }, }); export const updateRecipeInCollection: FieldResolver< 'Mutation', 'updateRecipeInCollection' > = async (root, args, ctx, info) => { const { user, abilities } = authenticateQuery(ctx); const { recipeCollectionId, recipeId, ...recipeOptions } = args.input; const collection = await user .getRecipeCollections() .accessibleBy(abilities) .findOne({ _id: recipeCollectionId }) .populate('nodes.recipe') .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' ); } try { await collection.updateRecipe(recipeId, recipeOptions); } catch (error) { if (error instanceof Error.ValidatorError) { throw new UserInputError(error.message); } else { throw new ApolloError('Unable to update the collection'); } } await collection.save(); return collection; }; export const UpdateRecipeInCollectionMF = mutationField( 'updateRecipeInCollection', { type: 'RecipeCollection', args: { input: arg({ type: 'UpdateRecipeInCollectionInput', }), }, resolve: updateRecipeInCollection, } );