import { Block , BlockDoc , BlockDTO } from '@/models' ; import { ErrorMessage } from '@/aops' ; export const create = async ( param ) : Promise < { parent : BlockDoc ; block : BlockDoc ; } > => { const parent = await Block . readOne ( param . parentId ) ; if ( ! parent ) { throw new Error ( ErrorMessage . NOT_FOUND ) ; } const block = await Block . createOne ( { ... param . blockDTO , pageId : parent . pageId . toHexString ( ) , } ) ; await parent . setChild ( block , param . index ) ; return { parent , block } ; } ; export const readAll = async ( pageId ) : Promise < BlockDoc [ ] > => { return Block . readAll ( pageId ) ; } ; export const update = async ( blockId , blockDTO ) : Promise < BlockDoc > => { const block = await Block . updateOneBlock ( blockId , blockDTO ) ; if ( ! block ) { throw new Error ( ErrorMessage . NOT_FOUND ) ; } return block ; } ; export const move = async ( blockId , toId , toIndex ? ) : Promise < { block : BlockDoc ; from ? : BlockDoc ; to ? : BlockDoc ; } > => { const block = await Block . readOne ( blockId ) ; const from = await Block . readOne ( block . parentId . toHexString ( ) ) ; const to = await Block . readOne ( toId ) ; if ( from . id !== to . id ) { await from . deleteChild ( blockId ) ; await to . setChild ( block , toIndex ) ; return { block , from , to } ; } toIndex ??= to . childIdList . length ; const fromIndex = from . findIndexFromChildIdList ( blockId ) ; toIndex = fromIndex < toIndex ? toIndex - 1 : toIndex ; await to . deleteChild ( blockId ) ; await to . setChild ( block , toIndex ) ; return { block , from : null , to } ; } ; export const deleteCascade = async ( blockId ) : Promise < BlockDoc > => { const block = await Block . readOne ( blockId ) ; if ( ! block ) { throw new Error ( ErrorMessage . NOT_FOUND ) ; } const parent = await Block . readOne ( block . parentId . toHexString ( ) ) ; await block . deleteCascade ( ) ; await parent . deleteChild ( blockId ) ; return parent ; } ; export const deleteOnly = async ( blockId ) : Promise < BlockDoc > => { const block = await Block . readOne ( blockId ) ; if ( ! block ) { throw new Error ( ErrorMessage . NOT_FOUND ) ; } const parent = await Block . readOne ( block . parentId . toHexString ( ) ) ; const index = parent . findIndexFromChildIdList ( blockId ) ; await parent . setChildren ( block . childIdList , index ) ; await parent . deleteChild ( blockId ) ; await Block . deleteOneBlock ( blockId ) ; return parent ; } ;