-
Notifications
You must be signed in to change notification settings - Fork 70
/
section.repository.ts
87 lines (80 loc) · 2.52 KB
/
section.repository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import {
Count,
DataObject,
Options,
repository,
Where,
juggler,
} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {
DefaultUserModifyCrudRepository,
IAuthUserWithPermissions,
ILogger,
LOGGER,
} from '@sourceloop/core';
import {Getter, inject} from '@loopback/core';
import {Section} from '../models/section.model';
import {SurveyDbSourceName} from '../types';
import {SurveyRepository} from './survey.repository';
import {AuthenticationBindings} from 'loopback4-authentication';
export class SectionRepository extends DefaultUserModifyCrudRepository<
Section,
typeof Section.prototype.id
> {
constructor(
@inject(`datasources.${SurveyDbSourceName}`) dataSource: juggler.DataSource,
@repository.getter('SurveyRepository')
protected surveyRepositoryGetter: Getter<SurveyRepository>,
@inject(LOGGER.LOGGER_INJECT) public logger: ILogger,
@inject.getter(AuthenticationBindings.CURRENT_USER)
public readonly getCurrentUser: Getter<IAuthUserWithPermissions>,
) {
super(Section, dataSource, getCurrentUser);
}
async create(
entity: DataObject<Section>,
options?: Options | undefined,
): Promise<Section> {
this._updateSurveyModifiedByAndOn(entity.surveyId as string).catch(err =>
this.logger.error(JSON.stringify(err)),
);
return super.create(entity);
}
async updateAll(
data: DataObject<Section>,
where?: Where<Section> | undefined,
options?: Options | undefined,
): Promise<Count> {
const surveyQuestion = where as Section;
if (surveyQuestion.surveyId) {
this._updateSurveyModifiedByAndOn(surveyQuestion.surveyId).catch(err =>
this.logger.error(JSON.stringify(err)),
);
}
return super.updateAll(data, where);
}
async reorder(surveyId: string, displayOrder: number) {
this._updateSurveyModifiedByAndOn(surveyId).catch(err =>
this.logger.error(JSON.stringify(err)),
);
const parameters = [surveyId, displayOrder];
const query = `
UPDATE ${process.env.SURVEY_DB_DATABASE}.section
SET display_order = display_order - 1
WHERE survey_id = ? AND display_order > ?`;
this.execute(query, parameters)
.then()
.catch(err => Promise.reject(err));
}
async _updateSurveyModifiedByAndOn(surveyId: string) {
try {
const surveyRepository = await this.surveyRepositoryGetter();
await surveyRepository.updateById(surveyId, {
id: surveyId,
});
} catch (err) {
throw new HttpErrors.InternalServerError(err);
}
}
}