delete the new item if it is different from the existing one

This commit is contained in:
Hongbo Wu 2024-02-19 11:47:09 +08:00
parent afd4d2a397
commit 26d05a2e6e
2 changed files with 9 additions and 34 deletions

View file

@ -57,38 +57,6 @@ export const libraryItemRepository = appDataSource
return result.generatedMaps[0] as LibraryItem
},
async updateLibraryItem(item: DeepPartial<LibraryItem>) {
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(
`

View file

@ -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