-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathsaved_object_content_storage.ts
404 lines (350 loc) · 12.8 KB
/
saved_object_content_storage.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
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import Boom from '@hapi/boom';
import type { SearchQuery, SearchIn } from '@kbn/content-management-plugin/common';
import type {
ContentStorage,
StorageContext,
MSearchConfig,
} from '@kbn/content-management-plugin/server';
import type {
SavedObject,
SavedObjectReference,
SavedObjectsFindOptions,
SavedObjectsCreateOptions,
SavedObjectsUpdateOptions,
SavedObjectsFindResult,
} from '@kbn/core-saved-objects-api-server';
import { pick } from 'lodash';
import type {
CMCrudTypes,
ServicesDefinitionSet,
SOWithMetadata,
SOWithMetadataPartial,
} from './types';
import { tagsToFindOptions } from './utils';
const savedObjectClientFromRequest = async (ctx: StorageContext) => {
if (!ctx.requestHandlerContext) {
throw new Error('Storage context.requestHandlerContext missing.');
}
const { savedObjects } = await ctx.requestHandlerContext.core;
return savedObjects.client;
};
type PartialSavedObject<T> = Omit<SavedObject<Partial<T>>, 'references'> & {
references: SavedObjectReference[] | undefined;
};
function savedObjectToItem<Attributes extends object, Item extends SOWithMetadata>(
savedObject: SavedObject<Attributes>,
allowedSavedObjectAttributes: string[],
partial: false
): Item;
function savedObjectToItem<Attributes extends object, PartialItem extends SOWithMetadata>(
savedObject: PartialSavedObject<Attributes>,
allowedSavedObjectAttributes: string[],
partial: true
): PartialItem;
function savedObjectToItem<Attributes extends object>(
savedObject: SavedObject<Attributes> | PartialSavedObject<Attributes>,
allowedSavedObjectAttributes: string[]
): SOWithMetadata | SOWithMetadataPartial {
const {
id,
type,
updated_at: updatedAt,
created_at: createdAt,
attributes,
references,
error,
namespaces,
version,
} = savedObject;
return {
id,
type,
updatedAt,
createdAt,
attributes: pick(attributes, allowedSavedObjectAttributes),
references,
error,
namespaces,
version,
};
}
export interface SearchArgsToSOFindOptionsOptionsDefault {
fields?: string[];
searchFields?: string[];
}
export const searchArgsToSOFindOptionsDefault = <T extends string>(
params: SearchIn<T, SearchArgsToSOFindOptionsOptionsDefault>
): SavedObjectsFindOptions => {
const { query, contentTypeId, options } = params;
return {
type: contentTypeId,
search: query.text,
perPage: query.limit,
page: query.cursor ? +query.cursor : undefined,
defaultSearchOperator: 'AND',
searchFields: options?.searchFields ?? ['description', 'title'],
fields: options?.fields ?? ['description', 'title'],
...tagsToFindOptions(query.tags),
};
};
export const createArgsToSoCreateOptionsDefault = (
params: SavedObjectsCreateOptions
): SavedObjectsCreateOptions => params;
export const updateArgsToSoUpdateOptionsDefault = <Types extends CMCrudTypes>(
params: SavedObjectsUpdateOptions<Types['Attributes']>
): SavedObjectsUpdateOptions<Types['Attributes']> => params;
export type CreateArgsToSoCreateOptions<Types extends CMCrudTypes> = (
params: Types['CreateOptions']
) => SavedObjectsCreateOptions;
export type SearchArgsToSOFindOptions<Types extends CMCrudTypes> = (
params: Types['SearchIn']
) => SavedObjectsFindOptions;
export type UpdateArgsToSoUpdateOptions<Types extends CMCrudTypes> = (
params: Types['UpdateOptions']
) => SavedObjectsUpdateOptions<Types['Attributes']>;
export interface SOContentStorageConstrutorParams<Types extends CMCrudTypes> {
savedObjectType: string;
cmServicesDefinition: ServicesDefinitionSet;
// this is necessary since unexpected saved object attributes could cause schema validation to fail
allowedSavedObjectAttributes: string[];
createArgsToSoCreateOptions?: CreateArgsToSoCreateOptions<Types>;
updateArgsToSoUpdateOptions?: UpdateArgsToSoUpdateOptions<Types>;
searchArgsToSOFindOptions?: SearchArgsToSOFindOptions<Types>;
enableMSearch?: boolean;
mSearchAdditionalSearchFields?: string[];
}
export abstract class SOContentStorage<Types extends CMCrudTypes>
implements
ContentStorage<
Types['Item'],
Types['PartialItem'],
MSearchConfig<Types['Item'], Types['Attributes']>
>
{
constructor({
savedObjectType,
cmServicesDefinition,
createArgsToSoCreateOptions,
updateArgsToSoUpdateOptions,
searchArgsToSOFindOptions,
enableMSearch,
allowedSavedObjectAttributes,
mSearchAdditionalSearchFields,
}: SOContentStorageConstrutorParams<Types>) {
this.savedObjectType = savedObjectType;
this.cmServicesDefinition = cmServicesDefinition;
this.createArgsToSoCreateOptions =
createArgsToSoCreateOptions || createArgsToSoCreateOptionsDefault;
this.updateArgsToSoUpdateOptions =
updateArgsToSoUpdateOptions || updateArgsToSoUpdateOptionsDefault;
this.searchArgsToSOFindOptions = searchArgsToSOFindOptions || searchArgsToSOFindOptionsDefault;
this.allowedSavedObjectAttributes = allowedSavedObjectAttributes;
if (enableMSearch) {
this.mSearch = {
savedObjectType: this.savedObjectType,
additionalSearchFields: mSearchAdditionalSearchFields,
toItemResult: (ctx: StorageContext, savedObject: SavedObjectsFindResult): Types['Item'] => {
const transforms = ctx.utils.getTransforms(this.cmServicesDefinition);
// Validate DB response and DOWN transform to the request version
const { value, error: resultError } = transforms.mSearch.out.result.down<
Types['Item'],
Types['Item']
>(
savedObjectToItem(
savedObject as SavedObjectsFindResult<Types['Attributes']>,
this.allowedSavedObjectAttributes,
false
)
);
if (resultError) {
throw Boom.badRequest(`Invalid response. ${resultError.message}`);
}
return value;
},
};
}
}
private savedObjectType: SOContentStorageConstrutorParams<Types>['savedObjectType'];
private cmServicesDefinition: SOContentStorageConstrutorParams<Types>['cmServicesDefinition'];
private createArgsToSoCreateOptions: CreateArgsToSoCreateOptions<Types>;
private updateArgsToSoUpdateOptions: UpdateArgsToSoUpdateOptions<Types>;
private searchArgsToSOFindOptions: SearchArgsToSOFindOptions<Types>;
private allowedSavedObjectAttributes: string[];
mSearch?: {
savedObjectType: string;
toItemResult: (ctx: StorageContext, savedObject: SavedObjectsFindResult) => Types['Item'];
additionalSearchFields?: string[];
};
async get(ctx: StorageContext, id: string): Promise<Types['GetOut']> {
const transforms = ctx.utils.getTransforms(this.cmServicesDefinition);
const soClient = await savedObjectClientFromRequest(ctx);
// Save data in DB
const {
saved_object: savedObject,
alias_purpose: aliasPurpose,
alias_target_id: aliasTargetId,
outcome,
} = await soClient.resolve<Types['Attributes']>(this.savedObjectType, id);
const response: Types['GetOut'] = {
item: savedObjectToItem(savedObject, this.allowedSavedObjectAttributes, false),
meta: {
aliasPurpose,
aliasTargetId,
outcome,
},
};
// Validate DB response and DOWN transform to the request version
const { value, error: resultError } = transforms.get.out.result.down<
Types['GetOut'],
Types['GetOut']
>(response);
if (resultError) {
throw Boom.badRequest(`Invalid response. ${resultError.message}`);
}
return value;
}
async bulkGet(): Promise<never> {
// Not implemented
throw new Error(`[bulkGet] has not been implemented. See ${this.constructor.name} class.`);
}
async create(
ctx: StorageContext,
data: Types['Attributes'],
options: Types['CreateOptions']
): Promise<Types['CreateOut']> {
const transforms = ctx.utils.getTransforms(this.cmServicesDefinition);
const soClient = await savedObjectClientFromRequest(ctx);
// Validate input (data & options) & UP transform them to the latest version
const { value: dataToLatest, error: dataError } = transforms.create.in.data.up<
Types['Attributes'],
Types['Attributes']
>(data);
if (dataError) {
throw Boom.badRequest(`Invalid data. ${dataError.message}`);
}
const { value: optionsToLatest, error: optionsError } = transforms.create.in.options.up<
Types['CreateOptions'],
Types['CreateOptions']
>(options);
if (optionsError) {
throw Boom.badRequest(`Invalid options. ${optionsError.message}`);
}
const createOptions = this.createArgsToSoCreateOptions(optionsToLatest);
// Save data in DB
const savedObject = await soClient.create<Types['Attributes']>(
this.savedObjectType,
dataToLatest,
createOptions
);
// Validate DB response and DOWN transform to the request version
const { value, error: resultError } = transforms.create.out.result.down<
Types['CreateOut'],
Types['CreateOut']
>({
item: savedObjectToItem(savedObject, this.allowedSavedObjectAttributes, false),
});
if (resultError) {
throw Boom.badRequest(`Invalid response. ${resultError.message}`);
}
return value;
}
async update(
ctx: StorageContext,
id: string,
data: Types['Attributes'],
options: Types['UpdateOptions']
): Promise<Types['UpdateOut']> {
const transforms = ctx.utils.getTransforms(this.cmServicesDefinition);
const soClient = await savedObjectClientFromRequest(ctx);
// Validate input (data & options) & UP transform them to the latest version
const { value: dataToLatest, error: dataError } = transforms.update.in.data.up<
Types['Attributes'],
Types['Attributes']
>(data);
if (dataError) {
throw Boom.badRequest(`Invalid data. ${dataError.message}`);
}
const { value: optionsToLatest, error: optionsError } = transforms.update.in.options.up<
Types['CreateOptions'],
Types['CreateOptions']
>(options);
if (optionsError) {
throw Boom.badRequest(`Invalid options. ${optionsError.message}`);
}
const updateOptions = this.updateArgsToSoUpdateOptions(optionsToLatest);
// Save data in DB
const partialSavedObject = await soClient.update<Types['Attributes']>(
this.savedObjectType,
id,
dataToLatest,
updateOptions
);
// Validate DB response and DOWN transform to the request version
const { value, error: resultError } = transforms.update.out.result.down<
Types['UpdateOut'],
Types['UpdateOut']
>({
item: savedObjectToItem(partialSavedObject, this.allowedSavedObjectAttributes, true),
});
if (resultError) {
throw Boom.badRequest(`Invalid response. ${resultError.message}`);
}
return value;
}
async delete(
ctx: StorageContext,
id: string,
// force is necessary to delete saved objects that exist in multiple namespaces
options?: { force: boolean }
): Promise<Types['DeleteOut']> {
const soClient = await savedObjectClientFromRequest(ctx);
await soClient.delete(this.savedObjectType, id, { force: options?.force ?? false });
return { success: true };
}
async search(
ctx: StorageContext,
query: SearchQuery,
options: Types['SearchOptions'] = {}
): Promise<Types['SearchOut']> {
const transforms = ctx.utils.getTransforms(this.cmServicesDefinition);
const soClient = await savedObjectClientFromRequest(ctx);
// Validate and UP transform the options
const { value: optionsToLatest, error: optionsError } = transforms.search.in.options.up<
Types['SearchOptions'],
Types['SearchOptions']
>(options);
if (optionsError) {
throw Boom.badRequest(`Invalid payload. ${optionsError.message}`);
}
const soQuery: SavedObjectsFindOptions = this.searchArgsToSOFindOptions({
contentTypeId: this.savedObjectType,
query,
options: optionsToLatest,
});
// Execute the query in the DB
const response = await soClient.find<Types['Attributes']>(soQuery);
// Validate the response and DOWN transform to the request version
const { value, error: resultError } = transforms.search.out.result.down<
Types['SearchOut'],
Types['SearchOut']
>({
hits: response.saved_objects.map((so) =>
savedObjectToItem(so, this.allowedSavedObjectAttributes, false)
),
pagination: {
total: response.total,
},
});
if (resultError) {
throw Boom.badRequest(`Invalid response. ${resultError.message}`);
}
return value;
}
}