Skip to content

Commit f11dec3

Browse files
author
Joan Reyero
committed
Transactions in upsert content
1 parent b845b7c commit f11dec3

1 file changed

Lines changed: 27 additions & 9 deletions

File tree

backend/src/services/eagleEyeContentService.ts

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
import { PageData, QueryData } from '../types/common'
1616
import Error400 from '../errors/Error400'
1717
import UserRepository from '../database/repositories/userRepository'
18+
import SequelizeRepository from '../database/repositories/sequelizeRepository'
1819

1920
export interface EagleEyeContentUpsertData extends EagleEyeAction {
2021
content: EagleEyeContent
@@ -38,19 +39,36 @@ export default class EagleEyeContentService extends LoggingBase {
3839
if (!data.url) {
3940
throw new Error400(this.options.language, 'errors.eagleEye.urlRequiredWhenUpserting')
4041
}
42+
const transaction = await SequelizeRepository.createTransaction(this.options)
4143

42-
// find by url
43-
const existing = await EagleEyeContentRepository.findByUrl(data.url, this.options)
44+
try {
45+
// find by url
46+
const existing = await EagleEyeContentRepository.findByUrl(data.url, {
47+
...this.options,
48+
transaction,
49+
})
50+
51+
let record
52+
53+
if (existing) {
54+
record = await EagleEyeContentRepository.update(existing.id, data, {
55+
...this.options,
56+
transaction,
57+
})
58+
} else {
59+
record = await EagleEyeContentRepository.create(data, {
60+
...this.options,
61+
transaction,
62+
})
63+
}
4464

45-
let record
65+
await SequelizeRepository.commitTransaction(transaction)
4666

47-
if (existing) {
48-
record = await EagleEyeContentRepository.update(existing.id, data, this.options)
49-
} else {
50-
record = await EagleEyeContentRepository.create(data, this.options)
67+
return record
68+
} catch (error) {
69+
await SequelizeRepository.rollbackTransaction(transaction)
70+
throw error
5171
}
52-
53-
return record
5472
}
5573

5674
async findById(id: string): Promise<EagleEyeContent> {

0 commit comments

Comments
 (0)