diff --git a/backend/src/models/block.ts b/backend/src/models/block.ts index 3162afe..67b0b0d 100644 --- a/backend/src/models/block.ts +++ b/backend/src/models/block.ts @@ -89,6 +89,7 @@ export interface BlockDoc extends Document { ) => Promise; deleteChild?: (this: BlockDoc, childId: string) => Promise; deleteCascade?: (this: BlockDoc) => Promise; + findIndexFromChildIdList?: (this: BlockDoc, childId: string) => number; } BlockSchema.statics.createOne = async function ( @@ -167,9 +168,7 @@ BlockSchema.methods.deleteChild = async function ( this: BlockDoc, childId: string, ): Promise { - const index = this.childIdList.findIndex( - (_childId) => _childId.toHexString() === childId, - ); + const index = this.findIndexFromChildIdList(childId); this.childIdList.splice(index, 1); await this.save(); }; @@ -185,4 +184,13 @@ BlockSchema.methods.deleteCascade = async function ( await Block.findByIdAndDelete(this.id).exec(); }; +BlockSchema.methods.findIndexFromChildIdList = function ( + this: BlockDoc, + childId: string, +): number { + return this.childIdList.findIndex( + (_childId) => _childId.toHexString() === childId, + ); +}; + export const Block = model(MODEL_NAME, BlockSchema) as BlockModel; diff --git a/backend/src/services/block.ts b/backend/src/services/block.ts index 390a1c7..46dd1b9 100644 --- a/backend/src/services/block.ts +++ b/backend/src/services/block.ts @@ -50,9 +50,7 @@ export const move = async ( } toIndex ??= to.childIdList.length; - const fromIndex = from.childIdList.findIndex( - (_childId) => _childId.toHexString() === blockId, - ); + const fromIndex = from.findIndexFromChildIdList(blockId); toIndex = fromIndex < toIndex ? toIndex - 1 : toIndex; await to.deleteChild(blockId); await to.setChild(block, toIndex); @@ -78,9 +76,7 @@ export const deleteOnly = async (blockId: string): Promise => { } const parent = await Block.readOne(block.parentId.toHexString()); - const index = parent.childIdList.findIndex( - (childId) => childId.toHexString() === blockId, - ); + const index = parent.findIndexFromChildIdList(blockId); await parent.setChildren(block.childIdList, index); await parent.deleteChild(blockId); diff --git a/backend/test/services/block.spec.ts b/backend/test/services/block.spec.ts index d98964c..2d12ad5 100644 --- a/backend/test/services/block.spec.ts +++ b/backend/test/services/block.spec.ts @@ -59,11 +59,7 @@ describe('@services/block', () => { expect(received.value).toEqual(expected.value); expect(received.type).toEqual(expected.type); - expect( - parent.childIdList.findIndex( - (childId) => childId.toHexString() === received.id, - ), - ).toEqual(index); + expect(parent.findIndexFromChildIdList(received.id)).toEqual(index); }); it('create: Duplicated error', async () => {