diff --git a/packages/api/src/repository/label.ts b/packages/api/src/repository/label.ts index 093a34bd99..6342f32272 100644 --- a/packages/api/src/repository/label.ts +++ b/packages/api/src/repository/label.ts @@ -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 }, deleteById(id: string) { diff --git a/packages/api/src/services/labels.ts b/packages/api/src/services/labels.ts index 9e8a508c8f..46ec8eb0aa 100644 --- a/packages/api/src/services/labels.ts +++ b/packages/api/src/services/labels.ts @@ -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 => { + // 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 )