-
Notifications
You must be signed in to change notification settings - Fork 582
/
index.ts
359 lines (323 loc) · 10.5 KB
/
index.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
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
import {
FbSubmission,
FormBuilderStorageOperationsCreateSubmissionParams,
FormBuilderStorageOperationsDeleteSubmissionParams,
FormBuilderStorageOperationsGetSubmissionParams,
FormBuilderStorageOperationsListSubmissionsParams,
FormBuilderStorageOperationsListSubmissionsResponse,
FormBuilderStorageOperationsUpdateSubmissionParams
} from "@webiny/api-form-builder/types";
import { Entity, Table } from "dynamodb-toolbox";
import { Client } from "@elastic/elasticsearch";
import WebinyError from "@webiny/error";
import { batchReadAll } from "@webiny/db-dynamodb/utils/batchRead";
import { sortItems } from "@webiny/db-dynamodb/utils/sort";
import { createLimit } from "@webiny/api-elasticsearch/limit";
import {
createElasticsearchBody,
createSubmissionElasticType
} from "~/operations/submission/elasticsearchBody";
import { PluginsContainer } from "@webiny/plugins";
import {
FormBuilderSubmissionStorageOperations,
FormBuilderSubmissionStorageOperationsCreatePartitionKeyParams
} from "~/types";
import configurations from "~/configurations";
import { cleanupItem } from "@webiny/db-dynamodb/utils/cleanup";
import { parseIdentifier } from "@webiny/utils";
import { decodeCursor, encodeCursor } from "@webiny/api-elasticsearch/cursors";
export interface Params {
entity: Entity<any>;
esEntity: Entity<any>;
table: Table;
elasticsearch: Client;
plugins: PluginsContainer;
}
export const createSubmissionStorageOperations = (
params: Params
): FormBuilderSubmissionStorageOperations => {
const { entity, esEntity, table, elasticsearch, plugins } = params;
const createSubmissionPartitionKey = (
params: FormBuilderSubmissionStorageOperationsCreatePartitionKeyParams
) => {
const { tenant, locale, formId } = params;
const { id } = parseIdentifier(formId);
return `T#${tenant}#L#${locale}#FB#F#${id}`;
};
const createSubmissionSortKey = (id: string) => {
return `FS#${id}`;
};
const createSubmissionType = () => {
return "fb.formSubmission";
};
const createSubmission = async (
params: FormBuilderStorageOperationsCreateSubmissionParams
): Promise<FbSubmission> => {
const { submission, form } = params;
const keys = {
PK: createSubmissionPartitionKey(form),
SK: createSubmissionSortKey(submission.id)
};
try {
await entity.put({
...submission,
...keys,
TYPE: createSubmissionType()
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not create form submission in the DynamoDB.",
ex.code || "UPDATE_FORM_SUBMISSION_ERROR",
{
submission,
form,
keys
}
);
}
try {
const { index } = configurations.es({
tenant: form.tenant
});
await esEntity.put({
index,
data: {
...submission,
__type: createSubmissionElasticType()
},
TYPE: createSubmissionType(),
...keys
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not create form submission in the Elasticsearch.",
ex.code || "UPDATE_FORM_SUBMISSION_ERROR",
{
submission,
form,
keys
}
);
}
return submission;
};
/**
* We do not save the data in the Elasticsearch because there is no need for that.
*/
const updateSubmission = async (
params: FormBuilderStorageOperationsUpdateSubmissionParams
): Promise<FbSubmission> => {
const { submission, form, original } = params;
const keys = {
PK: createSubmissionPartitionKey(form),
SK: createSubmissionSortKey(submission.id)
};
try {
await entity.put({
...submission,
...keys,
TYPE: createSubmissionType()
});
return submission;
} catch (ex) {
throw new WebinyError(
ex.message || "Could not update form submission in the DynamoDB.",
ex.code || "UPDATE_FORM_SUBMISSION_ERROR",
{
submission,
original,
form,
keys
}
);
}
};
const deleteSubmission = async (
params: FormBuilderStorageOperationsDeleteSubmissionParams
): Promise<FbSubmission> => {
const { submission, form } = params;
const keys = {
PK: createSubmissionPartitionKey(form),
SK: createSubmissionSortKey(submission.id)
};
try {
await entity.delete(keys);
} catch (ex) {
throw new WebinyError(
ex.message || "Could not delete form submission from DynamoDB.",
ex.code || "DELETE_FORM_SUBMISSION_ERROR",
{
submission,
form,
keys
}
);
}
try {
await esEntity.delete(keys);
} catch (ex) {
throw new WebinyError(
ex.message || "Could not delete form submission from Elasticsearch.",
ex.code || "DELETE_FORM_SUBMISSION_ERROR",
{
submission,
form,
keys
}
);
}
return submission;
};
/**
*
* We are using this method because it is faster to fetch the exact data from the DynamoDB than Elasticsearch.
*
* @internal
*/
const listSubmissionsByIds = async (
params: FormBuilderStorageOperationsListSubmissionsParams
): Promise<FbSubmission[]> => {
const { where, sort } = params;
const items = where.id_in.map(id => {
return entity.getBatch({
PK: createSubmissionPartitionKey({
...where
}),
SK: createSubmissionSortKey(id)
});
});
let results: FbSubmission[] = [];
try {
results = await batchReadAll<FbSubmission>({
table,
items
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not batch read form submissions.",
ex.code || "BATCH_READ_SUBMISSIONS_ERROR",
{
where,
sort
}
);
}
/**
* We need to remove empty results because it is a possibility that batch read returned null for non-existing record.
*/
const submissions = results.filter(Boolean).map(submission => {
return cleanupItem(entity, submission);
});
if (!sort) {
return submissions;
}
return sortItems<FbSubmission>({
items: submissions,
sort,
fields: []
});
};
const listSubmissions = async (
params: FormBuilderStorageOperationsListSubmissionsParams
): Promise<FormBuilderStorageOperationsListSubmissionsResponse> => {
const { where, sort, limit: initialLimit, after } = params;
if (where.id_in) {
const items = await listSubmissionsByIds(params);
return {
items,
meta: {
hasMoreItems: false,
cursor: null,
totalCount: items.length
}
};
}
const limit = createLimit(initialLimit);
const body = createElasticsearchBody({
plugins,
sort,
limit: limit + 1,
where,
after: decodeCursor(after) as any
});
const esConfig = configurations.es({
tenant: where.tenant
});
const query = {
...esConfig,
body
};
let response;
try {
response = await elasticsearch.search(query);
} catch (ex) {
throw new WebinyError(
ex.message || "Could list form submissions.",
ex.code || "LIST_SUBMISSIONS_ERROR",
{
where,
query
}
);
}
const { hits, total } = response.body.hits;
const items = hits.map(item => item._source);
const hasMoreItems = items.length > limit;
if (hasMoreItems) {
/**
* Remove the last item from results, we don't want to include it.
*/
items.pop();
}
/**
* Cursor is the `sort` value of the last item in the array.
* https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after
*/
const meta = {
hasMoreItems,
totalCount: total.value,
cursor: items.length > 0 ? encodeCursor(hits[items.length - 1].sort) : null
};
return {
items,
meta
};
};
const getSubmission = async (
params: FormBuilderStorageOperationsGetSubmissionParams
): Promise<FbSubmission> => {
const { where } = params;
const keys = {
PK: createSubmissionPartitionKey({
...where,
formId: where.formId as string
}),
SK: createSubmissionSortKey(where.id)
};
try {
const result = await entity.get(keys);
if (!result || !result.Item) {
return null;
}
return cleanupItem(entity, result.Item);
} catch (ex) {
throw new WebinyError(
ex.message || "Could not oad submission.",
ex.code || "GET_SUBMISSION_ERROR",
{
where,
keys
}
);
}
};
return {
createSubmission,
deleteSubmission,
updateSubmission,
listSubmissions,
getSubmission,
createSubmissionPartitionKey,
createSubmissionSortKey
};
};