mirror of
https://github.com/omnivore-app/omnivore.git
synced 2026-03-11 08:54:26 +00:00
insert labels only if name unique
This commit is contained in:
parent
89aaced005
commit
ccec94dae0
2 changed files with 23 additions and 23 deletions
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue