@webiny/api-file-manager-ddb 5.15.0-beta.0 → 5.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,8 @@ var _filter = require("@webiny/db-dynamodb/utils/filter");
27
27
 
28
28
  var _sort = require("@webiny/db-dynamodb/utils/sort");
29
29
 
30
+ var _FileDynamoDbFieldPlugin = require("../../plugins/FileDynamoDbFieldPlugin");
31
+
30
32
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
31
33
 
32
34
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
@@ -220,16 +222,18 @@ class FilesStorageOperations {
220
222
  }
221
223
  });
222
224
  }
225
+
226
+ const fields = this.context.plugins.byType(_FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin.type);
223
227
  /**
224
228
  * Filter the read items via the code.
225
229
  * It will build the filters out of the where input and transform the values it is using.
226
230
  */
227
231
 
228
-
229
232
  const filteredFiles = (0, _filter.filterItems)({
230
233
  items,
231
234
  where,
232
- context: this.context
235
+ context: this.context,
236
+ fields
233
237
  });
234
238
  const totalCount = filteredFiles.length;
235
239
  /**
@@ -238,10 +242,9 @@ class FilesStorageOperations {
238
242
  */
239
243
 
240
244
  const sortedFiles = (0, _sort.sortItems)({
241
- context: this.context,
242
245
  items: filteredFiles,
243
246
  sort,
244
- fields: ["id", "createdBy", "createdOn"]
247
+ fields
245
248
  });
246
249
  const start = (0, _cursor.decodeCursor)(after) || 0;
247
250
  const hasMoreItems = totalCount > start + limit;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/operations/files/FilesStorageOperations.ts"],"names":["cleanStorageFile","file","FilesStorageOperations","context","_context","partitionKey","tenant","tenancy","getCurrentTenant","locale","i18nContent","getLocale","WebinyError","Error","id","code","constructor","_table","_entity","table","get","PK","SK","getSortKey","Item","ex","message","create","params","keys","item","TYPE","put","update","delete","createBatch","files","fileChunks","fileChunk","batches","push","putBatch","batchWrite","items","list","where","limit","after","sort","options","createQueryAllOptions","queryAllParams","entity","queryParams","name","filteredFiles","totalCount","length","sortedFiles","fields","start","hasMoreItems","end","undefined","slice","cursor","meta","tags","filters","attr","eq","reverse","query","tagsObject","reduce","collection","tag","Object","match"],"mappings":";;;;;;;;;;;AAaA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AACA;;;;;;AAgBA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAIC,IAAD,IAA4C;AACjE,SAAO,qBAAWA,IAAX,EAAiB,CAAC,IAAD,EAAO,IAAP,EAAa,MAAb,EAAqB,SAArB,EAAgC,UAAhC,EAA4C,QAA5C,CAAjB,CAAP;AACH,CAFD;;AAIO,MAAMC,sBAAN,CAA0E;AAK1D,MAAPC,OAAO,GAAuB;AACtC,WAAO,KAAKC,QAAZ;AACH;;AAEuB,MAAZC,YAAY,GAAW;AAC/B,UAAMC,MAAM,GAAG,KAAKH,OAAL,CAAaI,OAAb,CAAqBC,gBAArB,EAAf;AACA,UAAMC,MAAM,GAAG,KAAKN,OAAL,CAAaO,WAAb,CAAyBC,SAAzB,EAAf;;AACA,QAAI,CAACL,MAAL,EAAa;AACT,YAAM,IAAIM,cAAJ,CAAgB,iBAAhB,EAAmC,kBAAnC,CAAN;AACH;;AACD,QAAI,CAACH,MAAL,EAAa;AACT,YAAM,IAAII,KAAJ,CA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;AACtC,YAAM,IAAIlE,cAAJ,CAAgB,wCAAhB,EAA0D,qBAA1D,EAAiF;AACnFE,QAAAA;AADmF,OAAjF,CAAN;AAGH;;AACD,WAAOA,EAAP;AACH;;AAEOoC,EAAAA,qBAAqB,CAAC;AAAEL,IAAAA;AAAF,GAAD,EAAgE;AACzF,UAAMI,OAAoC,GAAG,EAA7C;;AACA,QAAIJ,KAAK,CAAC/B,EAAV,EAAc;AACVmC,MAAAA,OAAO,CAACqB,EAAR,GAAazB,KAAK,CAAC/B,EAAnB;AACH;;AACD,WAAOmC,OAAP;AACH;;AAnU4E","sourcesContent":["import {\n File,\n FileManagerContext,\n FileManagerFilesStorageOperations,\n FileManagerFilesStorageOperationsCreateParams,\n FileManagerFilesStorageOperationsListParams,\n FileManagerFilesStorageOperationsListParamsWhere,\n FileManagerFilesStorageOperationsListResponse,\n FileManagerFilesStorageOperationsTagsParams,\n FileManagerFilesStorageOperationsTagsResponse,\n FileManagerFilesStorageOperationsUpdateParams\n} from \"@webiny/api-file-manager/types\";\nimport { Entity, Table } from \"dynamodb-toolbox\";\nimport WebinyError from \"@webiny/error\";\nimport defineTable from \"~/definitions/table\";\nimport defineFilesEntity from \"~/definitions/filesEntity\";\nimport lodashOmit from \"lodash.omit\";\nimport lodashChunk from \"lodash.chunk\";\nimport { queryOptions as DynamoDBToolboxQueryOptions } from \"dynamodb-toolbox/dist/classes/Table\";\nimport { queryAll } from \"@webiny/db-dynamodb/utils/query\";\nimport { FilterExpressions } from \"dynamodb-toolbox/dist/lib/expressionBuilder\";\nimport { decodeCursor, encodeCursor } from \"@webiny/db-dynamodb/utils/cursor\";\nimport { filterItems } from \"@webiny/db-dynamodb/utils/filter\";\nimport { sortItems } from \"@webiny/db-dynamodb/utils/sort\";\n\ninterface FileItem extends File {\n PK: string;\n SK: string;\n TYPE: string;\n}\n\ninterface ConstructorParams {\n context: FileManagerContext;\n}\n\ninterface QueryAllOptionsParams {\n where: FileManagerFilesStorageOperationsListParamsWhere;\n}\n\n/**\n * This is required due to sometimes file data sent is from the DynamoDB and we want to remove the unnecessary stuff.\n */\nconst cleanStorageFile = (file: File & Record<string, any>): File => {\n return lodashOmit(file, [\"PK\", \"SK\", \"TYPE\", \"created\", \"modified\", \"entity\"]);\n};\n\nexport class FilesStorageOperations implements FileManagerFilesStorageOperations {\n private readonly _context: any;\n private readonly _table: Table;\n private readonly _entity: Entity<any>;\n\n private get context(): FileManagerContext {\n return this._context;\n }\n\n private get partitionKey(): string {\n const tenant = this.context.tenancy.getCurrentTenant();\n const locale = this.context.i18nContent.getLocale();\n if (!tenant) {\n throw new WebinyError(\"Tenant missing.\", \"TENANT_NOT_FOUND\");\n }\n if (!locale) {\n throw new Error(\"Locale missing.\");\n }\n return `T#${tenant.id}#L#${locale.code}#FM#F`;\n }\n\n public constructor({ context }: ConstructorParams) {\n this._context = context;\n this._table = defineTable({\n context\n });\n\n this._entity = defineFilesEntity({\n context,\n table: this._table\n });\n }\n\n public async get(id: string): Promise<File | null> {\n try {\n const file = await this._entity.get({\n PK: this.partitionKey,\n SK: this.getSortKey(id)\n });\n if (!file || !file.Item) {\n return null;\n }\n return cleanStorageFile(file.Item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not fetch requested file.\",\n ex.code || \"GET_FILE_ERROR\",\n {\n id\n }\n );\n }\n }\n\n public async create(params: FileManagerFilesStorageOperationsCreateParams): Promise<File> {\n const { file } = params;\n\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n const item: FileItem = {\n ...keys,\n TYPE: \"fm.file\",\n ...file\n };\n try {\n await this._entity.put(item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not create a new file in the DynamoDB.\",\n ex.code || \"CREATE_FILE_ERROR\",\n {\n item\n }\n );\n }\n\n return file;\n }\n\n public async update({ file }: FileManagerFilesStorageOperationsUpdateParams): Promise<File> {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n\n const item: FileItem = {\n ...keys,\n TYPE: \"fm.file\",\n ...file\n };\n try {\n await this._entity.put(item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not update a file in the DynamoDB.\",\n ex.code || \"UPDATE_FILE_ERROR\",\n {\n item\n }\n );\n }\n return file;\n }\n\n public async delete(id: string): Promise<void> {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(id)\n };\n\n try {\n await this._entity.delete(keys);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not delete file from the DynamoDB.\",\n ex.code || \"DELETE_FILE_ERROR\",\n {\n id,\n keys\n }\n );\n }\n }\n\n public async createBatch({ files }): Promise<File[]> {\n const fileChunks = lodashChunk(files, 25);\n\n for (const fileChunk of fileChunks) {\n const batches = [];\n for (const file of fileChunk) {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n batches.push(\n this._entity.putBatch({\n ...keys,\n TYPE: \"fm.file\",\n ...file\n })\n );\n }\n try {\n await this._table.batchWrite(batches);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not batch insert a list of files.\",\n ex.code || \"BATCH_CREATE_FILES_ERROR\",\n {\n files: fileChunk,\n items: batches\n }\n );\n }\n }\n return files;\n }\n\n public async list(\n params: FileManagerFilesStorageOperationsListParams\n ): Promise<FileManagerFilesStorageOperationsListResponse> {\n const { where, limit, after, sort } = params;\n\n const options = this.createQueryAllOptions({\n where\n });\n const queryAllParams = {\n entity: this._entity,\n partitionKey: this.partitionKey,\n options\n };\n let items: FileItem[] = [];\n try {\n items = await queryAll(queryAllParams);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not query for the files.\",\n ex.code || \"FILE_LIST_ERROR\",\n {\n where,\n limit,\n after,\n sort,\n queryParams: {\n options,\n partitionKey: queryAllParams.partitionKey,\n entity: queryAllParams.entity.name,\n table: queryAllParams.entity.table.name\n }\n }\n );\n }\n /**\n * Filter the read items via the code.\n * It will build the filters out of the where input and transform the values it is using.\n */\n const filteredFiles = filterItems({\n items,\n where,\n context: this.context\n });\n\n const totalCount = filteredFiles.length;\n /**\n * Sorting is also done via the code.\n * It takes the sort input and sorts by it via the lodash sortBy method.\n */\n const sortedFiles = sortItems({\n context: this.context,\n items: filteredFiles,\n sort,\n fields: [\"id\", \"createdBy\", \"createdOn\"]\n });\n\n const start = decodeCursor(after) || 0;\n const hasMoreItems = totalCount > start + limit;\n const end = limit > totalCount + start + limit ? undefined : start + limit;\n const files = sortedFiles.slice(start, end);\n /**\n * Although we do not need a cursor here, we will use it as such to keep it standardized.\n * Number is simply encoded.\n */\n const cursor = files.length > 0 ? encodeCursor(start + limit) : null;\n\n const meta = {\n hasMoreItems,\n totalCount: totalCount,\n cursor\n };\n\n return [files, meta];\n }\n public async tags(\n params: FileManagerFilesStorageOperationsTagsParams\n ): Promise<FileManagerFilesStorageOperationsTagsResponse> {\n const { where } = params;\n\n const filters: FilterExpressions = [];\n if (where.locale) {\n filters.push({\n attr: \"locale\",\n eq: where.locale\n });\n delete where.locale;\n }\n if (where.tenant) {\n filters.push({\n attr: \"tenant\",\n eq: where.tenant\n });\n delete where.tenant;\n }\n\n const options: DynamoDBToolboxQueryOptions = {\n filters,\n reverse: false\n };\n\n let items: FileItem[] = [];\n\n const queryAllParams = {\n entity: this._entity,\n partitionKey: this.partitionKey,\n options\n };\n try {\n items = await queryAll(queryAllParams);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Error in the DynamoDB query.\",\n ex.code || \"DYNAMODB_ERROR\",\n {\n query: queryAllParams\n }\n );\n }\n /**\n * Aggregate all the tags from all the items in the database.\n */\n const tagsObject = items.reduce((collection, item) => {\n for (const tag of item.tags) {\n if (!collection[tag]) {\n collection[tag] = [];\n }\n collection[tag].push(item.id);\n }\n return collection;\n }, {});\n\n const tags: string[] = Object.keys(tagsObject);\n\n const hasMoreItems = false;\n const totalCount = tags.length;\n\n const meta = {\n hasMoreItems,\n totalCount,\n cursor: null\n };\n\n return [tags, meta];\n }\n /**\n * Create the sort key for the file.\n * Actually those are just some checks.\n */\n private getSortKey(id: string) {\n if (!id || !id.match(/^([a-zA-Z0-9]+)$/)) {\n throw new WebinyError(\"Could not determine the file sort key.\", \"FILE_SORT_KEY_ERROR\", {\n id\n });\n }\n return id;\n }\n\n private createQueryAllOptions({ where }: QueryAllOptionsParams): DynamoDBToolboxQueryOptions {\n const options: DynamoDBToolboxQueryOptions = {};\n if (where.id) {\n options.eq = where.id;\n }\n return options;\n }\n}\n"],"file":"FilesStorageOperations.js"}
1
+ {"version":3,"sources":["../../../src/operations/files/FilesStorageOperations.ts"],"names":["cleanStorageFile","file","FilesStorageOperations","context","_context","partitionKey","tenant","tenancy","getCurrentTenant","locale","i18nContent","getLocale","WebinyError","Error","id","code","constructor","_table","_entity","table","get","PK","SK","getSortKey","Item","ex","message","create","params","keys","item","TYPE","put","update","delete","createBatch","files","fileChunks","fileChunk","batches","push","putBatch","batchWrite","items","list","where","limit","after","sort","options","createQueryAllOptions","queryAllParams","entity","queryParams","name","fields","plugins","byType","FileDynamoDbFieldPlugin","type","filteredFiles","totalCount","length","sortedFiles","start","hasMoreItems","end","undefined","slice","cursor","meta","tags","filters","attr","eq","reverse","query","tagsObject","reduce","collection","tag","Object","match"],"mappings":";;;;;;;;;;;AAaA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AACA;;AACA;;;;;;AAgBA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAIC,IAAD,IAA4C;AACjE,SAAO,qBAAWA,IAAX,EAAiB,CAAC,IAAD,EAAO,IAAP,EAAa,MAAb,EAAqB,SAArB,EAAgC,UAAhC,EAA4C,QAA5C,CAAjB,CAAP;AACH,CAFD;;AAIO,MAAMC,sBAAN,CAA0E;AAK1D,MAAPC,OAAO,GAAuB;AACtC,WAAO,KAAKC,QAAZ;AACH;;AAEuB,MAAZC,YAAY,GAAW;AAC/B,UAAMC,MAAM,GAAG,KAAKH,OAAL,CAAaI,OAAb,CAAqBC,gBAArB,EAAf;AACA,UAAMC,M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S;AAETJ,MAAAA,UAFS;AAGTQ,MAAAA,MAAM,EAAE;AAHC,KAAb;AAMA,WAAO,CAACE,IAAD,EAAOD,IAAP,CAAP;AACH;AACD;AACJ;AACA;AACA;;;AACY/C,EAAAA,UAAU,CAACT,EAAD,EAAa;AAC3B,QAAI,CAACA,EAAD,IAAO,CAACA,EAAE,CAACoE,KAAH,CAAS,kBAAT,CAAZ,EAA0C;AACtC,YAAM,IAAItE,cAAJ,CAAgB,wCAAhB,EAA0D,qBAA1D,EAAiF;AACnFE,QAAAA;AADmF,OAAjF,CAAN;AAGH;;AACD,WAAOA,EAAP;AACH;;AAEOoC,EAAAA,qBAAqB,CAAC;AAAEL,IAAAA;AAAF,GAAD,EAAgE;AACzF,UAAMI,OAAoC,GAAG,EAA7C;;AACA,QAAIJ,KAAK,CAAC/B,EAAV,EAAc;AACVmC,MAAAA,OAAO,CAACyB,EAAR,GAAa7B,KAAK,CAAC/B,EAAnB;AACH;;AACD,WAAOmC,OAAP;AACH;;AAvU4E","sourcesContent":["import {\n File,\n FileManagerContext,\n FileManagerFilesStorageOperations,\n FileManagerFilesStorageOperationsCreateParams,\n FileManagerFilesStorageOperationsListParams,\n FileManagerFilesStorageOperationsListParamsWhere,\n FileManagerFilesStorageOperationsListResponse,\n FileManagerFilesStorageOperationsTagsParams,\n FileManagerFilesStorageOperationsTagsResponse,\n FileManagerFilesStorageOperationsUpdateParams\n} from \"@webiny/api-file-manager/types\";\nimport { Entity, Table } from \"dynamodb-toolbox\";\nimport WebinyError from \"@webiny/error\";\nimport defineTable from \"~/definitions/table\";\nimport defineFilesEntity from \"~/definitions/filesEntity\";\nimport lodashOmit from \"lodash.omit\";\nimport lodashChunk from \"lodash.chunk\";\nimport { queryOptions as DynamoDBToolboxQueryOptions } from \"dynamodb-toolbox/dist/classes/Table\";\nimport { queryAll } from \"@webiny/db-dynamodb/utils/query\";\nimport { FilterExpressions } from \"dynamodb-toolbox/dist/lib/expressionBuilder\";\nimport { decodeCursor, encodeCursor } from \"@webiny/db-dynamodb/utils/cursor\";\nimport { filterItems } from \"@webiny/db-dynamodb/utils/filter\";\nimport { sortItems } from \"@webiny/db-dynamodb/utils/sort\";\nimport { FileDynamoDbFieldPlugin } from \"~/plugins/FileDynamoDbFieldPlugin\";\n\ninterface FileItem extends File {\n PK: string;\n SK: string;\n TYPE: string;\n}\n\ninterface ConstructorParams {\n context: FileManagerContext;\n}\n\ninterface QueryAllOptionsParams {\n where: FileManagerFilesStorageOperationsListParamsWhere;\n}\n\n/**\n * This is required due to sometimes file data sent is from the DynamoDB and we want to remove the unnecessary stuff.\n */\nconst cleanStorageFile = (file: File & Record<string, any>): File => {\n return lodashOmit(file, [\"PK\", \"SK\", \"TYPE\", \"created\", \"modified\", \"entity\"]);\n};\n\nexport class FilesStorageOperations implements FileManagerFilesStorageOperations {\n private readonly _context: any;\n private readonly _table: Table;\n private readonly _entity: Entity<any>;\n\n private get context(): FileManagerContext {\n return this._context;\n }\n\n private get partitionKey(): string {\n const tenant = this.context.tenancy.getCurrentTenant();\n const locale = this.context.i18nContent.getLocale();\n if (!tenant) {\n throw new WebinyError(\"Tenant missing.\", \"TENANT_NOT_FOUND\");\n }\n if (!locale) {\n throw new Error(\"Locale missing.\");\n }\n return `T#${tenant.id}#L#${locale.code}#FM#F`;\n }\n\n public constructor({ context }: ConstructorParams) {\n this._context = context;\n this._table = defineTable({\n context\n });\n\n this._entity = defineFilesEntity({\n context,\n table: this._table\n });\n }\n\n public async get(id: string): Promise<File | null> {\n try {\n const file = await this._entity.get({\n PK: this.partitionKey,\n SK: this.getSortKey(id)\n });\n if (!file || !file.Item) {\n return null;\n }\n return cleanStorageFile(file.Item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not fetch requested file.\",\n ex.code || \"GET_FILE_ERROR\",\n {\n id\n }\n );\n }\n }\n\n public async create(params: FileManagerFilesStorageOperationsCreateParams): Promise<File> {\n const { file } = params;\n\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n const item: FileItem = {\n ...keys,\n TYPE: \"fm.file\",\n ...file\n };\n try {\n await this._entity.put(item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not create a new file in the DynamoDB.\",\n ex.code || \"CREATE_FILE_ERROR\",\n {\n item\n }\n );\n }\n\n return file;\n }\n\n public async update({ file }: FileManagerFilesStorageOperationsUpdateParams): Promise<File> {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n\n const item: FileItem = {\n ...keys,\n TYPE: \"fm.file\",\n ...file\n };\n try {\n await this._entity.put(item);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not update a file in the DynamoDB.\",\n ex.code || \"UPDATE_FILE_ERROR\",\n {\n item\n }\n );\n }\n return file;\n }\n\n public async delete(id: string): Promise<void> {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(id)\n };\n\n try {\n await this._entity.delete(keys);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not delete file from the DynamoDB.\",\n ex.code || \"DELETE_FILE_ERROR\",\n {\n id,\n keys\n }\n );\n }\n }\n\n public async createBatch({ files }): Promise<File[]> {\n const fileChunks = lodashChunk(files, 25);\n\n for (const fileChunk of fileChunks) {\n const batches = [];\n for (const file of fileChunk) {\n const keys = {\n PK: this.partitionKey,\n SK: this.getSortKey(file.id)\n };\n batches.push(\n this._entity.putBatch({\n ...keys,\n TYPE: \"fm.file\",\n ...file\n })\n );\n }\n try {\n await this._table.batchWrite(batches);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not batch insert a list of files.\",\n ex.code || \"BATCH_CREATE_FILES_ERROR\",\n {\n files: fileChunk,\n items: batches\n }\n );\n }\n }\n return files;\n }\n\n public async list(\n params: FileManagerFilesStorageOperationsListParams\n ): Promise<FileManagerFilesStorageOperationsListResponse> {\n const { where, limit, after, sort } = params;\n\n const options = this.createQueryAllOptions({\n where\n });\n const queryAllParams = {\n entity: this._entity,\n partitionKey: this.partitionKey,\n options\n };\n let items: FileItem[] = [];\n try {\n items = await queryAll(queryAllParams);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not query for the files.\",\n ex.code || \"FILE_LIST_ERROR\",\n {\n where,\n limit,\n after,\n sort,\n queryParams: {\n options,\n partitionKey: queryAllParams.partitionKey,\n entity: queryAllParams.entity.name,\n table: queryAllParams.entity.table.name\n }\n }\n );\n }\n\n const fields = this.context.plugins.byType<FileDynamoDbFieldPlugin>(\n FileDynamoDbFieldPlugin.type\n );\n /**\n * Filter the read items via the code.\n * It will build the filters out of the where input and transform the values it is using.\n */\n const filteredFiles = filterItems({\n items,\n where,\n context: this.context,\n fields\n });\n\n const totalCount = filteredFiles.length;\n /**\n * Sorting is also done via the code.\n * It takes the sort input and sorts by it via the lodash sortBy method.\n */\n const sortedFiles = sortItems({\n items: filteredFiles,\n sort,\n fields\n });\n\n const start = decodeCursor(after) || 0;\n const hasMoreItems = totalCount > start + limit;\n const end = limit > totalCount + start + limit ? undefined : start + limit;\n const files = sortedFiles.slice(start, end);\n /**\n * Although we do not need a cursor here, we will use it as such to keep it standardized.\n * Number is simply encoded.\n */\n const cursor = files.length > 0 ? encodeCursor(start + limit) : null;\n\n const meta = {\n hasMoreItems,\n totalCount: totalCount,\n cursor\n };\n\n return [files, meta];\n }\n public async tags(\n params: FileManagerFilesStorageOperationsTagsParams\n ): Promise<FileManagerFilesStorageOperationsTagsResponse> {\n const { where } = params;\n\n const filters: FilterExpressions = [];\n if (where.locale) {\n filters.push({\n attr: \"locale\",\n eq: where.locale\n });\n delete where.locale;\n }\n if (where.tenant) {\n filters.push({\n attr: \"tenant\",\n eq: where.tenant\n });\n delete where.tenant;\n }\n\n const options: DynamoDBToolboxQueryOptions = {\n filters,\n reverse: false\n };\n\n let items: FileItem[] = [];\n\n const queryAllParams = {\n entity: this._entity,\n partitionKey: this.partitionKey,\n options\n };\n try {\n items = await queryAll(queryAllParams);\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Error in the DynamoDB query.\",\n ex.code || \"DYNAMODB_ERROR\",\n {\n query: queryAllParams\n }\n );\n }\n /**\n * Aggregate all the tags from all the items in the database.\n */\n const tagsObject = items.reduce((collection, item) => {\n for (const tag of item.tags) {\n if (!collection[tag]) {\n collection[tag] = [];\n }\n collection[tag].push(item.id);\n }\n return collection;\n }, {});\n\n const tags: string[] = Object.keys(tagsObject);\n\n const hasMoreItems = false;\n const totalCount = tags.length;\n\n const meta = {\n hasMoreItems,\n totalCount,\n cursor: null\n };\n\n return [tags, meta];\n }\n /**\n * Create the sort key for the file.\n * Actually those are just some checks.\n */\n private getSortKey(id: string) {\n if (!id || !id.match(/^([a-zA-Z0-9]+)$/)) {\n throw new WebinyError(\"Could not determine the file sort key.\", \"FILE_SORT_KEY_ERROR\", {\n id\n });\n }\n return id;\n }\n\n private createQueryAllOptions({ where }: QueryAllOptionsParams): DynamoDBToolboxQueryOptions {\n const options: DynamoDBToolboxQueryOptions = {};\n if (where.id) {\n options.eq = where.id;\n }\n return options;\n }\n}\n"],"file":"FilesStorageOperations.js"}
@@ -1,5 +1,3 @@
1
- import { FieldPathPlugin } from "@webiny/db-dynamodb/plugins/definitions/FieldPathPlugin";
2
- import { DateTimeTransformPlugin } from "@webiny/db-dynamodb/plugins/definitions/DateTimeTransformPlugin";
3
- import { NumberTransformPlugin } from "@webiny/db-dynamodb/plugins/definitions/NumberTransformPlugin";
4
- declare const _default: () => (FieldPathPlugin | DateTimeTransformPlugin | NumberTransformPlugin)[];
1
+ import { FileDynamoDbFieldPlugin } from "../../plugins/FileDynamoDbFieldPlugin";
2
+ declare const _default: () => FileDynamoDbFieldPlugin[];
5
3
  export default _default;
@@ -5,51 +5,38 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
 
8
- var _FieldPathPlugin = require("@webiny/db-dynamodb/plugins/definitions/FieldPathPlugin");
8
+ var _FileDynamoDbFieldPlugin = require("../../plugins/FileDynamoDbFieldPlugin");
9
9
 
10
- var _DateTimeTransformPlugin = require("@webiny/db-dynamodb/plugins/definitions/DateTimeTransformPlugin");
11
-
12
- var _NumberTransformPlugin = require("@webiny/db-dynamodb/plugins/definitions/NumberTransformPlugin");
13
-
14
- var _default = () => [
10
+ var _default = () => [new _FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin({
11
+ field: "id"
12
+ }),
15
13
  /**
16
- * Path plugin for the fields that are ddb map type and the value filtered by is the id property in the object.
14
+ * Path plugin for the field that are ddb map type and the value filtered by is the id property in the object.
17
15
  */
18
- new _FieldPathPlugin.FieldPathPlugin({
19
- fields: ["createdBy"],
20
- createPath: field => {
21
- return `${field}.id`;
22
- }
16
+ new _FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin({
17
+ field: "createdBy",
18
+ path: "createdBy.id"
23
19
  }),
24
20
  /**
25
21
  * Path plugin for meta field properties.
26
22
  */
27
- new _FieldPathPlugin.FieldPathPlugin({
28
- fields: ["private"],
29
- createPath: field => {
30
- return `meta.${field}`;
31
- }
23
+ new _FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin({
24
+ field: "private",
25
+ path: "meta.private"
32
26
  }),
33
27
  /**
34
28
  * Path plugin for tag field.
35
29
  */
36
- new _FieldPathPlugin.FieldPathPlugin({
37
- fields: ["tag", "tags"],
38
- createPath: () => {
39
- return `tags`;
40
- }
41
- }),
42
- /**
43
- * Value transformation for the dateTime fields.
44
- */
45
- new _DateTimeTransformPlugin.DateTimeTransformPlugin({
46
- fields: ["createdOn"]
30
+ new _FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin({
31
+ field: "tag",
32
+ path: "tags"
47
33
  }),
48
34
  /**
49
- * Value transformation for the number fields.
35
+ * Value transformation for the dateTime field.
50
36
  */
51
- new _NumberTransformPlugin.NumberTransformPlugin({
52
- fields: ["size"]
37
+ new _FileDynamoDbFieldPlugin.FileDynamoDbFieldPlugin({
38
+ field: "createdOn",
39
+ type: "date"
53
40
  })];
54
41
 
55
42
  exports.default = _default;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/operations/files/fields.ts"],"names":["FieldPathPlugin","fields","createPath","field","DateTimeTransformPlugin","NumberTransformPlugin"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;eAEe,MAAM;AACjB;AACJ;AACA;AACI,IAAIA,gCAAJ,CAAoB;AAChBC,EAAAA,MAAM,EAAE,CAAC,WAAD,CADQ;AAEhBC,EAAAA,UAAU,EAAGC,KAAD,IAA2B;AACnC,WAAQ,GAAEA,KAAM,KAAhB;AACH;AAJe,CAApB,CAJiB;AAUjB;AACJ;AACA;AACI,IAAIH,gCAAJ,CAAoB;AAChBC,EAAAA,MAAM,EAAE,CAAC,SAAD,CADQ;AAEhBC,EAAAA,UAAU,EAAGC,KAAD,IAAmB;AAC3B,WAAQ,QAAOA,KAAM,EAArB;AACH;AAJe,CAApB,CAbiB;AAmBjB;AACJ;AACA;AACI,IAAIH,gCAAJ,CAAoB;AAChBC,EAAAA,MAAM,EAAE,CAAC,KAAD,EAAQ,MAAR,CADQ;AAEhBC,EAAAA,UAAU,EAAE,MAAM;AACd,WAAQ,MAAR;AACH;AAJe,CAApB,CAtBiB;AA4BjB;AACJ;AACA;AACI,IAAIE,gDAAJ,CAA4B;AACxBH,EAAAA,MAAM,EAAE,CAAC,WAAD;AADgB,CAA5B,CA/BiB;AAkCjB;AACJ;AACA;AACI,IAAII,4CAAJ,CAA0B;AACtBJ,EAAAA,MAAM,EAAE,CAAC,MAAD;AADc,CAA1B,CArCiB,C","sourcesContent":["import { FieldPathPlugin } from \"@webiny/db-dynamodb/plugins/definitions/FieldPathPlugin\";\nimport { DateTimeTransformPlugin } from \"@webiny/db-dynamodb/plugins/definitions/DateTimeTransformPlugin\";\nimport { NumberTransformPlugin } from \"@webiny/db-dynamodb/plugins/definitions/NumberTransformPlugin\";\n\nexport default () => [\n /**\n * Path plugin for the fields that are ddb map type and the value filtered by is the id property in the object.\n */\n new FieldPathPlugin({\n fields: [\"createdBy\"],\n createPath: (field: string): string => {\n return `${field}.id`;\n }\n }),\n /**\n * Path plugin for meta field properties.\n */\n new FieldPathPlugin({\n fields: [\"private\"],\n createPath: (field: string) => {\n return `meta.${field}`;\n }\n }),\n /**\n * Path plugin for tag field.\n */\n new FieldPathPlugin({\n fields: [\"tag\", \"tags\"],\n createPath: () => {\n return `tags`;\n }\n }),\n /**\n * Value transformation for the dateTime fields.\n */\n new DateTimeTransformPlugin({\n fields: [\"createdOn\"]\n }),\n /**\n * Value transformation for the number fields.\n */\n new NumberTransformPlugin({\n fields: [\"size\"]\n })\n];\n"],"file":"fields.js"}
1
+ {"version":3,"sources":["../../../src/operations/files/fields.ts"],"names":["FileDynamoDbFieldPlugin","field","path","type"],"mappings":";;;;;;;AAAA;;eAEe,MAAM,CACjB,IAAIA,gDAAJ,CAA4B;AACxBC,EAAAA,KAAK,EAAE;AADiB,CAA5B,CADiB;AAIjB;AACJ;AACA;AACI,IAAID,gDAAJ,CAA4B;AACxBC,EAAAA,KAAK,EAAE,WADiB;AAExBC,EAAAA,IAAI,EAAE;AAFkB,CAA5B,CAPiB;AAWjB;AACJ;AACA;AACI,IAAIF,gDAAJ,CAA4B;AACxBC,EAAAA,KAAK,EAAE,SADiB;AAExBC,EAAAA,IAAI,EAAE;AAFkB,CAA5B,CAdiB;AAkBjB;AACJ;AACA;AACI,IAAIF,gDAAJ,CAA4B;AACxBC,EAAAA,KAAK,EAAE,KADiB;AAExBC,EAAAA,IAAI,EAAE;AAFkB,CAA5B,CArBiB;AAyBjB;AACJ;AACA;AACI,IAAIF,gDAAJ,CAA4B;AACxBC,EAAAA,KAAK,EAAE,WADiB;AAExBE,EAAAA,IAAI,EAAE;AAFkB,CAA5B,CA5BiB,C","sourcesContent":["import { FileDynamoDbFieldPlugin } from \"~/plugins/FileDynamoDbFieldPlugin\";\n\nexport default () => [\n new FileDynamoDbFieldPlugin({\n field: \"id\"\n }),\n /**\n * Path plugin for the field that are ddb map type and the value filtered by is the id property in the object.\n */\n new FileDynamoDbFieldPlugin({\n field: \"createdBy\",\n path: \"createdBy.id\"\n }),\n /**\n * Path plugin for meta field properties.\n */\n new FileDynamoDbFieldPlugin({\n field: \"private\",\n path: \"meta.private\"\n }),\n /**\n * Path plugin for tag field.\n */\n new FileDynamoDbFieldPlugin({\n field: \"tag\",\n path: \"tags\"\n }),\n /**\n * Value transformation for the dateTime field.\n */\n new FileDynamoDbFieldPlugin({\n field: \"createdOn\",\n type: \"date\"\n })\n];\n"],"file":"fields.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-file-manager-ddb",
3
- "version": "5.15.0-beta.0",
3
+ "version": "5.15.0",
4
4
  "main": "index.js",
5
5
  "keywords": [
6
6
  "@webiny/api-file-manager",
@@ -22,10 +22,10 @@
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
24
  "@babel/runtime": "7.15.3",
25
- "@webiny/api-file-manager": "5.15.0-beta.0",
26
- "@webiny/db-dynamodb": "5.15.0-beta.0",
27
- "@webiny/error": "5.15.0-beta.0",
28
- "@webiny/project-utils": "5.15.0-beta.0",
25
+ "@webiny/api-file-manager": "5.15.0",
26
+ "@webiny/db-dynamodb": "5.15.0",
27
+ "@webiny/error": "5.15.0",
28
+ "@webiny/project-utils": "5.15.0",
29
29
  "aws-sdk": "2.968.0",
30
30
  "dynamodb-toolbox": "0.3.4",
31
31
  "lodash.chunk": "4.2.0",
@@ -38,7 +38,7 @@
38
38
  "@babel/plugin-transform-runtime": "^7.5.5",
39
39
  "@babel/preset-env": "^7.5.5",
40
40
  "@babel/preset-typescript": "^7.0.0",
41
- "@webiny/cli": "^5.15.0-beta.0",
41
+ "@webiny/cli": "^5.15.0",
42
42
  "jest": "^26.6.3",
43
43
  "jest-dynalite": "^3.2.0",
44
44
  "jsonpack": "^1.1.5",
@@ -65,5 +65,5 @@
65
65
  ]
66
66
  }
67
67
  },
68
- "gitHead": "baf2dbb8cae1b623b59d20fedc0cd0e11a310ca1"
68
+ "gitHead": "fd0ba247e5e0e2f5df66c8179f09af5ad6e9a0f2"
69
69
  }
@@ -0,0 +1,4 @@
1
+ import { FieldPlugin } from "@webiny/db-dynamodb/plugins/definitions/FieldPlugin";
2
+ export declare class FileDynamoDbFieldPlugin extends FieldPlugin {
3
+ static readonly type: string;
4
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.FileDynamoDbFieldPlugin = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _FieldPlugin = require("@webiny/db-dynamodb/plugins/definitions/FieldPlugin");
13
+
14
+ class FileDynamoDbFieldPlugin extends _FieldPlugin.FieldPlugin {}
15
+
16
+ exports.FileDynamoDbFieldPlugin = FileDynamoDbFieldPlugin;
17
+ (0, _defineProperty2.default)(FileDynamoDbFieldPlugin, "type", "fileManager.dynamodb.field.file");
18
+ //# sourceMappingURL=FileDynamoDbFieldPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/plugins/FileDynamoDbFieldPlugin.ts"],"names":["FileDynamoDbFieldPlugin","FieldPlugin"],"mappings":";;;;;;;;;;;AAAA;;AAEO,MAAMA,uBAAN,SAAsCC,wBAAtC,CAAkD;;;8BAA5CD,uB,UAC6B,iC","sourcesContent":["import { FieldPlugin } from \"@webiny/db-dynamodb/plugins/definitions/FieldPlugin\";\n\nexport class FileDynamoDbFieldPlugin extends FieldPlugin {\n public static readonly type: string = \"fileManager.dynamodb.field.file\";\n}\n"],"file":"FileDynamoDbFieldPlugin.js"}