-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathTemplateDataSource.ts
More file actions
1333 lines (1180 loc) · 39.1 KB
/
Copy pathTemplateDataSource.ts
File metadata and controls
1333 lines (1180 loc) · 39.1 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { logger } from '@user-office-software/duo-logger';
import { GraphQLError } from 'graphql';
import * as Yup from 'yup';
import {
ComparisonStatus,
ConflictResolutionStrategy,
DataType,
FieldDependency,
Question,
QuestionComparison,
QuestionTemplateRelation,
Template,
TemplateCategory,
TemplateCategoryId,
TemplateExport,
TemplateExportData,
TemplateExportMetadata,
TemplateGroupId,
TemplatesHasQuestions,
TemplateStep,
TemplateValidation,
TemplateValidationData,
Topic,
} from '../../models/Template';
import { CreateTemplateArgs } from '../../resolvers/mutations/template/CreateTemplateMutation';
import { CreateTopicArgs } from '../../resolvers/mutations/template/CreateTopicMutation';
import { DeleteQuestionTemplateRelationArgs } from '../../resolvers/mutations/template/DeleteQuestionTemplateRelationMutation';
import { SetActiveTemplateArgs } from '../../resolvers/mutations/template/SetActiveTemplateMutation';
import { UpdateQuestionTemplateRelationSettingsArgs } from '../../resolvers/mutations/template/UpdateQuestionTemplateRelationSettingsMutation';
import { UpdateTemplateArgs } from '../../resolvers/mutations/template/UpdateTemplateMutation';
import {
AllQuestionsFilterArgs,
QuestionsFilter,
} from '../../resolvers/queries/QuestionsQuery';
import { TemplatesArgs } from '../../resolvers/queries/TemplatesQuery';
import { ConflictResolution } from '../../resolvers/types/ConflictResolution';
import {
ConfigBase,
SampleDeclarationConfig,
SubTemplateConfig,
} from '../../resolvers/types/FieldConfig';
import { deepEqual } from '../../utils/json';
import { isAboveVersion, isBelowVersion } from '../../utils/version';
import { TemplateDataSource } from '../TemplateDataSource';
import database from './database';
import {
createProposalTemplateObject,
createQuestionObject,
createQuestionTemplateRelationObject,
createTemplateCategoryObject,
createTemplateGroupObject,
createTopicObject,
QuestionDependencyRecord,
QuestionRecord,
QuestionTemplateRelRecord,
TemplateCategoryRecord,
TemplateGroupRecord,
TemplateRecord,
TopicRecord,
} from './records';
import { createConfig } from '../../models/questionTypes/QuestionRegistry';
import { getQuestionDefinition } from '../../models/questionTypes/QuestionRegistry';
const EXPORT_VERSION = '1.2.0';
const MIN_SUPPORTED_VERSION = '1.2.0';
export default class PostgresTemplateDataSource implements TemplateDataSource {
async getTemplateCategories(): Promise<TemplateCategory[]> {
return database('template_categories')
.select('*')
.then((records: TemplateCategoryRecord[]) =>
records.map((record) => createTemplateCategoryObject(record))
);
}
async getComplementaryQuestions(
templateId: number
): Promise<Question[] | null> {
const questionRecords: QuestionRecord[] = (
await database.raw(
`
SELECT *
FROM questions AS questions
WHERE question_id NOT IN
(SELECT question_id
FROM templates_has_questions
WHERE template_id = ${templateId}
)
AND category_id =
(SELECT category_id
FROM template_groups
WHERE template_group_id =
( SELECT group_id FROM templates
WHERE template_id = ${templateId})
)
`
)
).rows;
if (!questionRecords) {
return [];
}
return questionRecords.map((value) => createQuestionObject(value));
}
getQuestions(filter?: QuestionsFilter): Promise<Question[]> {
return database
.select('*')
.from('questions')
.modify((query) => {
if (filter?.category !== undefined) {
query.where('category_id', filter.category);
}
if (filter?.dataType !== undefined) {
query.whereIn('data_type', filter.dataType);
}
if (filter?.excludeDataType !== undefined) {
query.whereNotIn('data_type', filter.excludeDataType);
}
if (filter?.text !== undefined) {
query.where('question', 'ilike', `%${filter.text}%`);
}
if (filter?.questionIds !== undefined) {
query.whereIn('question_id', filter.questionIds);
}
})
.then((rows: QuestionRecord[]) => {
return rows.map((row) => createQuestionObject(row));
});
}
fieldMap: { [key: string]: string } = {
question: 'questions.question',
naturalKey: 'questions.natural_key',
dataType: 'questions.data_type',
answers: 'answers_count',
templates: 'templates_count',
categoryId: 'template_categories.name',
};
async getAllQuestions(args: AllQuestionsFilterArgs): Promise<{
totalCount: number;
questions: Question[];
}> {
const { filter, first, offset, sortField, sortDirection, searchText } =
args;
return database('questions')
.select([
'questions.*',
'template_categories.*',
database.raw('count(distinct answers.question_id) as answers_count'),
database.raw('count(distinct tq.question_id) as templates_count'),
database.raw('count(*) OVER() AS full_count'),
])
.from('questions')
.leftJoin('answers', 'questions.question_id', 'answers.question_id')
.leftJoin(
'templates_has_questions as tq',
'questions.question_id',
'tq.question_id'
)
.leftJoin(
'template_categories',
'questions.category_id',
'template_categories.template_category_id'
)
.modify((query) => {
if (filter?.category !== undefined) {
query.where('questions.category_id', filter.category);
}
if (filter?.dataType !== undefined) {
query.whereIn('questions.data_type', filter.dataType);
}
if (filter?.excludeDataType !== undefined) {
query.whereNotIn('questions.data_type', filter.excludeDataType);
}
if (searchText) {
query.andWhere((qb) =>
qb
.orWhere('questions.question', 'ilike', `%${searchText.trim()}%`)
.orWhere(
'questions.question_id',
'ilike',
`%${searchText.trim()}%`
)
);
}
if (sortField && sortDirection) {
if (!this.fieldMap.hasOwnProperty(sortField)) {
throw new GraphQLError(`Bad sort field given: ${sortField}`);
}
query.orderBy(this.fieldMap[sortField], sortDirection);
}
if (first) {
query.limit(first);
}
if (offset) {
query.offset(offset);
}
})
.groupBy([
'questions.question_id',
'template_categories.template_category_id',
])
.then((rows: QuestionRecord[]) => {
return {
totalCount: rows[0] ? rows[0].full_count : 0,
questions: rows.map((row) => createQuestionObject(row)),
};
});
}
async createTemplate(args: CreateTemplateArgs): Promise<Template> {
return database('templates')
.insert({
group_id: args.groupId,
name: args.name,
description: args.description,
})
.returning('*')
.then((rows: TemplateRecord[]) => {
if (rows.length !== 1) {
throw new GraphQLError(
`createTemplate expected 1 result got ${rows.length}. ${args.name} ${args.description}`
);
}
return createProposalTemplateObject(rows[0]);
});
}
async deleteTemplate(templateId: number): Promise<Template> {
return database('templates')
.delete()
.where({ template_id: templateId })
.returning('*')
.then((resultSet: TemplateRecord[]) => {
if (!resultSet || resultSet.length == 0) {
throw new GraphQLError(
`DeleteTemplate template does not exist. ID: ${templateId}`
);
}
return createProposalTemplateObject(resultSet[0]);
});
}
async getTemplates(args: TemplatesArgs): Promise<Template[]> {
return database('templates')
.select('*')
.modify((query) => {
if (args.filter?.isArchived !== undefined) {
query.where({ is_archived: args.filter?.isArchived });
}
if (args.filter?.group) {
query.where({ group_id: args.filter?.group || undefined });
}
if (args.filter?.templateIds) {
query.where('template_id', 'in', args.filter.templateIds);
}
})
.then((resultSet: TemplateRecord[]) => {
if (!resultSet) {
return [];
}
return resultSet.map((value) => createProposalTemplateObject(value));
});
}
async getTemplate(templateId: number) {
return database('templates')
.select('*')
.where({ template_id: templateId })
.then((resultSet: TemplateRecord[]) => {
if (resultSet.length !== 1) {
return null;
}
return createProposalTemplateObject(resultSet[0]);
});
}
async getSubtemplatesForQuestions(questions: Question[]) {
const subTemplates: TemplateExportData[] = [];
for await (const question of questions) {
switch (question.dataType) {
case DataType.GENERIC_TEMPLATE:
case DataType.SAMPLE_DECLARATION:
const config = question.config as
| SubTemplateConfig
| SampleDeclarationConfig;
if (typeof config.templateId !== 'number') {
throw new GraphQLError(
`getTemplateAsJson expected number got ${typeof config.templateId}`
);
}
const subTemplate = await this.getTemplateExportData(
config.templateId
);
subTemplates.push(subTemplate);
break;
}
}
return subTemplates;
}
async getTemplateExportData(templateId: number): Promise<TemplateExportData> {
const template = await this.getTemplate(templateId);
const templateSteps = await this.getTemplateSteps(templateId);
const questions = await this.getQuestionsInTemplate(templateId);
const subTemplates = await this.getSubtemplatesForQuestions(questions);
if (!template || !templateSteps || !questions || !subTemplates) {
throw new GraphQLError(`Template does not exist. ID: ${templateId}`);
}
return new TemplateExportData(
template,
templateSteps,
questions,
subTemplates
);
}
async getTemplateExport(templateId: number): Promise<TemplateExport> {
const EXPORT_DATE = new Date();
const templateExportData = await this.getTemplateExportData(templateId);
return new TemplateExport(
new TemplateExportMetadata(EXPORT_VERSION, EXPORT_DATE),
templateExportData
);
}
isCriticalConflict = (questionA: Question, questionB: Question) =>
questionA.dataType !== questionB.dataType ||
questionA.categoryId !== questionB.categoryId;
async validateTemplateExportData(
data: TemplateExportData
): Promise<TemplateValidationData> {
const errors: string[] = [];
const questionComparisons: QuestionComparison[] = [];
if (!data.template) {
throw new GraphQLError('Template field is missing');
}
if (!data.templateSteps) {
throw new GraphQLError('TemplateSteps field is missing');
}
if (!data.questions) {
throw new GraphQLError('Questions field is missing');
}
if (!data.template.name) {
throw new GraphQLError('Template.name field is missing');
}
if (data.template.description == null) {
throw new GraphQLError('Template.description field is missing');
}
if (!data.template.groupId) {
throw new GraphQLError('Template.group field is missing');
}
const questionIds = data.questions.map((question) => question.id);
const existingQuestions = await this.getQuestions({
questionIds,
});
const newQuestions = data.questions.map(
(question) =>
new Question(
question.categoryId,
question.id,
question.naturalKey,
question.dataType,
question.question,
createConfig<any>(question.dataType as DataType, question.config)
)
);
for (const newQuestion of newQuestions) {
const existingQuestion =
existingQuestions.find(
(existingQuestion) => existingQuestion.id === newQuestion.id
) || null;
if (!existingQuestion) {
questionComparisons.push({
existingQuestion: null,
newQuestion: newQuestion,
status: ComparisonStatus.NEW,
conflictResolutionStrategy: ConflictResolutionStrategy.USE_NEW,
});
} else {
if (deepEqual(newQuestion, existingQuestion)) {
questionComparisons.push({
existingQuestion: existingQuestion,
newQuestion: newQuestion,
status: ComparisonStatus.SAME,
conflictResolutionStrategy: ConflictResolutionStrategy.USE_EXISTING,
});
} else {
if (this.isCriticalConflict(newQuestion, existingQuestion)) {
errors.push(
`Question with ID ${newQuestion.id} has a critical conflict with an existing question.`
);
}
questionComparisons.push({
existingQuestion: existingQuestion,
newQuestion: newQuestion,
status: ComparisonStatus.DIFFERENT,
conflictResolutionStrategy: ConflictResolutionStrategy.UNRESOLVED,
});
}
}
}
const validatedSubTemplates = await Promise.all(
data.subTemplates.map(async (template) => {
return await this.validateTemplateExportData(template);
})
);
return new TemplateValidationData(
errors.length === 0,
errors,
questionComparisons,
validatedSubTemplates
);
}
async validateTemplateExport(templateExport: TemplateExport) {
const { metadata, data } = templateExport;
if (isBelowVersion(metadata.version, MIN_SUPPORTED_VERSION)) {
throw new GraphQLError(
`Template version ${metadata.version} is below the minimum supported version ${MIN_SUPPORTED_VERSION}.`
);
}
if (isAboveVersion(metadata.version, EXPORT_VERSION)) {
throw new GraphQLError(
`Template version ${metadata.version} is above the current supported version ${EXPORT_VERSION}.`
);
}
const dataValidation = await this.validateTemplateExportData(data);
return new TemplateValidation(
JSON.stringify(templateExport),
metadata.version,
metadata.exportDate,
dataValidation
);
}
async getQuestionsDependencies(
questionRecords: Array<
QuestionRecord &
QuestionTemplateRelRecord & { dependency_natural_key: string }
>,
templateId: number
): Promise<FieldDependency[]> {
const questionDependencies: QuestionDependencyRecord[] = await database
.select('*')
.from('question_dependencies')
.where('template_id', templateId)
.whereIn(
'question_id',
questionRecords.map((questionRecord) => questionRecord.question_id)
);
return questionDependencies.map((questionDependency) => {
const question = questionRecords.find(
(field) =>
field.question_id === questionDependency.dependency_question_id
);
return new FieldDependency(
questionDependency.question_id,
questionDependency.dependency_question_id,
question?.natural_key as string,
questionDependency.dependency_condition
);
});
}
async getTemplateSteps(templateId: number): Promise<TemplateStep[]> {
const topicRecords: TopicRecord[] = await database
.select('*')
.from('topics')
.where('template_id', templateId)
.andWhere('is_enabled', true)
.orderBy('sort_order');
const questionRecords: Array<
QuestionRecord &
QuestionTemplateRelRecord & {
config: ConfigBase;
dependency_natural_key: string;
}
> = (
await database.raw(`
SELECT
templates_has_questions.*, questions.*, questions.natural_key as dependency_natural_key
FROM
templates_has_questions
LEFT JOIN
questions
ON
templates_has_questions.question_id =
questions.question_id
WHERE
templates_has_questions.template_id = ${templateId}
ORDER BY
templates_has_questions.sort_order`)
).rows;
const dependencies = await this.getQuestionsDependencies(
questionRecords,
templateId
);
const fields = await Promise.all(
questionRecords.map((record) => {
const questionDependencies = dependencies.filter(
(dependency) => dependency.questionId === record.question_id
);
return createQuestionTemplateRelationObject(
record,
questionDependencies
);
})
);
const steps = Array<TemplateStep>();
topicRecords.forEach((topic) => {
steps.push(
new TemplateStep(
createTopicObject(topic),
fields.filter((field) => field.topicId === topic.topic_id)
)
);
});
return steps;
}
async getTopics(
templateId: number,
topicToExcludeId = 0
): Promise<Topic[] | null> {
return database('topics')
.where('template_id', templateId)
.andWhere('topic_id', '!=', topicToExcludeId)
.orderBy('sort_order')
.select('*')
.then((resultSet: TopicRecord[]) => {
if (!resultSet) {
return null;
}
return resultSet.map((resultItem) => createTopicObject(resultItem));
});
}
async upsertTopics(data: Topic[]): Promise<Template> {
const dataToUpsert = data.map((item) => ({
topic_id: item.id,
topic_title: item.title,
template_id: item.templateId,
...(item.isEnabled !== undefined && { is_enabled: item.isEnabled }),
...(item.sortOrder !== undefined && { sort_order: item.sortOrder }),
}));
const result = await database.raw(
`? ON CONFLICT (topic_id)
DO UPDATE SET
topic_title = EXCLUDED.topic_title,
sort_order = EXCLUDED.sort_order
RETURNING *;`,
[database('topics').insert(dataToUpsert)]
);
if (result?.rows?.length) {
const returnValue = await this.getTemplate(dataToUpsert[0].template_id);
if (!returnValue) {
throw new GraphQLError('Could not get template');
}
return returnValue;
} else {
throw new GraphQLError('Something went wrong');
}
}
async createTopic(args: CreateTopicArgs): Promise<Topic> {
const newTopic = (
await database('topics')
.insert({
topic_title: args.title || 'New Topic',
sort_order: args.sortOrder,
is_enabled: true,
template_id: args.templateId,
})
.returning('*')
)[0] as TopicRecord;
return createTopicObject(newTopic);
}
async updateTopicTitle(topicId: number, title: string): Promise<Topic> {
const resultSet: TopicRecord[] = await database
.update(
{
topic_title: title,
},
['*']
)
.from('topics')
.where({ topic_id: topicId });
if (!resultSet || resultSet.length != 1) {
throw new GraphQLError(
'INSERT Topic resultSet must contain exactly 1 row'
);
}
return createTopicObject(resultSet[0]);
}
async updateQuestion(
questionId: string,
values: {
naturalKey?: string;
dataType?: string;
question?: string;
config?: string;
}
): Promise<Question> {
const rows = {
natural_key: values.naturalKey,
data_type: values.dataType,
question: values.question,
default_config: values.config,
};
await database
.update(rows, ['*'])
.from('questions')
.where('question_id', questionId);
const question = await this.getQuestion(questionId);
if (!question) {
throw new GraphQLError('Could not update field');
}
return question;
}
async updateQuestionTemplateRelationSettings(
args: UpdateQuestionTemplateRelationSettingsArgs
): Promise<Template> {
const {
templateId,
questionId,
dependencies,
config,
dependenciesOperator,
} = args;
await validateConfigBeforeWrite(config, questionId);
await database('templates_has_questions')
.update({
config: config,
dependencies_operator: dependenciesOperator,
})
.where({ question_id: questionId, template_id: templateId });
await database('question_dependencies')
.where({ question_id: questionId })
.andWhere({ template_id: templateId })
.del();
if (dependencies?.length) {
const dataToInsert = dependencies.map((dependency) => ({
question_id: questionId,
template_id: templateId,
dependency_question_id: dependency.dependencyId,
dependency_condition: dependency.condition,
}));
await database('question_dependencies').insert(dataToInsert);
}
const returnValue = await this.getTemplate(templateId);
if (!returnValue) {
throw new GraphQLError('Could not get template');
}
return returnValue;
}
async upsertQuestionTemplateRelations(
collection: TemplatesHasQuestions[]
): Promise<Template> {
const dataToUpsert: QuestionTemplateRelRecord[] = [];
for (const item of collection) {
if (!item.config) {
const question = await this.getQuestion(item.questionId);
item.config = JSON.stringify(question?.config);
}
dataToUpsert.push({
question_id: item.questionId,
template_id: item.templateId,
topic_id: item.topicId,
sort_order: item.sortOrder,
config: item.config,
});
}
const result = await database.raw(
`? ON CONFLICT (template_id, question_id)
DO UPDATE SET
sort_order = EXCLUDED.sort_order,
topic_id = EXCLUDED.topic_id,
config = EXCLUDED.config
RETURNING *;`,
[database('templates_has_questions').insert(dataToUpsert)]
);
if (result?.rows?.length) {
const returnValue = await this.getTemplate(dataToUpsert[0].template_id);
if (!returnValue) {
throw new GraphQLError('Could not get template');
}
return returnValue;
} else {
throw new GraphQLError('Something went wrong');
}
}
async updateTemplate(values: UpdateTemplateArgs): Promise<Template | null> {
await database('templates')
.update({
name: values.name,
description: values.description,
is_archived: values.isArchived,
})
.where({ template_id: values.templateId });
return this.getTemplate(values.templateId);
}
async createQuestion(
category_id: TemplateCategoryId,
question_id: string,
natural_key: string,
data_type: DataType,
question: string,
default_config: string
): Promise<Question> {
const resultSet: QuestionRecord[] = await database
.insert(
{
category_id,
question_id,
natural_key,
data_type,
question,
default_config,
},
['*']
)
.from('questions');
if (!resultSet || resultSet.length != 1) {
throw new GraphQLError(
'INSERT field resultSet must contain exactly 1 row'
);
}
return createQuestionObject(resultSet[0]);
}
async upsertQuestion(
category_id: TemplateCategoryId,
question_id: string,
natural_key: string,
data_type: DataType,
question: string,
default_config: string
): Promise<Question> {
const naturalKeyExistAlready = await database
.select('natural_key')
.from('questions')
.where('natural_key', natural_key);
if (naturalKeyExistAlready.length != 0) {
natural_key = natural_key + '_' + Date.now();
}
const resultSet: QuestionRecord[] = await database
.insert(
{
category_id,
question_id,
natural_key,
data_type,
question,
default_config,
},
['*']
)
.from('questions')
.onConflict('question_id')
.merge();
if (!resultSet || resultSet.length != 1) {
throw new GraphQLError('Failure to upsert question');
}
return createQuestionObject(resultSet[0]);
}
async getQuestion(questionId: string): Promise<Question | null> {
return database('questions')
.where({ question_id: questionId })
.select('*')
.first()
.then((result: QuestionRecord | null) => {
if (!result) {
return null;
}
return createQuestionObject(result);
});
}
async getQuestionByNaturalKey(naturalKey: string): Promise<Question | null> {
return database('questions')
.where({ natural_key: naturalKey })
.select('*')
.first()
.then((result: QuestionRecord | null) => {
if (!result) {
return null;
}
return createQuestionObject(result);
});
}
async getQuestionTemplateRelation(
questionId: string,
templateId: number
): Promise<QuestionTemplateRelation | null> {
const [questionRecord]: Array<
QuestionTemplateRelRecord &
QuestionRecord & { config: ConfigBase; dependency_natural_key: string }
> = await database({
templates_has_questions: 'templates_has_questions',
})
.where({
'templates_has_questions.question_id': questionId,
})
.andWhere({
'templates_has_questions.template_id': templateId,
})
.leftJoin(
{ questions: 'questions' },
'templates_has_questions.question_id',
'questions.question_id'
)
.select(
'templates_has_questions.*',
'questions.*',
'questions.natural_key as dependency_natural_key'
);
if (!questionRecord) {
return null;
}
const dependencies = await this.getQuestionsDependencies(
[questionRecord],
templateId
);
return createQuestionTemplateRelationObject(questionRecord, dependencies);
}
async getQuestionTemplateRelations(
templateId: number,
topicId: number,
questionToExcludeId: string
): Promise<TemplatesHasQuestions[] | null> {
return database('templates_has_questions')
.where('template_id', templateId)
.where('topic_id', topicId)
.andWhere('question_id', '!=', questionToExcludeId)
.orderBy('sort_order')
.select('*')
.then((resultSet: QuestionTemplateRelRecord[]) => {
if (!resultSet) {
return null;
}
return resultSet.map((resultItem) => ({
questionId: resultItem.question_id,
templateId: resultItem.template_id,
topicId: resultItem.topic_id,
sortOrder: resultItem.sort_order,
dependencies: [],
config: resultItem.config,
dependenciesOperator: resultItem.dependencies_operator,
}));
});
}
async getActiveTemplateId(groupId: TemplateGroupId): Promise<number | null> {
return database('active_templates')
.select('template_id')
.where('group_id', groupId)
.first()
.then((result: { template_id: number }) => {
if (!result) {
return null;
}
return result.template_id;
});
}
async setActiveTemplate(args: SetActiveTemplateArgs): Promise<boolean> {
await database('active_templates')
.delete('template_id')
.where('group_id', args.templateGroupId);
await database('active_templates').insert({
group_id: args.templateGroupId,
template_id: args.templateId,
});
return true;
}
async deleteQuestion(questionId: string): Promise<Question> {
const [questionRecord]: QuestionRecord[] = await database('questions')
.where({ question_id: questionId })
.returning('*')
.del();
if (!questionRecord) {
logger.logError('Could not delete question', { fieldId: questionId });
throw new GraphQLError(`Could not delete question ${questionId}`);
}
return createQuestionObject(questionRecord);
}
async deleteQuestionTemplateRelation(
args: DeleteQuestionTemplateRelationArgs
): Promise<Template> {
const rowsAffected = await database('templates_has_questions')
.where({
template_id: args.templateId,
question_id: args.questionId,
})
.del();
if (rowsAffected !== 1) {
throw new GraphQLError(
`Could not delete questionId ${args.questionId} in templateId:${args.templateId}`
);
}
const returnValue = await this.getTemplate(args.templateId);
if (!returnValue) {
throw new GraphQLError('Could not find template');
}
return returnValue;