import { Schema, Error, Types } from 'mongoose'; import { RecipeCollection, RecipeCollectionProps, RecipeCollectionType, } from './collection-model'; import { Recipe } from '../recipe'; export interface ManualRecipeCollection extends RecipeCollection { addRecipe: (recipe: Recipe, options?: { order?: number }) => RecipeCollection; updateRecipe: ( this: RecipeCollection, recipe: Types.ObjectId | string, options?: { order?: number } ) => RecipeCollection; removeRecipe: (recipe: Types.ObjectId | string) => RecipeCollection; } export interface ManualRecipeCollectionProps extends RecipeCollectionProps {} const ManualCollectionSchema = new Schema({}, { discriminatorKey: 'type' }); // // Custom Methods // ManualCollectionSchema.methods = { /** * Add a group to the ingredientList */ async addRecipe( this: RecipeCollection, recipe: Recipe, options: { order?: number } = {} ) { const { order } = options; const colItem = this.nodes.create({ recipe: recipe.id }); // Throw: Already exists in collection if (this.nodes.findIndex(rcp => rcp.recipe.equals(recipe.id)) > -1) { throw new Error.ValidatorError({ message: 'This recipe already exists in the Collection', }); } if (order && order < this.nodes.length) { this.nodes.splice(order, 0, colItem); } else { this.nodes.push(colItem); } return this; }, /** * Update a group to the ingredientList */ updateRecipe( this: RecipeCollection, id: Types.ObjectId | string, options?: { order?: number } ) { const index = this.nodes.findIndex(rcp => rcp.recipe.equals(id)); if (index === -1) { throw new Error.ValidatorError({ message: 'Unable to Find Recipe in Collection', }); } const { order } = options; const recipe = this.nodes[index]; // move order if (order !== undefined && order < this.nodes.length) { const a = this.nodes.pull(recipe); this.nodes.splice(order, 0, recipe); } return this; }, /** * Remove a group to the ingredientList */ removeRecipe(this: RecipeCollection, id: Types.ObjectId | string) { const curLength = this.nodes.length; const a = this.nodes.pull({ recipe: id }); if (this.nodes.length === curLength) { throw new Error.ValidatorError({ message: 'No Matching Recipe was found in the collection', }); } return this; }, }; export const ManualRecipeCollection = RecipeCollection.discriminator< ManualRecipeCollection >(RecipeCollectionType.MANUAL, ManualCollectionSchema);