Fix: rename author to check using normalized column and prevent unique constraint violation

This commit is contained in:
Nicholas Wallace 2026-05-31 09:16:25 -07:00
parent df88110a63
commit 80ab52dcb9
2 changed files with 16 additions and 18 deletions

View file

@ -1,5 +1,4 @@
const { Request, Response, NextFunction } = require('express') const { Request, Response, NextFunction } = require('express')
const sequelize = require('sequelize')
const fs = require('../libs/fsExtra') const fs = require('../libs/fsExtra')
const { createNewSortInstance } = require('../libs/fastSort') const { createNewSortInstance } = require('../libs/fastSort')
@ -113,18 +112,10 @@ class AuthorController {
payload.lastFirst = Database.authorModel.getLastFirst(payload.name) payload.lastFirst = Database.authorModel.getLastFirst(payload.name)
} }
// Check if author name matches another author in the same library and merge the authors // Check if the new author name matches another author in the same library and merge the authors
let existingAuthor = null let existingAuthor = null
if (authorNameUpdate) { if (authorNameUpdate) {
existingAuthor = await Database.authorModel.findOne({ existingAuthor = await Database.authorModel.getByNameAndLibrary(payload.name, req.author.libraryId, req.author.id)
where: {
id: {
[sequelize.Op.not]: req.author.id
},
name: payload.name,
libraryId: req.author.libraryId
}
})
} }
if (existingAuthor) { if (existingAuthor) {
Logger.info(`[AuthorController] Merging author "${req.author.name}" with "${existingAuthor.name}"`) Logger.info(`[AuthorController] Merging author "${req.author.name}" with "${existingAuthor.name}"`)

View file

@ -1,4 +1,4 @@
const { DataTypes, Model } = require('sequelize') const { DataTypes, Model, Op } = require('sequelize')
const parseNameString = require('../utils/parsers/parseNameString') const parseNameString = require('../utils/parsers/parseNameString')
class Author extends Model { class Author extends Model {
@ -119,17 +119,24 @@ class Author extends Model {
* Get author by name and libraryId. name case insensitive * Get author by name and libraryId. name case insensitive
* @param {string} authorName * @param {string} authorName
* @param {string} libraryId * @param {string} libraryId
* @param {string} [excludeAuthorId]
* @returns {Promise<Author>} * @returns {Promise<Author>}
*/ */
static async getByNameAndLibrary(authorName, libraryId) { static async getByNameAndLibrary(authorName, libraryId, excludeAuthorId = null) {
const searchName = this.normalizeSearchName(authorName) const searchName = this.normalizeSearchName(authorName)
if (!searchName) return null if (!searchName) return null
return this.findOne({
where: { const where = {
searchName, searchName,
libraryId libraryId
}
if (excludeAuthorId) {
where.id = {
[Op.not]: excludeAuthorId
} }
}) }
return this.findOne({ where })
} }
/** /**