@webiny/db-dynamodb 0.0.0-mt-1

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 (103) hide show
  1. package/BatchProcess.d.ts +31 -0
  2. package/BatchProcess.js +196 -0
  3. package/DynamoDbDriver.d.ts +27 -0
  4. package/DynamoDbDriver.js +272 -0
  5. package/LICENSE +21 -0
  6. package/QueryGenerator.d.ts +19 -0
  7. package/QueryGenerator.js +79 -0
  8. package/README.md +67 -0
  9. package/index.d.ts +2 -0
  10. package/index.js +15 -0
  11. package/operators/comparison/beginsWith.d.ts +3 -0
  12. package/operators/comparison/beginsWith.js +24 -0
  13. package/operators/comparison/between.d.ts +3 -0
  14. package/operators/comparison/between.js +30 -0
  15. package/operators/comparison/eq.d.ts +3 -0
  16. package/operators/comparison/eq.js +34 -0
  17. package/operators/comparison/gt.d.ts +3 -0
  18. package/operators/comparison/gt.js +24 -0
  19. package/operators/comparison/gte.d.ts +3 -0
  20. package/operators/comparison/gte.js +24 -0
  21. package/operators/comparison/lt.d.ts +3 -0
  22. package/operators/comparison/lt.js +24 -0
  23. package/operators/comparison/lte.d.ts +3 -0
  24. package/operators/comparison/lte.js +24 -0
  25. package/operators/index.d.ts +12 -0
  26. package/operators/index.js +39 -0
  27. package/operators/logical/and.d.ts +3 -0
  28. package/operators/logical/and.js +63 -0
  29. package/operators/logical/or.d.ts +3 -0
  30. package/operators/logical/or.js +63 -0
  31. package/package.json +45 -0
  32. package/plugins/definitions/AttributePlugin.d.ts +20 -0
  33. package/plugins/definitions/AttributePlugin.js +61 -0
  34. package/plugins/definitions/DateTimeTransformPlugin.d.ts +4 -0
  35. package/plugins/definitions/DateTimeTransformPlugin.js +54 -0
  36. package/plugins/definitions/FieldPathPlugin.d.ts +22 -0
  37. package/plugins/definitions/FieldPathPlugin.js +48 -0
  38. package/plugins/definitions/FieldPlugin.d.ts +34 -0
  39. package/plugins/definitions/FieldPlugin.js +73 -0
  40. package/plugins/definitions/NumberTransformPlugin.d.ts +4 -0
  41. package/plugins/definitions/NumberTransformPlugin.js +49 -0
  42. package/plugins/definitions/TimeTransformPlugin.d.ts +4 -0
  43. package/plugins/definitions/TimeTransformPlugin.js +65 -0
  44. package/plugins/definitions/ValueFilterPlugin.d.ts +20 -0
  45. package/plugins/definitions/ValueFilterPlugin.js +49 -0
  46. package/plugins/definitions/ValueTransformPlugin.d.ts +22 -0
  47. package/plugins/definitions/ValueTransformPlugin.js +52 -0
  48. package/plugins/definitions/assignFields.d.ts +1 -0
  49. package/plugins/definitions/assignFields.js +37 -0
  50. package/plugins/filters/andIn.d.ts +3 -0
  51. package/plugins/filters/andIn.js +35 -0
  52. package/plugins/filters/between.d.ts +3 -0
  53. package/plugins/filters/between.js +36 -0
  54. package/plugins/filters/contains.d.ts +3 -0
  55. package/plugins/filters/contains.js +32 -0
  56. package/plugins/filters/eq.d.ts +3 -0
  57. package/plugins/filters/eq.js +20 -0
  58. package/plugins/filters/fuzzy.d.ts +3 -0
  59. package/plugins/filters/fuzzy.js +30 -0
  60. package/plugins/filters/gt.d.ts +3 -0
  61. package/plugins/filters/gt.js +20 -0
  62. package/plugins/filters/gte.d.ts +3 -0
  63. package/plugins/filters/gte.js +20 -0
  64. package/plugins/filters/in.d.ts +3 -0
  65. package/plugins/filters/in.js +35 -0
  66. package/plugins/filters/index.d.ts +2 -0
  67. package/plugins/filters/index.js +32 -0
  68. package/plugins/filters/lt.d.ts +3 -0
  69. package/plugins/filters/lt.js +20 -0
  70. package/plugins/filters/lte.d.ts +3 -0
  71. package/plugins/filters/lte.js +20 -0
  72. package/plugins/index.d.ts +2 -0
  73. package/plugins/index.js +19 -0
  74. package/statements/createKeyConditionExpressionArgs.d.ts +12 -0
  75. package/statements/createKeyConditionExpressionArgs.js +48 -0
  76. package/statements/processStatement.d.ts +4 -0
  77. package/statements/processStatement.js +39 -0
  78. package/types.d.ts +29 -0
  79. package/types.js +5 -0
  80. package/utils/attributes.d.ts +10 -0
  81. package/utils/attributes.js +35 -0
  82. package/utils/batchRead.d.ts +15 -0
  83. package/utils/batchRead.js +58 -0
  84. package/utils/batchWrite.d.ts +17 -0
  85. package/utils/batchWrite.js +30 -0
  86. package/utils/cleanup.d.ts +3 -0
  87. package/utils/cleanup.js +53 -0
  88. package/utils/cursor.d.ts +2 -0
  89. package/utils/cursor.js +26 -0
  90. package/utils/documentClient.d.ts +8 -0
  91. package/utils/documentClient.js +33 -0
  92. package/utils/filter.d.ts +12 -0
  93. package/utils/filter.js +212 -0
  94. package/utils/get.d.ts +17 -0
  95. package/utils/get.js +30 -0
  96. package/utils/listResponse.d.ts +13 -0
  97. package/utils/listResponse.js +30 -0
  98. package/utils/query.d.ts +33 -0
  99. package/utils/query.js +127 -0
  100. package/utils/sort.d.ts +17 -0
  101. package/utils/sort.js +93 -0
  102. package/utils/table.d.ts +7 -0
  103. package/utils/table.js +27 -0
@@ -0,0 +1,8 @@
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;
@@ -0,0 +1,33 @@
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;
@@ -0,0 +1,12 @@
1
+ import { PluginsContainer } from "@webiny/plugins";
2
+ import { FieldPlugin } from "../plugins/definitions/FieldPlugin";
3
+ export interface Params<T extends any = any> {
4
+ plugins: PluginsContainer;
5
+ items: T[];
6
+ where: Record<string, any>;
7
+ /**
8
+ * An array of fields that require some special operation.
9
+ */
10
+ fields: FieldPlugin[];
11
+ }
12
+ export declare const filterItems: <T extends unknown = any>(params: Params<T>) => T[];
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.filterItems = void 0;
9
+
10
+ var _dotProp = _interopRequireDefault(require("dot-prop"));
11
+
12
+ var _error = _interopRequireDefault(require("@webiny/error"));
13
+
14
+ var _ValueFilterPlugin = require("../plugins/definitions/ValueFilterPlugin");
15
+
16
+ const getMappedPlugins = params => {
17
+ return params.plugins.byType(params.type).reduce((plugins, plugin) => {
18
+ const op = plugin[params.property];
19
+ plugins[op] = plugin;
20
+ return plugins;
21
+ }, {});
22
+ };
23
+
24
+ const extractWhereArgs = key => {
25
+ const result = key.split("_");
26
+ const field = result.shift();
27
+ const rawOp = result.length === 0 ? "eq" : result.join("_");
28
+ /**
29
+ * When rawOp is not, it means it is equal negated so just return that.
30
+ */
31
+
32
+ if (rawOp === "not") {
33
+ return {
34
+ field,
35
+ operation: "eq",
36
+ negate: true
37
+ };
38
+ }
39
+
40
+ const negate = rawOp.match("not_") !== null;
41
+ const operation = rawOp.replace("not_", "");
42
+ return {
43
+ field,
44
+ operation,
45
+ negate
46
+ };
47
+ };
48
+
49
+ const findFilterPlugin = (plugins, operation) => {
50
+ if (plugins[operation]) {
51
+ return plugins[operation];
52
+ }
53
+
54
+ throw new _error.default(`Missing filter plugin definition.`, "FILTER_PLUGIN_ERROR", {
55
+ operation
56
+ });
57
+ };
58
+
59
+ const multiSearchFieldOperations = ["contains", "fuzzy"];
60
+
61
+ const createFilters = params => {
62
+ const {
63
+ plugins,
64
+ where,
65
+ fields
66
+ } = params;
67
+ const keys = Object.keys(where);
68
+ /**
69
+ * Skip everything if there are no conditions to be applied.
70
+ */
71
+
72
+ if (keys.length === 0) {
73
+ return [];
74
+ }
75
+
76
+ const filterPlugins = getMappedPlugins({
77
+ plugins,
78
+ type: _ValueFilterPlugin.ValueFilterPlugin.type,
79
+ property: "operation"
80
+ });
81
+ return keys.reduce((filters, key) => {
82
+ const compareValue = where[key];
83
+
84
+ if (compareValue === undefined) {
85
+ return filters;
86
+ }
87
+ /**
88
+ * @see DynamoDbContainsFilter
89
+ */
90
+
91
+
92
+ if (multiSearchFieldOperations.includes(key) === true) {
93
+ const data = compareValue;
94
+ let transformValue = undefined;
95
+ const paths = data.fields.map(field => {
96
+ const fieldPlugin = fields.find(plugin => plugin.getField() === field);
97
+
98
+ if (fieldPlugin) {
99
+ transformValue = value => {
100
+ return fieldPlugin.transformValue(value);
101
+ };
102
+
103
+ return fieldPlugin.getPath();
104
+ }
105
+
106
+ return field;
107
+ });
108
+ filters.push({
109
+ compareValue: data.value,
110
+ filterPlugin: findFilterPlugin(filterPlugins, key),
111
+ transformValue,
112
+ paths,
113
+ negate: false
114
+ });
115
+ return filters;
116
+ }
117
+
118
+ const {
119
+ field,
120
+ operation,
121
+ negate
122
+ } = extractWhereArgs(key);
123
+ const filterPlugin = findFilterPlugin(filterPlugins, operation);
124
+ const fieldPlugin = fields.find(plugin => plugin.getField() === field);
125
+ let path = field;
126
+ let transformValue = undefined;
127
+
128
+ if (fieldPlugin) {
129
+ transformValue = value => {
130
+ return fieldPlugin.transformValue(value);
131
+ };
132
+
133
+ path = fieldPlugin.getPath();
134
+ }
135
+
136
+ filters.push({
137
+ compareValue,
138
+ filterPlugin,
139
+ transformValue,
140
+ paths: [path],
141
+ negate
142
+ });
143
+ return filters;
144
+ }, []);
145
+ };
146
+ /**
147
+ * Transforms the value with given transformer callable.
148
+ */
149
+
150
+
151
+ const transform = (value, transformValue) => {
152
+ if (!transformValue) {
153
+ return value;
154
+ }
155
+
156
+ if (Array.isArray(value)) {
157
+ return value.map(v => transformValue(v));
158
+ }
159
+
160
+ return transformValue(value);
161
+ };
162
+ /**
163
+ * Creates a filter callable that we can send to the .filter() method of the array.
164
+ */
165
+
166
+
167
+ const createFilterCallable = params => {
168
+ const filters = createFilters(params);
169
+ /**
170
+ * Just return null so there are no filters to be applied.
171
+ * Later in the code we check for null so we do not loop through the items.
172
+ */
173
+
174
+ if (filters.length === 0) {
175
+ return null;
176
+ }
177
+
178
+ return item => {
179
+ for (const filter of filters) {
180
+ const result = filter.paths.some(path => {
181
+ const value = transform(_dotProp.default.get(item, path), filter.transformValue);
182
+ const compareValue = transform(filter.compareValue, filter.transformValue);
183
+ const matched = filter.filterPlugin.matches({
184
+ value,
185
+ compareValue
186
+ });
187
+ return filter.negate ? !matched : matched;
188
+ });
189
+
190
+ if (result === false) {
191
+ return false;
192
+ }
193
+ }
194
+
195
+ return true;
196
+ };
197
+ };
198
+
199
+ const filterItems = params => {
200
+ const filter = createFilterCallable(params);
201
+ /**
202
+ * No point in going through all the items when there are no filters to be applied.
203
+ */
204
+
205
+ if (!filter) {
206
+ return params.items;
207
+ }
208
+
209
+ return params.items.filter(filter);
210
+ };
211
+
212
+ exports.filterItems = filterItems;
package/utils/get.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Entity } from "dynamodb-toolbox";
2
+ export interface Params {
3
+ entity: Entity<any>;
4
+ keys: {
5
+ PK: string;
6
+ SK: string;
7
+ };
8
+ }
9
+ /**
10
+ * Gets a single record from the DynamoDB table.
11
+ * Returns either record or null.
12
+ *
13
+ * Be aware to wrap in try/catch to avoid the error killing your app.
14
+ *
15
+ * @throws
16
+ */
17
+ export declare const get: <T>(params: Params) => Promise<T>;
package/utils/get.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.get = void 0;
7
+
8
+ /**
9
+ * Gets a single record from the DynamoDB table.
10
+ * Returns either record or null.
11
+ *
12
+ * Be aware to wrap in try/catch to avoid the error killing your app.
13
+ *
14
+ * @throws
15
+ */
16
+ const get = async params => {
17
+ const {
18
+ entity,
19
+ keys
20
+ } = params;
21
+ const result = await entity.get(keys);
22
+
23
+ if (!result || !result.Item) {
24
+ return null;
25
+ }
26
+
27
+ return result.Item;
28
+ };
29
+
30
+ exports.get = get;
@@ -0,0 +1,13 @@
1
+ interface MetaResponse {
2
+ cursor: string | null;
3
+ totalCount: number;
4
+ hasMoreItems: boolean;
5
+ }
6
+ interface CreateListResponseParams<T> {
7
+ items: T[];
8
+ after?: string | null;
9
+ totalCount: number;
10
+ limit: number;
11
+ }
12
+ export declare const createListResponse: <T>(params: CreateListResponseParams<T>) => [T[], MetaResponse];
13
+ export {};
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createListResponse = void 0;
7
+
8
+ var _cursor = require("./cursor");
9
+
10
+ const createListResponse = params => {
11
+ const {
12
+ items: initialItems,
13
+ after,
14
+ totalCount,
15
+ limit
16
+ } = params;
17
+ const start = (0, _cursor.decodeCursor)(after) || 0;
18
+ const hasMoreItems = totalCount > start + limit;
19
+ const end = limit > totalCount + start + limit ? undefined : start + limit;
20
+ const items = end ? initialItems.slice(start, end) : initialItems;
21
+ const cursor = items.length > 0 ? (0, _cursor.encodeCursor)(start + limit) : null;
22
+ const meta = {
23
+ hasMoreItems,
24
+ totalCount,
25
+ cursor
26
+ };
27
+ return [items, meta];
28
+ };
29
+
30
+ exports.createListResponse = createListResponse;
@@ -0,0 +1,33 @@
1
+ import { queryOptions as DynamoDBToolboxQueryOptions } from "dynamodb-toolbox/dist/classes/Table";
2
+ import { Entity } from "dynamodb-toolbox";
3
+ export interface QueryAllParams {
4
+ entity: Entity<any>;
5
+ partitionKey: string;
6
+ options?: DynamoDBToolboxQueryOptions;
7
+ }
8
+ export interface QueryOneParams extends QueryAllParams {
9
+ options?: Omit<DynamoDBToolboxQueryOptions, "limit">;
10
+ }
11
+ export interface QueryParams extends QueryAllParams {
12
+ previous?: any;
13
+ }
14
+ export interface QueryResult<T> {
15
+ result: any | null;
16
+ items: T[];
17
+ }
18
+ declare type DbItem<T> = T & {
19
+ PK: string;
20
+ SK: string;
21
+ TYPE: string;
22
+ GSI1_PK?: string;
23
+ GSI1_SK?: string;
24
+ };
25
+ /**
26
+ * Will run the query to fetch the first possible item from the database.
27
+ */
28
+ export declare const queryOne: <T>(params: QueryOneParams) => Promise<DbItem<T>>;
29
+ /**
30
+ * Will run the query to fetch the results no matter how much iterations it needs to go through.
31
+ */
32
+ export declare const queryAll: <T>(params: QueryAllParams) => Promise<DbItem<T>[]>;
33
+ export {};
package/utils/query.js ADDED
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.queryOne = exports.queryAll = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _error = _interopRequireDefault(require("@webiny/error"));
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; }
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; }
17
+
18
+ /**
19
+ * Will run query only once. Pass the previous to run the query again to fetch new data.
20
+ * It returns the result and the items it found.
21
+ * Result is required to fetch the items that were not fetched in the previous run.
22
+ */
23
+ const query = async params => {
24
+ const {
25
+ entity,
26
+ previous,
27
+ partitionKey,
28
+ options
29
+ } = params;
30
+ let result;
31
+ /**
32
+ * In case there is no previous result we must make a new query.
33
+ * This is the first query on the given partition key.
34
+ */
35
+
36
+ if (!previous) {
37
+ result = await entity.query(partitionKey, options);
38
+ } else if (typeof previous.next === "function") {
39
+ /**
40
+ * In case we have a previous result and it has a next method, we run it.
41
+ * In case result of the next method is false, it means it has nothing else to read
42
+ * and we return a null to keep the query from repeating.
43
+ */
44
+ result = await previous.next();
45
+
46
+ if (result === false) {
47
+ return {
48
+ result: null,
49
+ items: []
50
+ };
51
+ }
52
+ } else {
53
+ /**
54
+ * This could probably never happen but keep it here just in case to break the query loop.
55
+ * Basically, either previous does not exist or it exists and it does not have the next method
56
+ * and at that point a result returned will be null and loop should not start again.
57
+ */
58
+ return {
59
+ result: null,
60
+ items: []
61
+ };
62
+ }
63
+ /**
64
+ * We expect the result to contain an Items array and if not, something went wrong, very wrong.
65
+ */
66
+
67
+
68
+ if (!result || !result.Items || !Array.isArray(result.Items)) {
69
+ throw new _error.default("Error when querying for content entries - no result.", "QUERY_ERROR", {
70
+ partitionKey,
71
+ options
72
+ });
73
+ }
74
+
75
+ return {
76
+ result,
77
+ items: result.Items
78
+ };
79
+ };
80
+ /**
81
+ * Will run the query to fetch the first possible item from the database.
82
+ */
83
+
84
+
85
+ const queryOne = async params => {
86
+ const {
87
+ items
88
+ } = await query(_objectSpread(_objectSpread({}, params), {}, {
89
+ options: _objectSpread(_objectSpread({}, params.options || {}), {}, {
90
+ limit: 1
91
+ })
92
+ }));
93
+
94
+ if (items.length === 0) {
95
+ return null;
96
+ }
97
+
98
+ return items.shift();
99
+ };
100
+ /**
101
+ * Will run the query to fetch the results no matter how much iterations it needs to go through.
102
+ */
103
+
104
+
105
+ exports.queryOne = queryOne;
106
+
107
+ const queryAll = async params => {
108
+ const items = [];
109
+ let results;
110
+ let previousResult = undefined;
111
+
112
+ while (results = await query(_objectSpread(_objectSpread({}, params), {}, {
113
+ previous: previousResult
114
+ }))) {
115
+ items.push(...results.items);
116
+
117
+ if (!results.result) {
118
+ return items;
119
+ }
120
+
121
+ previousResult = results.result;
122
+ }
123
+
124
+ return items;
125
+ };
126
+
127
+ exports.queryAll = queryAll;
@@ -0,0 +1,17 @@
1
+ import { FieldPlugin } from "../plugins/definitions/FieldPlugin";
2
+ interface Params<T> {
3
+ /**
4
+ * The items we are sorting.
5
+ */
6
+ items: T[];
7
+ /**
8
+ * Sort options. For example: ["id_ASC"]
9
+ */
10
+ sort: string[];
11
+ /**
12
+ * Fields we can sort by.
13
+ */
14
+ fields?: FieldPlugin[];
15
+ }
16
+ export declare const sortItems: <T extends unknown = any>(params: Params<T>) => T[];
17
+ export {};
package/utils/sort.js ADDED
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.sortItems = void 0;
9
+
10
+ var _orderBy = _interopRequireDefault(require("lodash/orderBy"));
11
+
12
+ var _error = _interopRequireDefault(require("@webiny/error"));
13
+
14
+ const extractSort = (sortBy, fields) => {
15
+ const result = sortBy.split("_");
16
+
17
+ if (result.length !== 2) {
18
+ throw new _error.default("Problem in determining the sorting for the entry items.", "SORT_ERROR", {
19
+ sortBy
20
+ });
21
+ }
22
+
23
+ const [field, order] = result;
24
+
25
+ if (!field) {
26
+ throw new _error.default("Sorting field does not exist.", "SORTING_FIELD_ERROR", {
27
+ field,
28
+ order,
29
+ fields
30
+ });
31
+ }
32
+
33
+ const fieldPlugin = fields.find(f => f.getField() === field);
34
+ const isSortable = fieldPlugin ? fieldPlugin.isSortable() : true;
35
+
36
+ if (isSortable === false) {
37
+ throw new _error.default(`Cannot sort by given field: "${field}".`, "UNSUPPORTED_SORT_ERROR", {
38
+ fields,
39
+ field
40
+ });
41
+ }
42
+
43
+ return {
44
+ field,
45
+ reverse: order.toUpperCase() === "DESC"
46
+ };
47
+ };
48
+
49
+ const sortItems = params => {
50
+ const {
51
+ items,
52
+ sort: initialSort = [],
53
+ fields = []
54
+ } = params;
55
+ /**
56
+ * Skip sorting if nothing was passed to sort by or nothing to sort.
57
+ */
58
+
59
+ if (items.length <= 1 || Array.isArray(initialSort) === false || initialSort.length === 0) {
60
+ return items;
61
+ }
62
+
63
+ const info = {
64
+ sorters: [],
65
+ orders: []
66
+ };
67
+
68
+ for (const sort of initialSort) {
69
+ /**
70
+ * Possibly empty array item was passed.
71
+ */
72
+ if (!sort) {
73
+ continue;
74
+ }
75
+
76
+ const {
77
+ field,
78
+ reverse
79
+ } = extractSort(sort, fields);
80
+ const fieldPlugin = fields.find(f => f.getField() === field);
81
+ const path = fieldPlugin ? fieldPlugin.getPath() : field;
82
+ info.sorters.push(path);
83
+ info.orders.push(reverse === true ? "desc" : "asc");
84
+ }
85
+
86
+ if (info.sorters.length === 0) {
87
+ return items;
88
+ }
89
+
90
+ return (0, _orderBy.default)(items, info.sorters, info.orders);
91
+ };
92
+
93
+ exports.sortItems = sortItems;
@@ -0,0 +1,7 @@
1
+ import { DbContext } from "@webiny/handler-db/types";
2
+ /**
3
+ * Will be removed in favor of passing the table name directly to the storage operations.
4
+ *
5
+ * @deprecated
6
+ */
7
+ export declare const getTable: <T extends DbContext>(context: T) => string;
package/utils/table.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.getTable = void 0;
9
+
10
+ var _error = _interopRequireDefault(require("@webiny/error"));
11
+
12
+ /**
13
+ * Will be removed in favor of passing the table name directly to the storage operations.
14
+ *
15
+ * @deprecated
16
+ */
17
+ const getTable = context => {
18
+ if (!context.db) {
19
+ throw new _error.default("Missing db on context.", "DB_ERROR");
20
+ } else if (!context.db.table) {
21
+ throw new _error.default("Missing table on context.db.", "TABLE_ERROR");
22
+ }
23
+
24
+ return context.db.table;
25
+ };
26
+
27
+ exports.getTable = getTable;