Merge pull request #3275 from omnivore-app/fix/label-name-not-unique
insert labels only if name unique
This commit is contained in:
@ -73,7 +73,13 @@ export const labelRepository = appDataSource.getRepository(Label).extend({
|
||||
},
|
||||
|
||||
createLabels(labels: CreateLabelInput[], userId: string) {
|
||||
return this.save(labels.map((l) => convertToLabel(l, userId)))
|
||||
return this.upsert(
|
||||
labels.map((l) => convertToLabel(l, userId)),
|
||||
{
|
||||
conflictPaths: ['name', 'user'],
|
||||
skipUpdateIfNoValuesChanged: true,
|
||||
}
|
||||
)
|
||||
},
|
||||
|
||||
deleteById(id: string) {
|
||||
|
||||
@ -2,7 +2,6 @@ import { DeepPartial, FindOptionsWhere, In } from 'typeorm'
|
||||
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity'
|
||||
import { EntityLabel, LabelSource } from '../entity/entity_label'
|
||||
import { Label } from '../entity/label'
|
||||
import { LibraryItem } from '../entity/library_item'
|
||||
import { createPubSubClient, EntityType, PubsubClient } from '../pubsub'
|
||||
import { authTrx } from '../repository'
|
||||
import { CreateLabelInput, labelRepository } from '../repository/label'
|
||||
@ -37,30 +36,21 @@ export const findOrCreateLabels = async (
|
||||
labels: CreateLabelInput[],
|
||||
userId: string
|
||||
): Promise<Label[]> => {
|
||||
// create labels if not exist
|
||||
await authTrx(
|
||||
async (tx) =>
|
||||
tx.withRepository(labelRepository).createLabels(labels, userId),
|
||||
undefined,
|
||||
userId
|
||||
)
|
||||
|
||||
// find labels
|
||||
return authTrx(
|
||||
async (tx) => {
|
||||
const labelRepo = tx.withRepository(labelRepository)
|
||||
// find existing labels
|
||||
const labelEntities = await labelRepo.findByNames(
|
||||
async (tx) =>
|
||||
tx.withRepository(labelRepository).findByNames(
|
||||
labels.map((l) => l.name),
|
||||
userId
|
||||
)
|
||||
|
||||
const existingLabelsInLowerCase = labelEntities.map((l) =>
|
||||
l.name.toLowerCase()
|
||||
)
|
||||
const newLabels = labels.filter(
|
||||
(l) => !existingLabelsInLowerCase.includes(l.name.toLowerCase())
|
||||
)
|
||||
if (newLabels.length === 0) {
|
||||
return labelEntities
|
||||
}
|
||||
|
||||
// create new labels
|
||||
const newLabelEntities = await labelRepo.createLabels(newLabels, userId)
|
||||
|
||||
return [...labelEntities, ...newLabelEntities]
|
||||
},
|
||||
),
|
||||
undefined,
|
||||
userId
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user