-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsettings-service.ts
More file actions
274 lines (240 loc) · 8.59 KB
/
settings-service.ts
File metadata and controls
274 lines (240 loc) · 8.59 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { Inject, Service, Token } from "typedi";
import { Repository } from "typeorm";
import { IService } from ".";
import { ApplicationSettings } from "../entities/application-settings";
import { FormSettings } from "../entities/form-settings";
import { Question } from "../entities/question";
import {
EmailSettings,
EmailTemplate,
FrontendSettings,
Settings,
} from "../entities/settings";
import {
ConfigurationServiceToken,
IConfigurationService,
} from "./config-service";
import { DatabaseServiceToken, IDatabaseService } from "./database-service";
import { ILoggerService, LoggerServiceToken } from "./logger-service";
/**
* Describes a service to retrieve the application's settings.
*/
export interface ISettingsService extends IService {
/**
* Gets the application settings.
*/
getSettings(): Promise<Settings>;
/**
* Updates all settings.
* @param settings The updated settings
*/
updateSettings(settings: Settings): Promise<Settings>;
}
/**
* A token used to inject a concrete settings service.
*/
export const SettingsServiceToken = new Token<ISettingsService>();
@Service(SettingsServiceToken)
export class SettingsService implements ISettingsService {
private _settings!: Repository<Settings>;
private _questions!: Repository<Question>;
public constructor(
@Inject(ConfigurationServiceToken)
private readonly _config: IConfigurationService,
@Inject(DatabaseServiceToken) private readonly _database: IDatabaseService,
@Inject(LoggerServiceToken) private readonly _logger: ILoggerService,
) {}
/**
* Sets up the settings service.
*/
public async bootstrap(): Promise<void> {
this._settings = this._database.getRepository(Settings);
this._questions = this._database.getRepository(Question);
}
/**
* Sorts questions by order id ascendent.
* @param formSettings The from of which the questions should be ordered
*/
private sortFormSettingsByQuestionOrder(formSettings: FormSettings): void {
formSettings.questions.sort((a, b) => a.order - b.order);
}
/**
* Makes sure that both, profile from and confirmation form questions are being sorted.
* @param settings The settings of which the questions should be ordered
*/
private sortQuestionsByOrder(settings: Settings): void {
this.sortFormSettingsByQuestionOrder(settings.application.profileForm);
this.sortFormSettingsByQuestionOrder(settings.application.confirmationForm);
}
/**
* Gets the application settings.
*/
public async getSettings(): Promise<Settings> {
let [settings] = await this._settings.find();
if (settings === undefined) {
this._logger.info("no settings found. creating defaults");
settings = this.getDefaultSettings();
await this._settings.save(settings);
this._logger.debug("default settings saved", settings);
return settings;
}
this.sortQuestionsByOrder(settings);
return settings;
}
/**
* Creates a settings object with default values.
*/
private getDefaultSettings(): Settings {
const settings = new Settings();
settings.application = this.getDefaultApplicationSettings();
settings.frontend = this.getDefaultFrontendSettings();
settings.email = this.getDefaultEmailSettings();
return settings;
}
/**
* Creates an application settings object with default values.
*/
private getDefaultApplicationSettings(): ApplicationSettings {
const applicationSettings = new ApplicationSettings();
applicationSettings.profileForm = this.getDefaultFormSettings();
applicationSettings.confirmationForm = this.getDefaultFormSettings();
applicationSettings.allowProfileFormFrom = new Date();
applicationSettings.allowProfileFormUntil = new Date();
applicationSettings.hoursToConfirm = 24;
return applicationSettings;
}
/**
* Creates an application settings object with default values.
*/
private getDefaultProjectSettings(): ProjectSettings {
const projectSettings = new ProjectSettings();
projectSettings.allowRatingProjects = false;
return projectSettings;
}
/**
* Creates a form settings object with default values.
*/
private getDefaultFormSettings(): FormSettings {
const formSettings = new FormSettings();
formSettings.title = "Form";
formSettings.questions = [];
return formSettings;
}
/**
* Creates a frontend settings object with default values.
*/
private getDefaultFrontendSettings(): FrontendSettings {
const frontendSettings = new FrontendSettings();
frontendSettings.colorGradientStart = "#53bd9a";
frontendSettings.colorGradientEnd = "#56d175";
frontendSettings.colorLink = "#007bff";
frontendSettings.colorLinkHover = "#0056b3";
frontendSettings.loginSignupImage = "http://placehold.it/300x300";
frontendSettings.sidebarImage = "http://placehold.it/300x300";
return frontendSettings;
}
/**
* Creates a email settings object with default values.
*/
private getDefaultEmailSettings(): EmailSettings {
const emailSettings = new EmailSettings();
emailSettings.verifyEmail = this.getDefaultEmailTemplate();
emailSettings.admittedEmail = this.getDefaultEmailTemplate();
emailSettings.submittedEmail = this.getDefaultEmailTemplate();
emailSettings.forgotPasswordEmail = this.getDefaultEmailTemplate();
emailSettings.sender = "support@hackaburg.de";
// path.join() will replace https:// with https:/, which breaks urls
const baseURLWithoutTrailingSlash =
this._config.config.http.baseURL.replace(/\/+$/, "");
const verifyURL = `${baseURLWithoutTrailingSlash}/verify#{{verifyToken}}`;
emailSettings.verifyEmail.htmlTemplate = `<a href="${verifyURL}">${verifyURL}</a>`;
emailSettings.verifyEmail.textTemplate = verifyURL;
return emailSettings;
}
/**
* Creates a email template object with default values.
*/
private getDefaultEmailTemplate(): EmailTemplate {
const template = new EmailTemplate();
template.htmlTemplate = "";
template.subject = "";
template.textTemplate = "";
return template;
}
/**
* Gets the question IDs from the given settings.
* @param settings The settings to retrieve the questions from
*/
private getAllQuestionIDs(settings: Settings): ReadonlyArray<Question["id"]> {
return [
...settings.application.profileForm.questions,
...settings.application.confirmationForm.questions,
].map(({ id }) => id);
}
/**
* Removes questions that are not included in the updated settings.
* @param existingSettings The existing settings from the database
* @param updatedSettings The updated settings
*/
private async removeOrphanQuestions(
existingSettings: Settings,
updatedSettings: Settings,
): Promise<void> {
const existingQuestionIDs = this.getAllQuestionIDs(existingSettings);
const questionIDs = this.getAllQuestionIDs(updatedSettings);
const orphanQuestionIDs = existingQuestionIDs.filter(
(id) => !questionIDs.includes(id),
);
if (orphanQuestionIDs.length > 0) {
await this._questions.delete(orphanQuestionIDs);
}
}
/**
* Automatically adds order numbers from the sequence of questions.
* @param formSettings The form to add the order to
*/
private addOrderToQuestionsInFormSettings(formSettings: FormSettings): void {
for (
let questionIndex = 0;
questionIndex < formSettings.questions.length;
questionIndex++
) {
const question = formSettings.questions[questionIndex];
question.order = questionIndex;
}
}
/**
* Makes sure that for both, profile from and confirmation form questions order numbers are generated.
*/
private addOrderToQuestionsInSettings(settings: Settings): void {
this.addOrderToQuestionsInFormSettings(settings.application.profileForm);
this.addOrderToQuestionsInFormSettings(
settings.application.confirmationForm,
);
}
/**
* Updates all settings.
* @param changes The updated settings
*/
public async updateSettings(settings: Settings): Promise<Settings> {
this.addOrderToQuestionsInSettings(settings);
const existingSettings = await this.getSettings();
await this.removeOrphanQuestions(existingSettings, settings);
const existingSettingsWithoutOrphanQuestions = await this.getSettings();
const merged = this._settings.merge(
existingSettingsWithoutOrphanQuestions,
settings,
);
const saved = await this._settings.save(merged);
this.sortQuestionsByOrder(saved);
return saved;
}
}
/**
* An error to signal updating the settings didn't work.
*/
export class UpdateSettingsError extends Error {
constructor(message: string) {
super(message);
}
}