@webiny/db-dynamodb 0.0.0-mt-2 → 0.0.0-unstable.5e7233243f

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.
Files changed (97) hide show
  1. package/BatchProcess.d.ts +26 -10
  2. package/BatchProcess.js +7 -3
  3. package/BatchProcess.js.map +1 -0
  4. package/DynamoDbDriver.d.ts +19 -11
  5. package/DynamoDbDriver.js +2 -2
  6. package/DynamoDbDriver.js.map +1 -0
  7. package/QueryGenerator.d.ts +15 -13
  8. package/QueryGenerator.js +15 -12
  9. package/QueryGenerator.js.map +1 -0
  10. package/index.js.map +1 -0
  11. package/operators/comparison/beginsWith.js.map +1 -0
  12. package/operators/comparison/between.js.map +1 -0
  13. package/operators/comparison/eq.js.map +1 -0
  14. package/operators/comparison/gt.js.map +1 -0
  15. package/operators/comparison/gte.js.map +1 -0
  16. package/operators/comparison/lt.js.map +1 -0
  17. package/operators/comparison/lte.js.map +1 -0
  18. package/operators/index.js.map +1 -0
  19. package/operators/logical/and.js.map +1 -0
  20. package/operators/logical/or.js.map +1 -0
  21. package/package.json +16 -15
  22. package/plugins/definitions/AttributePlugin.d.ts +3 -3
  23. package/plugins/definitions/AttributePlugin.js.map +1 -0
  24. package/plugins/definitions/DateTimeTransformPlugin.d.ts +2 -2
  25. package/plugins/definitions/DateTimeTransformPlugin.js +6 -2
  26. package/plugins/definitions/DateTimeTransformPlugin.js.map +1 -0
  27. package/plugins/definitions/FieldPathPlugin.d.ts +3 -3
  28. package/plugins/definitions/FieldPathPlugin.js +2 -2
  29. package/plugins/definitions/FieldPathPlugin.js.map +1 -0
  30. package/plugins/definitions/FieldPlugin.d.ts +3 -3
  31. package/plugins/definitions/FieldPlugin.js.map +1 -0
  32. package/plugins/definitions/NumberTransformPlugin.d.ts +2 -2
  33. package/plugins/definitions/NumberTransformPlugin.js +2 -2
  34. package/plugins/definitions/NumberTransformPlugin.js.map +1 -0
  35. package/plugins/definitions/TimeTransformPlugin.d.ts +2 -2
  36. package/plugins/definitions/TimeTransformPlugin.js +2 -2
  37. package/plugins/definitions/TimeTransformPlugin.js.map +1 -0
  38. package/plugins/definitions/ValueFilterPlugin.d.ts +10 -10
  39. package/plugins/definitions/ValueFilterPlugin.js.map +1 -0
  40. package/plugins/definitions/ValueTransformPlugin.d.ts +8 -8
  41. package/plugins/definitions/ValueTransformPlugin.js +2 -2
  42. package/plugins/definitions/ValueTransformPlugin.js.map +1 -0
  43. package/plugins/definitions/assignFields.js.map +1 -0
  44. package/plugins/filters/andIn.js.map +1 -0
  45. package/plugins/filters/between.js.map +1 -0
  46. package/plugins/filters/contains.js.map +1 -0
  47. package/plugins/filters/eq.js +13 -0
  48. package/plugins/filters/eq.js.map +1 -0
  49. package/plugins/filters/fuzzy.js.map +1 -0
  50. package/plugins/filters/gt.js.map +1 -0
  51. package/plugins/filters/gte.js.map +1 -0
  52. package/plugins/filters/in.js.map +1 -0
  53. package/plugins/filters/index.js +3 -1
  54. package/plugins/filters/index.js.map +1 -0
  55. package/plugins/filters/lt.js.map +1 -0
  56. package/plugins/filters/lte.js.map +1 -0
  57. package/plugins/filters/startsWith.d.ts +3 -0
  58. package/plugins/filters/startsWith.js +33 -0
  59. package/plugins/filters/startsWith.js.map +1 -0
  60. package/plugins/index.js.map +1 -0
  61. package/statements/createKeyConditionExpressionArgs.d.ts +12 -9
  62. package/statements/createKeyConditionExpressionArgs.js +4 -0
  63. package/statements/createKeyConditionExpressionArgs.js.map +1 -0
  64. package/statements/processStatement.d.ts +3 -4
  65. package/statements/processStatement.js +7 -4
  66. package/statements/processStatement.js.map +1 -0
  67. package/types.d.ts +37 -8
  68. package/types.js.map +1 -0
  69. package/utils/attributes.d.ts +2 -2
  70. package/utils/attributes.js +2 -2
  71. package/utils/attributes.js.map +1 -0
  72. package/utils/batchRead.d.ts +1 -1
  73. package/utils/batchRead.js +56 -25
  74. package/utils/batchRead.js.map +1 -0
  75. package/utils/batchWrite.js.map +1 -0
  76. package/utils/cleanup.d.ts +2 -2
  77. package/utils/cleanup.js +8 -11
  78. package/utils/cleanup.js.map +1 -0
  79. package/utils/cursor.d.ts +2 -2
  80. package/utils/cursor.js.map +1 -0
  81. package/utils/filter.d.ts +2 -2
  82. package/utils/filter.js +6 -5
  83. package/utils/filter.js.map +1 -0
  84. package/utils/get.d.ts +2 -2
  85. package/utils/get.js.map +1 -0
  86. package/utils/listResponse.d.ts +1 -1
  87. package/utils/listResponse.js +9 -6
  88. package/utils/listResponse.js.map +1 -0
  89. package/utils/query.d.ts +2 -3
  90. package/utils/query.js +4 -8
  91. package/utils/query.js.map +1 -0
  92. package/utils/sort.d.ts +2 -2
  93. package/utils/sort.js +3 -5
  94. package/utils/sort.js.map +1 -0
  95. package/utils/table.js.map +1 -0
  96. package/utils/documentClient.d.ts +0 -8
  97. package/utils/documentClient.js +0 -33
@@ -0,0 +1 @@
1
+ {"version":3,"names":["MAX_BATCH_ITEMS","flatten","responses","entries","values","Object","items","push","batchReadAllChunk","params","table","records","result","batchGet","Responses","next","previous","nextResult","batchReadAll","maxChunk","length","WebinyError","chunkItemsList","lodashChunk","chunkItems","results"],"sources":["batchRead.ts"],"sourcesContent":["import { Table } from \"dynamodb-toolbox\";\nimport lodashChunk from \"lodash/chunk\";\nimport WebinyError from \"@webiny/error\";\n\ninterface Item {\n Table: Table;\n Key: any;\n}\ninterface Params {\n table: Table;\n items: Item[];\n}\n\nconst MAX_BATCH_ITEMS = 100;\n\nconst flatten = (responses: Record<string, any[]>): any[] => {\n const entries = [];\n const values = Object.values(responses);\n for (const items of values) {\n entries.push(...items);\n }\n return entries;\n};\n\ninterface BatchReadAllChunkParams {\n table: Table;\n items: Item[];\n}\nconst batchReadAllChunk = async <T = any>(params: BatchReadAllChunkParams): Promise<T[]> => {\n const { table, items } = params;\n const records: T[] = [];\n\n const result = await table.batchGet(items);\n if (!result || !result.Responses) {\n return records;\n }\n records.push(...flatten(result.Responses));\n if (!result.next || typeof result.next !== \"function\") {\n return records;\n }\n let previous = result;\n while (typeof previous.next === \"function\") {\n const nextResult = await previous.next();\n if (!nextResult) {\n return records;\n }\n records.push(...flatten(nextResult.Responses));\n previous = nextResult;\n }\n return records;\n};\n/**\n * This helper function is meant to be used to batch read from one table.\n * It will fetch all results, as there is a next() method call built in.\n */\nexport const batchReadAll = async <T = any>(\n params: Params,\n maxChunk = MAX_BATCH_ITEMS\n): Promise<T[]> => {\n if (params.items.length === 0) {\n return [];\n } else if (maxChunk > MAX_BATCH_ITEMS) {\n throw new WebinyError(\n `Cannot set to load more than ${MAX_BATCH_ITEMS} items from the DynamoDB at once.`,\n \"DYNAMODB_MAX_BATCH_GET_LIMIT_ERROR\",\n {\n maxChunk\n }\n );\n }\n\n const records: T[] = [];\n\n const chunkItemsList: Item[][] = lodashChunk(params.items, maxChunk);\n\n for (const chunkItems of chunkItemsList) {\n const results = await batchReadAllChunk<T>({\n table: params.table,\n items: chunkItems\n });\n\n records.push(...results);\n }\n\n return records;\n};\n"],"mappings":";;;;;;;;;AACA;;AACA;;AAWA,MAAMA,eAAe,GAAG,GAAxB;;AAEA,MAAMC,OAAO,GAAIC,SAAD,IAA6C;EACzD,MAAMC,OAAO,GAAG,EAAhB;EACA,MAAMC,MAAM,GAAGC,MAAM,CAACD,MAAP,CAAcF,SAAd,CAAf;;EACA,KAAK,MAAMI,KAAX,IAAoBF,MAApB,EAA4B;IACxBD,OAAO,CAACI,IAAR,CAAa,GAAGD,KAAhB;EACH;;EACD,OAAOH,OAAP;AACH,CAPD;;AAaA,MAAMK,iBAAiB,GAAG,MAAgBC,MAAhB,IAAkE;EACxF,MAAM;IAAEC,KAAF;IAASJ;EAAT,IAAmBG,MAAzB;EACA,MAAME,OAAY,GAAG,EAArB;EAEA,MAAMC,MAAM,GAAG,MAAMF,KAAK,CAACG,QAAN,CAAeP,KAAf,CAArB;;EACA,IAAI,CAACM,MAAD,IAAW,CAACA,MAAM,CAACE,SAAvB,EAAkC;IAC9B,OAAOH,OAAP;EACH;;EACDA,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,OAAOd,OAAP;AACH,CA9BM"}
@@ -0,0 +1 @@
1
+ {"version":3,"names":["batchWriteAll","params","maxChunk","items","length","chunkedItems","lodashChunk","table","batchWrite"],"sources":["batchWrite.ts"],"sourcesContent":["import { Table } from \"dynamodb-toolbox\";\nimport lodashChunk from \"lodash/chunk\";\nimport { DocumentClient } from \"aws-sdk/clients/dynamodb\";\n\ninterface Item {\n [key: string]: DocumentClient.WriteRequest;\n}\ninterface Params {\n table: Table;\n items: Item[];\n}\n\n/**\n * Method is meant for batch writing to a single table.\n * It expects already prepared items for the write.\n * It can either delete or put items\n * The method does not check items before actually sending them into the underlying library.\n */\nexport const batchWriteAll = async (params: Params, maxChunk = 25): Promise<void> => {\n if (params.items.length === 0) {\n return;\n }\n const chunkedItems: Item[][] = lodashChunk(params.items, maxChunk);\n for (const items of chunkedItems) {\n await params.table.batchWrite(items);\n }\n};\n"],"mappings":";;;;;;;;;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,aAAa,GAAG,OAAOC,MAAP,EAAuBC,QAAQ,GAAG,EAAlC,KAAwD;EACjF,IAAID,MAAM,CAACE,KAAP,CAAaC,MAAb,KAAwB,CAA5B,EAA+B;IAC3B;EACH;;EACD,MAAMC,YAAsB,GAAG,IAAAC,cAAA,EAAYL,MAAM,CAACE,KAAnB,EAA0BD,QAA1B,CAA/B;;EACA,KAAK,MAAMC,KAAX,IAAoBE,YAApB,EAAkC;IAC9B,MAAMJ,MAAM,CAACM,KAAP,CAAaC,UAAb,CAAwBL,KAAxB,CAAN;EACH;AACJ,CARM"}
@@ -1,3 +1,3 @@
1
1
  import { Entity } from "dynamodb-toolbox";
2
- export declare const cleanupItem: <T>(entity: Entity<any>, item?: T & Record<string, any>, removeAttributes?: string[]) => T;
3
- export declare const cleanupItems: <T>(entity: Entity<any>, items: (T & Record<string, any>)[], removeAttributes?: string[]) => T[];
2
+ export declare function cleanupItem<T>(entity: Entity<any>, item?: (T & Record<string, any>) | null, removeAttributes?: string[]): T | null;
3
+ export declare function cleanupItems<T>(entity: Entity<any>, items: (T & Record<string, any>)[], removeAttributes?: string[]): T[];
package/utils/cleanup.js CHANGED
@@ -5,13 +5,14 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.cleanupItems = exports.cleanupItem = void 0;
8
+ exports.cleanupItem = cleanupItem;
9
+ exports.cleanupItems = cleanupItems;
9
10
 
10
11
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
12
 
12
- 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; }
13
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
13
14
 
14
- 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; }
15
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15
16
 
16
17
  /**
17
18
  * The attributes defined by us or the dynamodb-toolbox library.
@@ -19,7 +20,7 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
19
20
  */
20
21
  const attributesToRemove = ["PK", "SK", "created", "_ct", "modified", "_mt", "entity", "_et", "GSI1_PK", "GSI1_SK", "TYPE"];
21
22
 
22
- const cleanupItem = (entity, item, removeAttributes = []) => {
23
+ function cleanupItem(entity, item, removeAttributes = []) {
23
24
  if (!item) {
24
25
  return null;
25
26
  }
@@ -42,12 +43,8 @@ const cleanupItem = (entity, item, removeAttributes = []) => {
42
43
  }
43
44
 
44
45
  return newItem;
45
- };
46
-
47
- exports.cleanupItem = cleanupItem;
46
+ }
48
47
 
49
- const cleanupItems = (entity, items, removeAttributes = []) => {
48
+ function cleanupItems(entity, items, removeAttributes = []) {
50
49
  return items.map(item => cleanupItem(entity, item, removeAttributes));
51
- };
52
-
53
- exports.cleanupItems = cleanupItems;
50
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["attributesToRemove","cleanupItem","entity","item","removeAttributes","newItem","targets","concat","attributes","schema","key","hasOwnProperty","includes","cleanupItems","items","map"],"sources":["cleanup.ts"],"sourcesContent":["import { Entity } from \"dynamodb-toolbox\";\n\n/**\n * The attributes defined by us or the dynamodb-toolbox library.\n * Add more attributes if necessary.\n */\nconst attributesToRemove = [\n \"PK\",\n \"SK\",\n \"created\",\n \"_ct\",\n \"modified\",\n \"_mt\",\n \"entity\",\n \"_et\",\n \"GSI1_PK\",\n \"GSI1_SK\",\n \"TYPE\"\n];\n\nexport function cleanupItem<T>(\n entity: Entity<any>,\n item?: (T & Record<string, any>) | null,\n removeAttributes: string[] = []\n): T | null {\n if (!item) {\n return null;\n }\n const newItem = {\n ...item\n };\n const targets = attributesToRemove.concat(removeAttributes);\n const attributes = entity.schema.attributes;\n for (const key in item) {\n if (item.hasOwnProperty(key) === false) {\n continue;\n }\n if (attributes[key] && targets.includes(key) === false) {\n continue;\n }\n delete newItem[key];\n }\n return newItem;\n}\n\nexport function cleanupItems<T>(\n entity: Entity<any>,\n items: (T & Record<string, any>)[],\n removeAttributes: string[] = []\n): T[] {\n return items.map(item => cleanupItem<T>(entity, item, removeAttributes) as T);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAEA;AACA;AACA;AACA;AACA,MAAMA,kBAAkB,GAAG,CACvB,IADuB,EAEvB,IAFuB,EAGvB,SAHuB,EAIvB,KAJuB,EAKvB,UALuB,EAMvB,KANuB,EAOvB,QAPuB,EAQvB,KARuB,EASvB,SATuB,EAUvB,SAVuB,EAWvB,MAXuB,CAA3B;;AAcO,SAASC,WAAT,CACHC,MADG,EAEHC,IAFG,EAGHC,gBAA0B,GAAG,EAH1B,EAIK;EACR,IAAI,CAACD,IAAL,EAAW;IACP,OAAO,IAAP;EACH;;EACD,MAAME,OAAO,qBACNF,IADM,CAAb;;EAGA,MAAMG,OAAO,GAAGN,kBAAkB,CAACO,MAAnB,CAA0BH,gBAA1B,CAAhB;EACA,MAAMI,UAAU,GAAGN,MAAM,CAACO,MAAP,CAAcD,UAAjC;;EACA,KAAK,MAAME,GAAX,IAAkBP,IAAlB,EAAwB;IACpB,IAAIA,IAAI,CAACQ,cAAL,CAAoBD,GAApB,MAA6B,KAAjC,EAAwC;MACpC;IACH;;IACD,IAAIF,UAAU,CAACE,GAAD,CAAV,IAAmBJ,OAAO,CAACM,QAAR,CAAiBF,GAAjB,MAA0B,KAAjD,EAAwD;MACpD;IACH;;IACD,OAAOL,OAAO,CAACK,GAAD,CAAd;EACH;;EACD,OAAOL,OAAP;AACH;;AAEM,SAASQ,YAAT,CACHX,MADG,EAEHY,KAFG,EAGHV,gBAA0B,GAAG,EAH1B,EAIA;EACH,OAAOU,KAAK,CAACC,GAAN,CAAUZ,IAAI,IAAIF,WAAW,CAAIC,MAAJ,EAAYC,IAAZ,EAAkBC,gBAAlB,CAA7B,CAAP;AACH"}
package/utils/cursor.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const encodeCursor: (cursor?: any) => string;
2
- export declare const decodeCursor: (cursor?: string) => any;
1
+ export declare const encodeCursor: (cursor?: any) => string | null;
2
+ export declare const decodeCursor: (cursor?: string | null) => string | null;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["encodeCursor","cursor","Buffer","from","JSON","stringify","toString","decodeCursor","parse"],"sources":["cursor.ts"],"sourcesContent":["export const encodeCursor = (cursor?: any): string | null => {\n if (!cursor) {\n return null;\n }\n\n return Buffer.from(JSON.stringify(cursor)).toString(\"base64\");\n};\n\nexport const decodeCursor = (cursor?: string | null): string | null => {\n if (!cursor) {\n return null;\n }\n\n return JSON.parse(Buffer.from(cursor, \"base64\").toString(\"ascii\"));\n};\n"],"mappings":";;;;;;;AAAO,MAAMA,YAAY,GAAIC,MAAD,IAAiC;EACzD,IAAI,CAACA,MAAL,EAAa;IACT,OAAO,IAAP;EACH;;EAED,OAAOC,MAAM,CAACC,IAAP,CAAYC,IAAI,CAACC,SAAL,CAAeJ,MAAf,CAAZ,EAAoCK,QAApC,CAA6C,QAA7C,CAAP;AACH,CANM;;;;AAQA,MAAMC,YAAY,GAAIN,MAAD,IAA2C;EACnE,IAAI,CAACA,MAAL,EAAa;IACT,OAAO,IAAP;EACH;;EAED,OAAOG,IAAI,CAACI,KAAL,CAAWN,MAAM,CAACC,IAAP,CAAYF,MAAZ,EAAoB,QAApB,EAA8BK,QAA9B,CAAuC,OAAvC,CAAX,CAAP;AACH,CANM"}
package/utils/filter.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PluginsContainer } from "@webiny/plugins";
2
2
  import { FieldPlugin } from "../plugins/definitions/FieldPlugin";
3
- export interface Params<T extends any = any> {
3
+ export interface Params<T = any> {
4
4
  plugins: PluginsContainer;
5
5
  items: T[];
6
6
  where: Record<string, any>;
@@ -9,4 +9,4 @@ export interface Params<T extends any = any> {
9
9
  */
10
10
  fields: FieldPlugin[];
11
11
  }
12
- export declare const filterItems: <T extends unknown = any>(params: Params<T>) => T[];
12
+ export declare function filterItems<T = any>(params: Params<T>): T[];
package/utils/filter.js CHANGED
@@ -5,7 +5,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.filterItems = void 0;
8
+ exports.filterItems = filterItems;
9
9
 
10
10
  var _dotProp = _interopRequireDefault(require("dot-prop"));
11
11
 
@@ -15,6 +15,9 @@ var _ValueFilterPlugin = require("../plugins/definitions/ValueFilterPlugin");
15
15
 
16
16
  const getMappedPlugins = params => {
17
17
  return params.plugins.byType(params.type).reduce((plugins, plugin) => {
18
+ /**
19
+ * We expect op to be a string, that is why we cast.
20
+ */
18
21
  const op = plugin[params.property];
19
22
  plugins[op] = plugin;
20
23
  return plugins;
@@ -196,7 +199,7 @@ const createFilterCallable = params => {
196
199
  };
197
200
  };
198
201
 
199
- const filterItems = params => {
202
+ function filterItems(params) {
200
203
  const filter = createFilterCallable(params);
201
204
  /**
202
205
  * No point in going through all the items when there are no filters to be applied.
@@ -207,6 +210,4 @@ const filterItems = params => {
207
210
  }
208
211
 
209
212
  return params.items.filter(filter);
210
- };
211
-
212
- exports.filterItems = filterItems;
213
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["getMappedPlugins","params","plugins","byType","type","reduce","plugin","op","property","extractWhereArgs","key","result","split","field","shift","rawOp","length","join","operation","negate","match","replace","findFilterPlugin","WebinyError","multiSearchFieldOperations","createFilters","where","fields","keys","Object","filterPlugins","ValueFilterPlugin","filters","compareValue","undefined","includes","data","transformValue","paths","map","fieldPlugin","find","getField","value","getPath","push","filterPlugin","path","transform","Array","isArray","v","createFilterCallable","item","filter","some","dotProp","get","matched","matches","filterItems","items"],"sources":["filter.ts"],"sourcesContent":["import dotProp from \"dot-prop\";\nimport WebinyError from \"@webiny/error\";\nimport { Plugin, PluginsContainer } from \"@webiny/plugins\";\nimport { ValueFilterPlugin } from \"~/plugins/definitions/ValueFilterPlugin\";\nimport { FieldPlugin } from \"~/plugins/definitions/FieldPlugin\";\nimport { DynamoDbContainsFilter } from \"~/types\";\n\ntype TransformValue = (value: any) => any;\n\nexport interface Params<T = any> {\n plugins: PluginsContainer;\n items: T[];\n where: Record<string, any>;\n /**\n * An array of fields that require some special operation.\n */\n fields: FieldPlugin[];\n}\n\ninterface MappedPluginParams<T extends Plugin = Plugin> {\n plugins: PluginsContainer;\n type: string;\n property: keyof T;\n}\n\ninterface Filter {\n compareValue: any;\n filterPlugin: ValueFilterPlugin;\n transformValue?: TransformValue;\n paths: string[];\n negate: boolean;\n}\n\nconst getMappedPlugins = <T extends Plugin>(params: MappedPluginParams<T>): Record<string, T> => {\n return params.plugins.byType<T>(params.type).reduce((plugins, plugin) => {\n /**\n * We expect op to be a string, that is why we cast.\n */\n const op = plugin[params.property] as unknown as string;\n plugins[op] = plugin;\n return plugins;\n }, {} as Record<string, T>);\n};\n\ninterface ExtractWhereArgsResult {\n field: string;\n operation: string;\n negate: boolean;\n}\nconst extractWhereArgs = (key: string): ExtractWhereArgsResult => {\n const result = key.split(\"_\");\n const field = result.shift() as string;\n const rawOp = result.length === 0 ? \"eq\" : result.join(\"_\");\n /**\n * When rawOp is not, it means it is equal negated so just return that.\n */\n if (rawOp === \"not\") {\n return {\n field,\n operation: \"eq\",\n negate: true\n };\n }\n const negate = rawOp.match(\"not_\") !== null;\n const operation = rawOp.replace(\"not_\", \"\");\n return {\n field,\n operation,\n negate\n };\n};\n\nconst findFilterPlugin = (\n plugins: Record<string, ValueFilterPlugin>,\n operation: string\n): ValueFilterPlugin => {\n if (plugins[operation]) {\n return plugins[operation];\n }\n throw new WebinyError(`Missing filter plugin definition.`, \"FILTER_PLUGIN_ERROR\", {\n operation\n });\n};\n\nconst multiSearchFieldOperations = [\"contains\", \"fuzzy\"];\n\nconst createFilters = (params: Omit<Params, \"items\">): Filter[] => {\n const { plugins, where, fields } = params;\n\n const keys = Object.keys(where);\n /**\n * Skip everything if there are no conditions to be applied.\n */\n if (keys.length === 0) {\n return [];\n }\n const filterPlugins = getMappedPlugins<ValueFilterPlugin>({\n plugins,\n type: ValueFilterPlugin.type,\n property: \"operation\"\n });\n\n return keys.reduce((filters, key) => {\n const compareValue = where[key];\n if (compareValue === undefined) {\n return filters;\n }\n /**\n * @see DynamoDbContainsFilter\n */\n if (multiSearchFieldOperations.includes(key) === true) {\n const data: DynamoDbContainsFilter = compareValue;\n let transformValue: TransformValue | undefined = undefined;\n const paths = data.fields.map(field => {\n const fieldPlugin = fields.find(plugin => plugin.getField() === field);\n if (fieldPlugin) {\n transformValue = (value: any) => {\n return fieldPlugin.transformValue(value);\n };\n return fieldPlugin.getPath();\n }\n return field;\n });\n filters.push({\n compareValue: data.value,\n filterPlugin: findFilterPlugin(filterPlugins, key),\n transformValue,\n paths,\n negate: false\n });\n return filters;\n }\n\n const { field, operation, negate } = extractWhereArgs(key);\n\n const filterPlugin = findFilterPlugin(filterPlugins, operation);\n\n const fieldPlugin = fields.find(plugin => plugin.getField() === field);\n let path: string = field;\n let transformValue: TransformValue | undefined = undefined;\n if (fieldPlugin) {\n transformValue = (value: any) => {\n return fieldPlugin.transformValue(value);\n };\n path = fieldPlugin.getPath();\n }\n\n filters.push({\n compareValue,\n filterPlugin,\n transformValue,\n paths: [path],\n negate\n });\n\n return filters;\n }, [] as Filter[]);\n};\n/**\n * Transforms the value with given transformer callable.\n */\nconst transform = (value: any, transformValue?: TransformValue): any => {\n if (!transformValue) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(v => transformValue(v));\n }\n return transformValue(value);\n};\n/**\n * Creates a filter callable that we can send to the .filter() method of the array.\n */\nconst createFilterCallable = (params: Omit<Params, \"items\">): ((item: any) => boolean) | null => {\n const filters = createFilters(params);\n /**\n * Just return null so there are no filters to be applied.\n * Later in the code we check for null so we do not loop through the items.\n */\n if (filters.length === 0) {\n return null;\n }\n\n return (item: any) => {\n for (const filter of filters) {\n const result = filter.paths.some(path => {\n const value = transform(dotProp.get(item, path), filter.transformValue);\n const compareValue = transform(filter.compareValue, filter.transformValue);\n const matched = filter.filterPlugin.matches({\n value,\n compareValue\n });\n\n return filter.negate ? !matched : matched;\n });\n if (result === false) {\n return false;\n }\n }\n return true;\n };\n};\n\nexport function filterItems<T = any>(params: Params<T>): T[] {\n const filter = createFilterCallable(params);\n /**\n * No point in going through all the items when there are no filters to be applied.\n */\n if (!filter) {\n return params.items;\n }\n return params.items.filter(filter);\n}\n"],"mappings":";;;;;;;;;AAAA;;AACA;;AAEA;;AA8BA,MAAMA,gBAAgB,GAAsBC,MAAnB,IAAwE;EAC7F,OAAOA,MAAM,CAACC,OAAP,CAAeC,MAAf,CAAyBF,MAAM,CAACG,IAAhC,EAAsCC,MAAtC,CAA6C,CAACH,OAAD,EAAUI,MAAV,KAAqB;IACrE;AACR;AACA;IACQ,MAAMC,EAAE,GAAGD,MAAM,CAACL,MAAM,CAACO,QAAR,CAAjB;IACAN,OAAO,CAACK,EAAD,CAAP,GAAcD,MAAd;IACA,OAAOJ,OAAP;EACH,CAPM,EAOJ,EAPI,CAAP;AAQH,CATD;;AAgBA,MAAMO,gBAAgB,GAAIC,GAAD,IAAyC;EAC9D,MAAMC,MAAM,GAAGD,GAAG,CAACE,KAAJ,CAAU,GAAV,CAAf;EACA,MAAMC,KAAK,GAAGF,MAAM,CAACG,KAAP,EAAd;EACA,MAAMC,KAAK,GAAGJ,MAAM,CAACK,MAAP,KAAkB,CAAlB,GAAsB,IAAtB,GAA6BL,MAAM,CAACM,IAAP,CAAY,GAAZ,CAA3C;EACA;AACJ;AACA;;EACI,IAAIF,KAAK,KAAK,KAAd,EAAqB;IACjB,OAAO;MACHF,KADG;MAEHK,SAAS,EAAE,IAFR;MAGHC,MAAM,EAAE;IAHL,CAAP;EAKH;;EACD,MAAMA,MAAM,GAAGJ,KAAK,CAACK,KAAN,CAAY,MAAZ,MAAwB,IAAvC;EACA,M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AM,KAAK,KAAf,EAAsB;QAClB,OAAO,KAAP;MACH;IACJ;;IACD,OAAO,IAAP;EACH,CAjBD;AAkBH,CA5BD;;AA8BO,SAASiD,WAAT,CAA8B3D,MAA9B,EAAsD;EACzD,MAAMqD,MAAM,GAAGF,oBAAoB,CAACnD,MAAD,CAAnC;EACA;AACJ;AACA;;EACI,IAAI,CAACqD,MAAL,EAAa;IACT,OAAOrD,MAAM,CAAC4D,KAAd;EACH;;EACD,OAAO5D,MAAM,CAAC4D,KAAP,CAAaP,MAAb,CAAoBA,MAApB,CAAP;AACH"}
package/utils/get.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Entity } from "dynamodb-toolbox";
2
- export interface Params {
2
+ export interface GetRecordParams {
3
3
  entity: Entity<any>;
4
4
  keys: {
5
5
  PK: string;
@@ -14,4 +14,4 @@ export interface Params {
14
14
  *
15
15
  * @throws
16
16
  */
17
- export declare const get: <T>(params: Params) => Promise<T>;
17
+ export declare const get: <T>(params: GetRecordParams) => Promise<T | null>;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["get","params","entity","keys","result","Item"],"sources":["get.ts"],"sourcesContent":["import { Entity } from \"dynamodb-toolbox\";\n\nexport interface GetRecordParams {\n entity: Entity<any>;\n keys: {\n PK: string;\n SK: string;\n };\n}\n\n/**\n * Gets a single record from the DynamoDB table.\n * Returns either record or null.\n *\n * Be aware to wrap in try/catch to avoid the error killing your app.\n *\n * @throws\n */\nexport const get = async <T>(params: GetRecordParams): Promise<T | null> => {\n const { entity, keys } = params;\n\n const result = await entity.get(keys);\n\n if (!result || !result.Item) {\n return null;\n }\n return result.Item;\n};\n"],"mappings":";;;;;;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,GAAG,GAAG,MAAUC,MAAV,IAAyD;EACxE,MAAM;IAAEC,MAAF;IAAUC;EAAV,IAAmBF,MAAzB;EAEA,MAAMG,MAAM,GAAG,MAAMF,MAAM,CAACF,GAAP,CAAWG,IAAX,CAArB;;EAEA,IAAI,CAACC,MAAD,IAAW,CAACA,MAAM,CAACC,IAAvB,EAA6B;IACzB,OAAO,IAAP;EACH;;EACD,OAAOD,MAAM,CAACC,IAAd;AACH,CATM"}
@@ -9,5 +9,5 @@ interface CreateListResponseParams<T> {
9
9
  totalCount: number;
10
10
  limit: number;
11
11
  }
12
- export declare const createListResponse: <T>(params: CreateListResponseParams<T>) => [T[], MetaResponse];
12
+ export declare function createListResponse<T>(params: CreateListResponseParams<T>): [T[], MetaResponse];
13
13
  export {};
@@ -3,18 +3,23 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.createListResponse = void 0;
6
+ exports.createListResponse = createListResponse;
7
7
 
8
8
  var _cursor = require("./cursor");
9
9
 
10
- const createListResponse = params => {
10
+ function createListResponse(params) {
11
11
  const {
12
12
  items: initialItems,
13
13
  after,
14
14
  totalCount,
15
15
  limit
16
16
  } = params;
17
- const start = (0, _cursor.decodeCursor)(after) || 0;
17
+ let start = Number((0, _cursor.decodeCursor)(after));
18
+
19
+ if (isNaN(start) === true) {
20
+ start = 0;
21
+ }
22
+
18
23
  const hasMoreItems = totalCount > start + limit;
19
24
  const end = limit > totalCount + start + limit ? undefined : start + limit;
20
25
  const items = end ? initialItems.slice(start, end) : initialItems;
@@ -25,6 +30,4 @@ const createListResponse = params => {
25
30
  cursor
26
31
  };
27
32
  return [items, meta];
28
- };
29
-
30
- exports.createListResponse = createListResponse;
33
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createListResponse","params","items","initialItems","after","totalCount","limit","start","Number","decodeCursor","isNaN","hasMoreItems","end","undefined","slice","cursor","length","encodeCursor","meta"],"sources":["listResponse.ts"],"sourcesContent":["import { decodeCursor, encodeCursor } from \"~/utils/cursor\";\n\ninterface MetaResponse {\n cursor: string | null;\n totalCount: number;\n hasMoreItems: boolean;\n}\n\ninterface CreateListResponseParams<T> {\n items: T[];\n after?: string | null;\n totalCount: number;\n limit: number;\n}\n\nexport function createListResponse<T>(params: CreateListResponseParams<T>): [T[], MetaResponse] {\n const { items: initialItems, after, totalCount, limit } = params;\n let start = Number(decodeCursor(after));\n if (isNaN(start) === true) {\n start = 0;\n }\n const hasMoreItems = totalCount > start + limit;\n const end = limit > totalCount + start + limit ? undefined : start + limit;\n const items = end ? initialItems.slice(start, end) : initialItems;\n\n const cursor = items.length > 0 ? encodeCursor(start + limit) : null;\n\n const meta = {\n hasMoreItems,\n totalCount,\n cursor\n };\n\n return [items, meta];\n}\n"],"mappings":";;;;;;;AAAA;;AAeO,SAASA,kBAAT,CAA+BC,MAA/B,EAAyF;EAC5F,MAAM;IAAEC,KAAK,EAAEC,YAAT;IAAuBC,KAAvB;IAA8BC,UAA9B;IAA0CC;EAA1C,IAAoDL,MAA1D;EACA,IAAIM,KAAK,GAAGC,MAAM,CAAC,IAAAC,oBAAA,EAAaL,KAAb,CAAD,CAAlB;;EACA,IAAIM,KAAK,CAACH,KAAD,CAAL,KAAiB,IAArB,EAA2B;IACvBA,KAAK,GAAG,CAAR;EACH;;EACD,MAAMI,YAAY,GAAGN,UAAU,GAAGE,KAAK,GAAGD,KAA1C;EACA,MAAMM,GAAG,GAAGN,KAAK,GAAGD,UAAU,GAAGE,KAAb,GAAqBD,KAA7B,GAAqCO,SAArC,GAAiDN,KAAK,GAAGD,KAArE;EACA,MAAMJ,KAAK,GAAGU,GAAG,GAAGT,YAAY,CAACW,KAAb,CAAmBP,KAAnB,EAA0BK,GAA1B,CAAH,GAAoCT,YAArD;EAEA,MAAMY,MAAM,GAAGb,KAAK,CAACc,MAAN,GAAe,CAAf,GAAmB,IAAAC,oBAAA,EAAaV,KAAK,GAAGD,KAArB,CAAnB,GAAiD,IAAhE;EAEA,MAAMY,IAAI,GAAG;IACTP,YADS;IAETN,UAFS;IAGTU;EAHS,CAAb;EAMA,OAAO,CAACb,KAAD,EAAQgB,IAAR,CAAP;AACH"}
package/utils/query.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface QueryResult<T> {
15
15
  result: any | null;
16
16
  items: T[];
17
17
  }
18
- declare type DbItem<T> = T & {
18
+ export declare type DbItem<T> = T & {
19
19
  PK: string;
20
20
  SK: string;
21
21
  TYPE: string;
@@ -25,9 +25,8 @@ declare type DbItem<T> = T & {
25
25
  /**
26
26
  * Will run the query to fetch the first possible item from the database.
27
27
  */
28
- export declare const queryOne: <T>(params: QueryOneParams) => Promise<DbItem<T>>;
28
+ export declare const queryOne: <T>(params: QueryOneParams) => Promise<DbItem<T> | null>;
29
29
  /**
30
30
  * Will run the query to fetch the results no matter how much iterations it needs to go through.
31
31
  */
32
32
  export declare const queryAll: <T>(params: QueryAllParams) => Promise<DbItem<T>[]>;
33
- export {};
package/utils/query.js CHANGED
@@ -11,9 +11,9 @@ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/de
11
11
 
12
12
  var _error = _interopRequireDefault(require("@webiny/error"));
13
13
 
14
- 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; }
14
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15
15
 
16
- 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; }
16
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
17
 
18
18
  /**
19
19
  * Will run query only once. Pass the previous to run the query again to fetch new data.
@@ -90,12 +90,8 @@ const queryOne = async params => {
90
90
  limit: 1
91
91
  })
92
92
  }));
93
-
94
- if (items.length === 0) {
95
- return null;
96
- }
97
-
98
- return items.shift();
93
+ const item = items.shift();
94
+ return item ? item : null;
99
95
  };
100
96
  /**
101
97
  * Will run the query to fetch the results no matter how much iterations it needs to go through.
@@ -0,0 +1 @@
1
+ {"version":3,"names":["query","params","entity","previous","partitionKey","options","result","next","items","Items","Array","isArray","WebinyError","queryOne","limit","item","shift","queryAll","results","previousResult","undefined","push"],"sources":["query.ts"],"sourcesContent":["import { queryOptions as DynamoDBToolboxQueryOptions } from \"dynamodb-toolbox/dist/classes/Table\";\nimport WebinyError from \"@webiny/error\";\nimport { Entity } from \"dynamodb-toolbox\";\n\nexport interface QueryAllParams {\n entity: Entity<any>;\n partitionKey: string;\n options?: DynamoDBToolboxQueryOptions;\n}\n\nexport interface QueryOneParams extends QueryAllParams {\n options?: Omit<DynamoDBToolboxQueryOptions, \"limit\">;\n}\n\nexport interface QueryParams extends QueryAllParams {\n previous?: any;\n}\n\nexport interface QueryResult<T> {\n result: any | null;\n items: T[];\n}\n\nexport type DbItem<T> = T & {\n PK: string;\n SK: string;\n TYPE: string;\n GSI1_PK?: string;\n GSI1_SK?: string;\n};\n\n/**\n * Will run query only once. Pass the previous to run the query again to fetch new data.\n * It returns the result and the items it found.\n * Result is required to fetch the items that were not fetched in the previous run.\n */\nconst query = async <T>(params: QueryParams): Promise<QueryResult<T>> => {\n const { entity, previous, partitionKey, options } = params;\n let result;\n /**\n * In case there is no previous result we must make a new query.\n * This is the first query on the given partition key.\n */\n if (!previous) {\n result = await entity.query(partitionKey, options);\n } else if (typeof previous.next === \"function\") {\n /**\n * In case we have a previous result and it has a next method, we run it.\n * In case result of the next method is false, it means it has nothing else to read\n * and we return a null to keep the query from repeating.\n */\n result = await previous.next();\n if (result === false) {\n return {\n result: null,\n items: []\n };\n }\n } else {\n /**\n * This could probably never happen but keep it here just in case to break the query loop.\n * Basically, either previous does not exist or it exists and it does not have the next method\n * and at that point a result returned will be null and loop should not start again.\n */\n return {\n result: null,\n items: []\n };\n }\n /**\n * We expect the result to contain an Items array and if not, something went wrong, very wrong.\n */\n if (!result || !result.Items || !Array.isArray(result.Items)) {\n throw new WebinyError(\n \"Error when querying for content entries - no result.\",\n \"QUERY_ERROR\",\n {\n partitionKey,\n options\n }\n );\n }\n return {\n result,\n items: result.Items\n };\n};\n/**\n * Will run the query to fetch the first possible item from the database.\n */\nexport const queryOne = async <T>(params: QueryOneParams): Promise<DbItem<T> | null> => {\n const { items } = await query<DbItem<T>>({\n ...params,\n options: {\n ...(params.options || {}),\n limit: 1\n }\n });\n const item = items.shift();\n return item ? item : null;\n};\n/**\n * Will run the query to fetch the results no matter how much iterations it needs to go through.\n */\nexport const queryAll = async <T>(params: QueryAllParams): Promise<DbItem<T>[]> => {\n const items: DbItem<T>[] = [];\n let results: QueryResult<DbItem<T>>;\n let previousResult: any = undefined;\n while ((results = await query({ ...params, previous: previousResult }))) {\n items.push(...results.items);\n if (!results.result) {\n return items;\n }\n previousResult = results.result;\n }\n return items;\n};\n"],"mappings":";;;;;;;;;;;AACA;;;;;;AA8BA;AACA;AACA;AACA;AACA;AACA,MAAMA,KAAK,GAAG,MAAUC,MAAV,IAA2D;EACrE,MAAM;IAAEC,MAAF;IAAUC,QAAV;IAAoBC,YAApB;IAAkCC;EAAlC,IAA8CJ,MAApD;EACA,IAAIK,MAAJ;EACA;AACJ;A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GAAG,EAA3B;EACA,IAAIU,OAAJ;EACA,IAAIC,cAAmB,GAAGC,SAA1B;;EACA,OAAQF,OAAO,GAAG,MAAMlB,KAAK,iCAAMC,MAAN;IAAcE,QAAQ,EAAEgB;EAAxB,GAA7B,EAAyE;IACrEX,KAAK,CAACa,IAAN,CAAW,GAAGH,OAAO,CAACV,KAAtB;;IACA,IAAI,CAACU,OAAO,CAACZ,MAAb,EAAqB;MACjB,OAAOE,KAAP;IACH;;IACDW,cAAc,GAAGD,OAAO,CAACZ,MAAzB;EACH;;EACD,OAAOE,KAAP;AACH,CAZM"}
package/utils/sort.d.ts CHANGED
@@ -7,11 +7,11 @@ interface Params<T> {
7
7
  /**
8
8
  * Sort options. For example: ["id_ASC"]
9
9
  */
10
- sort: string[];
10
+ sort?: string[];
11
11
  /**
12
12
  * Fields we can sort by.
13
13
  */
14
14
  fields?: FieldPlugin[];
15
15
  }
16
- export declare const sortItems: <T extends unknown = any>(params: Params<T>) => T[];
16
+ export declare function sortItems<T = any>(params: Params<T>): T[];
17
17
  export {};
package/utils/sort.js CHANGED
@@ -5,7 +5,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.sortItems = void 0;
8
+ exports.sortItems = sortItems;
9
9
 
10
10
  var _orderBy = _interopRequireDefault(require("lodash/orderBy"));
11
11
 
@@ -46,7 +46,7 @@ const extractSort = (sortBy, fields) => {
46
46
  };
47
47
  };
48
48
 
49
- const sortItems = params => {
49
+ function sortItems(params) {
50
50
  const {
51
51
  items,
52
52
  sort: initialSort = [],
@@ -88,6 +88,4 @@ const sortItems = params => {
88
88
  }
89
89
 
90
90
  return (0, _orderBy.default)(items, info.sorters, info.orders);
91
- };
92
-
93
- exports.sortItems = sortItems;
91
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["extractSort","sortBy","fields","result","split","length","WebinyError","field","order","fieldPlugin","find","f","getField","isSortable","reverse","toUpperCase","sortItems","params","items","sort","initialSort","Array","isArray","info","sorters","orders","path","getPath","push","lodashOrderBy"],"sources":["sort.ts"],"sourcesContent":["import lodashOrderBy from \"lodash/orderBy\";\nimport WebinyError from \"@webiny/error\";\nimport { FieldPlugin } from \"~/plugins/definitions/FieldPlugin\";\n\ninterface Info {\n sorters: string[];\n orders: (boolean | \"asc\" | \"desc\")[];\n}\n\ninterface Response {\n reverse: boolean;\n field: string;\n}\n\nconst extractSort = (sortBy: string, fields: FieldPlugin[]): Response => {\n const result = sortBy.split(\"_\");\n if (result.length !== 2) {\n throw new WebinyError(\n \"Problem in determining the sorting for the entry items.\",\n \"SORT_ERROR\",\n {\n sortBy\n }\n );\n }\n const [field, order] = result;\n\n if (!field) {\n throw new WebinyError(\"Sorting field does not exist.\", \"SORTING_FIELD_ERROR\", {\n field,\n order,\n fields\n });\n }\n const fieldPlugin = fields.find(f => f.getField() === field);\n const isSortable = fieldPlugin ? fieldPlugin.isSortable() : true;\n if (isSortable === false) {\n throw new WebinyError(`Cannot sort by given field: \"${field}\".`, \"UNSUPPORTED_SORT_ERROR\", {\n fields,\n field\n });\n }\n\n return {\n field,\n reverse: order.toUpperCase() === \"DESC\"\n };\n};\n\ninterface Params<T> {\n /**\n * The items we are sorting.\n */\n items: T[];\n /**\n * Sort options. For example: [\"id_ASC\"]\n */\n sort?: string[];\n /**\n * Fields we can sort by.\n */\n fields?: FieldPlugin[];\n}\n\nexport function sortItems<T = any>(params: Params<T>): T[] {\n const { items, sort: initialSort = [], fields = [] } = params;\n /**\n * Skip sorting if nothing was passed to sort by or nothing to sort.\n */\n if (items.length <= 1 || Array.isArray(initialSort) === false || initialSort.length === 0) {\n return items;\n }\n\n const info: Info = {\n sorters: [],\n orders: []\n };\n\n for (const sort of initialSort) {\n /**\n * Possibly empty array item was passed.\n */\n if (!sort) {\n continue;\n }\n const { field, reverse } = extractSort(sort, fields);\n const fieldPlugin = fields.find(f => f.getField() === field);\n const path = fieldPlugin ? fieldPlugin.getPath() : field;\n\n info.sorters.push(path);\n info.orders.push(reverse === true ? \"desc\" : \"asc\");\n }\n\n if (info.sorters.length === 0) {\n return items;\n }\n\n return lodashOrderBy(items, info.sorters, info.orders);\n}\n"],"mappings":";;;;;;;;;AAAA;;AACA;;AAaA,MAAMA,WAAW,GAAG,CAACC,MAAD,EAAiBC,MAAjB,KAAqD;EACrE,MAAMC,MAAM,GAAGF,MAAM,CAACG,KAAP,CAAa,GAAb,CAAf;;EACA,IAAID,MAAM,CAACE,MAAP,KAAkB,CAAtB,EAAyB;IACrB,MAAM,IAAIC,cAAJ,CACF,yDADE,EAEF,YAFE,EAGF;MACIL;IADJ,CAHE,CAAN;EAOH;;EACD,MAAM,CAACM,KAAD,EAAQC,KAAR,IAAiBL,MAAvB;;EAEA,IAAI,CAACI,KAAL,EAAY;IACR,MAAM,IAAID,cAAJ,CAAgB,+BAAhB,EAAiD,qBAAjD,EAAwE;MAC1EC,KAD0E;MAE1EC,KAF0E;MAG1EN;IAH0E,CAAxE,CAAN;EAKH;;EACD,MAAMO,WAAW,GAAGP,MAAM,CAACQ,IAAP,CAAYC,CAAC,IAAIA,CAAC,CAACC,QAAF,OAAiBL,KAAlC,CAApB;EACA,MAAMM,UAAU,GAAGJ,WAAW,GAAGA,WAAW,CAACI,UAAZ,EAAH,GAA8B,IAA5D;;EACA,IAAIA,UAAU,KAAK,KAAnB,EAA0B;IACtB,MAAM,IAAIP,cAAJ,CAAiB,gCAA+BC,KAAM,IAAtD,EAA2D,wBAA3D,EAAqF;MACvFL,MADuF;MAEvFK;IAFuF,CAArF,CAAN;EAIH;;EAED,OAAO;IACHA,KADG;IAEHO,OAAO,EAAEN,KAAK,CAACO,WAAN,OAAwB;EAF9B,CAAP;AAIH,CAjCD;;AAkDO,SAASC,SAAT,CAA4BC,MAA5B,EAAoD;EACvD,MAAM;IAAEC,KAAF;IAASC,IAAI,EAAEC,WAAW,GAAG,EAA7B;IAAiClB,MAAM,GAAG;EAA1C,IAAiDe,MAAvD;EACA;AACJ;AACA;;EACI,IAAIC,KAAK,CAACb,MAAN,IAAgB,CAAhB,IAAqBgB,KAAK,CAACC,OAAN,CAAcF,WAAd,MAA+B,KAApD,IAA6DA,WAAW,CAACf,MAAZ,KAAuB,CAAxF,EAA2F;IACvF,OAAOa,KAAP;EACH;;EAED,MAAMK,IAAU,GAAG;IACfC,OAAO,EAAE,EADM;IAEfC,MAAM,EAAE;EAFO,CAAnB;;EAKA,KAAK,MAAMN,IAAX,IAAmBC,WAAnB,EAAgC;IAC5B;AACR;AACA;IACQ,IAAI,CAACD,IAAL,EAAW;MACP;IACH;;IACD,MAAM;MAAEZ,KAAF;MAASO;IAAT,IAAqBd,WAAW,CAACmB,IAAD,EAAOjB,MAAP,CAAtC;IACA,MAAMO,WAAW,GAAGP,MAAM,CAACQ,IAAP,CAAYC,CAAC,IAAIA,CAAC,CAACC,QAAF,OAAiBL,KAAlC,CAApB;IACA,MAAMmB,IAAI,GAAGjB,WAAW,GAAGA,WAAW,CAACkB,OAAZ,EAAH,GAA2BpB,KAAnD;IAEAgB,IAAI,CAACC,OAAL,CAAaI,IAAb,CAAkBF,IAAlB;IACAH,IAAI,CAACE,MAAL,CAAYG,IAAZ,CAAiBd,OAAO,KAAK,IAAZ,GAAmB,MAAnB,GAA4B,KAA7C;EACH;;EAED,IAAIS,IAAI,CAACC,OAAL,CAAanB,MAAb,KAAwB,CAA5B,EAA+B;IAC3B,OAAOa,KAAP;EACH;;EAED,OAAO,IAAAW,gBAAA,EAAcX,KAAd,EAAqBK,IAAI,CAACC,OAA1B,EAAmCD,IAAI,CAACE,MAAxC,CAAP;AACH"}
@@ -0,0 +1 @@
1
+ {"version":3,"names":["getTable","context","db","WebinyError","table"],"sources":["table.ts"],"sourcesContent":["import WebinyError from \"@webiny/error\";\nimport { DbContext } from \"@webiny/handler-db/types\";\n\n/**\n * Will be removed in favor of passing the table name directly to the storage operations.\n *\n * @deprecated\n */\nexport const getTable = <T extends DbContext>(context: T): string => {\n if (!context.db) {\n throw new WebinyError(\"Missing db on context.\", \"DB_ERROR\");\n } else if (!context.db.table) {\n throw new WebinyError(\"Missing table on context.db.\", \"TABLE_ERROR\");\n }\n return context.db.table;\n};\n"],"mappings":";;;;;;;;;AAAA;;AAGA;AACA;AACA;AACA;AACA;AACO,MAAMA,QAAQ,GAAyBC,OAAtB,IAA6C;EACjE,IAAI,CAACA,OAAO,CAACC,EAAb,EAAiB;IACb,MAAM,IAAIC,cAAJ,CAAgB,wBAAhB,EAA0C,UAA1C,CAAN;EACH,CAFD,MAEO,IAAI,CAACF,OAAO,CAACC,EAAR,CAAWE,KAAhB,EAAuB;IAC1B,MAAM,IAAID,cAAJ,CAAgB,8BAAhB,EAAgD,aAAhD,CAAN;EACH;;EACD,OAAOF,OAAO,CAACC,EAAR,CAAWE,KAAlB;AACH,CAPM"}
@@ -1,8 +0,0 @@
1
- import { DocumentClient } from "aws-sdk/clients/dynamodb";
2
- import { DbContext } from "@webiny/handler-db/types";
3
- /**
4
- * Will be removed in favor of directly passing the documentClient to the storage operations.
5
- *
6
- * @deprecated
7
- */
8
- export declare const getDocumentClient: <T extends DbContext>(context: T) => DocumentClient;
@@ -1,33 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.getDocumentClient = void 0;
9
-
10
- var _error = _interopRequireDefault(require("@webiny/error"));
11
-
12
- /**
13
- * Will be removed in favor of directly passing the documentClient to the storage operations.
14
- *
15
- * @deprecated
16
- */
17
- const getDocumentClient = context => {
18
- if (!context.db) {
19
- throw new _error.default("Missing db on context.", "DB_ERROR");
20
- } else if (!context.db.driver) {
21
- throw new _error.default(`Missing driver on the context.db property.`, "DRIVER_ERROR");
22
- }
23
-
24
- const driver = context.db.driver;
25
-
26
- if (!driver.documentClient) {
27
- throw new _error.default(`Missing documentClient on the context.db.driver property.`, "DOCUMENT_CLIENT_ERROR");
28
- }
29
-
30
- return driver.documentClient;
31
- };
32
-
33
- exports.getDocumentClient = getDocumentClient;