Skip to content

Commit

Permalink
insert labels only if name unique
Browse files Browse the repository at this point in the history
  • Loading branch information
sywhb committed Dec 22, 2023
1 parent 89aaced commit ccec94d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 23 deletions.
12 changes: 11 additions & 1 deletion packages/api/src/repository/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,17 @@ export const labelRepository = appDataSource.getRepository(Label).extend({
},

createLabels(labels: CreateLabelInput[], userId: string) {
return this.save(labels.map((l) => convertToLabel(l, userId)))
return this.query(
`
INSERT INTO omnivore.labels (user_id, name, color, description, internal)
SELECT $1, $2, $3, $4, $5
WHERE NOT EXISTS (
SELECT 1 FROM omnivore.labels WHERE LOWER(name) = LOWER($2) AND user_id = $1
)
RETURNING id, name, color, description, created_at
`,
labels.map((l) => Object.values(convertToLabel(l, userId)))
) as Promise<Label[]>
},

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

0 comments on commit ccec94d

Please sign in to comment.