Skip to content

Commit

Permalink
Merge pull request #3275 from omnivore-app/fix/label-name-not-unique
Browse files Browse the repository at this point in the history
insert labels only if name unique
  • Loading branch information
sywhb authored Dec 22, 2023
2 parents 89aaced + c21ba9e commit d850bc2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 23 deletions.
8 changes: 7 additions & 1 deletion packages/api/src/repository/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
34 changes: 12 additions & 22 deletions packages/api/src/services/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
)
Expand Down

1 comment on commit d850bc2

@vercel
Copy link

@vercel vercel bot commented on d850bc2 Dec 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.