From 26d05a2e6e044789da36b3e417c08cfa2c47a854 Mon Sep 17 00:00:00 2001 From: Hongbo Wu Date: Mon, 19 Feb 2024 11:47:09 +0800 Subject: [PATCH] delete the new item if it is different from the existing one --- packages/api/src/repository/library_item.ts | 32 --------------------- packages/api/src/services/library_item.ts | 11 +++++-- 2 files changed, 9 insertions(+), 34 deletions(-) diff --git a/packages/api/src/repository/library_item.ts b/packages/api/src/repository/library_item.ts index 678d9cd12..f4003b7bc 100644 --- a/packages/api/src/repository/library_item.ts +++ b/packages/api/src/repository/library_item.ts @@ -57,38 +57,6 @@ export const libraryItemRepository = appDataSource return result.generatedMaps[0] as LibraryItem }, - async updateLibraryItem(item: DeepPartial) { - return this.save(item) - - // const columns = getColumnsDbName(this) - // // overwrites columns except id and slug - // const overwrites = columns.filter( - // (column) => !['id', 'slug'].includes(column) - // ) - - // const hashedUrl = 'md5(original_url)' - // const conflictColumns = ['user_id', hashedUrl] - - // const [query, params] = this.createQueryBuilder() - // .insert() - // .into(LibraryItem) - // .values(convertToLibraryItem(item)) - // .orUpdate(overwrites, conflictColumns, { - // skipUpdateIfNoValuesChanged: true, - // }) - // .returning(getColumns(this)) - // .getQueryAndParameters() - - // // this is a workaround for the typeorm bug which quotes the md5 function - // const newQuery = query.replace(`"${hashedUrl}"`, hashedUrl) - // const results = (await this.query(newQuery, params)) as never[] - - // // convert to camel case - // const newItem = keysToCamelCase(results[0]) as LibraryItem - - // return newItem - }, - createByPopularRead(name: string, userId: string) { return this.query( ` diff --git a/packages/api/src/services/library_item.ts b/packages/api/src/services/library_item.ts index a09b4c773..20b47afb7 100644 --- a/packages/api/src/services/library_item.ts +++ b/packages/api/src/services/library_item.ts @@ -839,7 +839,7 @@ export const createOrUpdateLibraryItem = async ( const newLibraryItem = await authTrx( async (tx) => { const repo = tx.withRepository(libraryItemRepository) - // find existing library item by user_id and url + // find existing library item by user_id and url for update const existingLibraryItem = await repo.findByUserIdAndUrl( userId, libraryItem.originalUrl, @@ -848,11 +848,18 @@ export const createOrUpdateLibraryItem = async ( if (existingLibraryItem) { // update existing library item - return repo.save({ + const newItem = await repo.save({ ...libraryItem, id: existingLibraryItem.id, slug: existingLibraryItem.slug, // keep the original slug }) + + // delete the new item if it's different from the existing one + if (libraryItem.id && libraryItem.id !== existingLibraryItem.id) { + await repo.delete(libraryItem.id) + } + + return newItem } // create or update library item