@webiny/db-dynamodb 0.0.0-unstable.df6d94b531 β†’ 0.0.0-unstable.df7a8bb475

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 (237) hide show
  1. package/DynamoDbDriver.d.ts +18 -32
  2. package/DynamoDbDriver.js +207 -213
  3. package/DynamoDbDriver.js.map +1 -1
  4. package/README.md +6 -62
  5. package/index.d.ts +4 -3
  6. package/index.js +5 -35
  7. package/index.js.map +1 -1
  8. package/package.json +20 -26
  9. package/plugins/definitions/AttributePlugin.d.ts +3 -5
  10. package/plugins/definitions/AttributePlugin.js +7 -17
  11. package/plugins/definitions/AttributePlugin.js.map +1 -1
  12. package/plugins/definitions/DateTimeTransformPlugin.d.ts +2 -1
  13. package/plugins/definitions/DateTimeTransformPlugin.js +19 -25
  14. package/plugins/definitions/DateTimeTransformPlugin.js.map +1 -1
  15. package/plugins/definitions/FieldPathPlugin.js +12 -20
  16. package/plugins/definitions/FieldPathPlugin.js.map +1 -1
  17. package/plugins/definitions/FieldPlugin.d.ts +2 -2
  18. package/plugins/definitions/FieldPlugin.js +4 -17
  19. package/plugins/definitions/FieldPlugin.js.map +1 -1
  20. package/plugins/definitions/TimeTransformPlugin.d.ts +2 -1
  21. package/plugins/definitions/TimeTransformPlugin.js +23 -24
  22. package/plugins/definitions/TimeTransformPlugin.js.map +1 -1
  23. package/plugins/definitions/ValueFilterPlugin.d.ts +3 -1
  24. package/plugins/definitions/ValueFilterPlugin.js +14 -16
  25. package/plugins/definitions/ValueFilterPlugin.js.map +1 -1
  26. package/plugins/definitions/ValueTransformPlugin.d.ts +1 -1
  27. package/plugins/definitions/ValueTransformPlugin.js +12 -20
  28. package/plugins/definitions/ValueTransformPlugin.js.map +1 -1
  29. package/plugins/definitions/assignFields.js +6 -12
  30. package/plugins/definitions/assignFields.js.map +1 -1
  31. package/plugins/filters/andIn.d.ts +2 -2
  32. package/plugins/filters/andIn.js +7 -13
  33. package/plugins/filters/andIn.js.map +1 -1
  34. package/plugins/filters/between.d.ts +2 -2
  35. package/plugins/filters/between.js +7 -13
  36. package/plugins/filters/between.js.map +1 -1
  37. package/plugins/filters/contains.d.ts +2 -2
  38. package/plugins/filters/contains.js +45 -21
  39. package/plugins/filters/contains.js.map +1 -1
  40. package/plugins/filters/eq.d.ts +2 -2
  41. package/plugins/filters/eq.js +7 -12
  42. package/plugins/filters/eq.js.map +1 -1
  43. package/plugins/filters/fuzzy.d.ts +2 -2
  44. package/plugins/filters/fuzzy.js +19 -16
  45. package/plugins/filters/fuzzy.js.map +1 -1
  46. package/plugins/filters/gt.d.ts +2 -2
  47. package/plugins/filters/gt.js +5 -10
  48. package/plugins/filters/gt.js.map +1 -1
  49. package/plugins/filters/gte.d.ts +2 -2
  50. package/plugins/filters/gte.js +5 -10
  51. package/plugins/filters/gte.js.map +1 -1
  52. package/plugins/filters/in.d.ts +2 -2
  53. package/plugins/filters/in.js +7 -13
  54. package/plugins/filters/in.js.map +1 -1
  55. package/plugins/filters/index.d.ts +1 -1
  56. package/plugins/filters/index.js +13 -19
  57. package/plugins/filters/index.js.map +1 -1
  58. package/plugins/filters/lt.d.ts +2 -2
  59. package/plugins/filters/lt.js +5 -10
  60. package/plugins/filters/lt.js.map +1 -1
  61. package/plugins/filters/lte.d.ts +2 -2
  62. package/plugins/filters/lte.js +5 -10
  63. package/plugins/filters/lte.js.map +1 -1
  64. package/plugins/filters/startsWith.d.ts +2 -2
  65. package/plugins/filters/startsWith.js +16 -11
  66. package/plugins/filters/startsWith.js.map +1 -1
  67. package/plugins/index.d.ts +9 -1
  68. package/plugins/index.js +13 -11
  69. package/plugins/index.js.map +1 -1
  70. package/store/entity.d.ts +6 -0
  71. package/store/entity.js +11 -0
  72. package/store/entity.js.map +1 -0
  73. package/store/keys.d.ts +6 -0
  74. package/store/keys.js +16 -0
  75. package/store/keys.js.map +1 -0
  76. package/store/types.d.ts +6 -0
  77. package/store/types.js +3 -0
  78. package/store/types.js.map +1 -0
  79. package/toolbox.d.ts +8 -0
  80. package/toolbox.js +5 -0
  81. package/toolbox.js.map +1 -0
  82. package/types.d.ts +3 -24
  83. package/types.js +2 -4
  84. package/types.js.map +1 -1
  85. package/utils/attributes.d.ts +5 -5
  86. package/utils/attributes.js +10 -15
  87. package/utils/attributes.js.map +1 -1
  88. package/utils/batch/batchRead.d.ts +15 -0
  89. package/utils/{batchRead.js β†’ batch/batchRead.js} +10 -13
  90. package/utils/batch/batchRead.js.map +1 -0
  91. package/utils/batch/batchWrite.d.ts +13 -0
  92. package/utils/batch/batchWrite.js +57 -0
  93. package/utils/batch/batchWrite.js.map +1 -0
  94. package/utils/batch/index.d.ts +3 -0
  95. package/utils/batch/index.js +5 -0
  96. package/utils/batch/index.js.map +1 -0
  97. package/utils/batch/types.d.ts +30 -0
  98. package/utils/batch/types.js +3 -0
  99. package/utils/batch/types.js.map +1 -0
  100. package/utils/cleanup.d.ts +3 -3
  101. package/utils/cleanup.js +9 -14
  102. package/utils/cleanup.js.map +1 -1
  103. package/utils/count.d.ts +2 -0
  104. package/utils/count.js +16 -0
  105. package/utils/count.js.map +1 -0
  106. package/utils/createEntity.d.ts +36 -0
  107. package/utils/createEntity.js +85 -0
  108. package/utils/createEntity.js.map +1 -0
  109. package/utils/createTable.d.ts +11 -0
  110. package/utils/createTable.js +39 -0
  111. package/utils/createTable.js.map +1 -0
  112. package/utils/cursor.js +4 -10
  113. package/utils/cursor.js.map +1 -1
  114. package/utils/delete.d.ts +10 -0
  115. package/utils/delete.js +11 -0
  116. package/utils/delete.js.map +1 -0
  117. package/utils/entity/Entity.d.ts +28 -0
  118. package/utils/entity/Entity.js +99 -0
  119. package/utils/entity/Entity.js.map +1 -0
  120. package/utils/entity/EntityReadBatch.d.ts +18 -0
  121. package/utils/entity/EntityReadBatch.js +39 -0
  122. package/utils/entity/EntityReadBatch.js.map +1 -0
  123. package/utils/entity/EntityReadBatchBuilder.d.ts +10 -0
  124. package/utils/entity/EntityReadBatchBuilder.js +21 -0
  125. package/utils/entity/EntityReadBatchBuilder.js.map +1 -0
  126. package/utils/entity/EntityWriteBatch.d.ts +23 -0
  127. package/utils/entity/EntityWriteBatch.js +51 -0
  128. package/utils/entity/EntityWriteBatch.js.map +1 -0
  129. package/utils/entity/EntityWriteBatchBuilder.d.ts +11 -0
  130. package/utils/entity/EntityWriteBatchBuilder.js +20 -0
  131. package/utils/entity/EntityWriteBatchBuilder.js.map +1 -0
  132. package/utils/entity/getEntity.d.ts +4 -0
  133. package/utils/entity/getEntity.js +12 -0
  134. package/utils/entity/getEntity.js.map +1 -0
  135. package/utils/entity/index.d.ts +7 -0
  136. package/utils/entity/index.js +9 -0
  137. package/utils/entity/index.js.map +1 -0
  138. package/utils/entity/types.d.ts +75 -0
  139. package/utils/entity/types.js +4 -0
  140. package/utils/entity/types.js.map +1 -0
  141. package/utils/filter.d.ts +2 -2
  142. package/utils/filter.js +14 -16
  143. package/utils/filter.js.map +1 -1
  144. package/utils/get.d.ts +8 -6
  145. package/utils/get.js +15 -10
  146. package/utils/get.js.map +1 -1
  147. package/utils/index.d.ts +17 -0
  148. package/utils/index.js +19 -0
  149. package/utils/index.js.map +1 -0
  150. package/utils/listResponse.js +7 -11
  151. package/utils/listResponse.js.map +1 -1
  152. package/utils/put.d.ts +12 -0
  153. package/utils/put.js +12 -0
  154. package/utils/put.js.map +1 -0
  155. package/utils/query.d.ts +15 -14
  156. package/utils/query.js +51 -24
  157. package/utils/query.js.map +1 -1
  158. package/utils/scan.d.ts +38 -0
  159. package/utils/scan.js +82 -0
  160. package/utils/scan.js.map +1 -0
  161. package/utils/sort.d.ts +1 -1
  162. package/utils/sort.js +10 -15
  163. package/utils/sort.js.map +1 -1
  164. package/utils/table/Table.d.ts +10 -0
  165. package/utils/table/Table.js +27 -0
  166. package/utils/table/Table.js.map +1 -0
  167. package/utils/table/TableReadBatch.d.ts +19 -0
  168. package/utils/table/TableReadBatch.js +54 -0
  169. package/utils/table/TableReadBatch.js.map +1 -0
  170. package/utils/table/TableWriteBatch.d.ts +21 -0
  171. package/utils/table/TableWriteBatch.js +61 -0
  172. package/utils/table/TableWriteBatch.js.map +1 -0
  173. package/utils/table/index.d.ts +4 -0
  174. package/utils/table/index.js +6 -0
  175. package/utils/table/index.js.map +1 -0
  176. package/utils/table/types.d.ts +39 -0
  177. package/utils/table/types.js +3 -0
  178. package/utils/table/types.js.map +1 -0
  179. package/utils/update.d.ts +12 -0
  180. package/utils/update.js +12 -0
  181. package/utils/update.js.map +1 -0
  182. package/BatchProcess.d.ts +0 -47
  183. package/BatchProcess.js +0 -164
  184. package/BatchProcess.js.map +0 -1
  185. package/QueryGenerator.d.ts +0 -21
  186. package/QueryGenerator.js +0 -64
  187. package/QueryGenerator.js.map +0 -1
  188. package/operators/comparison/beginsWith.d.ts +0 -3
  189. package/operators/comparison/beginsWith.js +0 -24
  190. package/operators/comparison/beginsWith.js.map +0 -1
  191. package/operators/comparison/between.d.ts +0 -3
  192. package/operators/comparison/between.js +0 -30
  193. package/operators/comparison/between.js.map +0 -1
  194. package/operators/comparison/eq.d.ts +0 -3
  195. package/operators/comparison/eq.js +0 -32
  196. package/operators/comparison/eq.js.map +0 -1
  197. package/operators/comparison/gt.d.ts +0 -3
  198. package/operators/comparison/gt.js +0 -24
  199. package/operators/comparison/gt.js.map +0 -1
  200. package/operators/comparison/gte.d.ts +0 -3
  201. package/operators/comparison/gte.js +0 -24
  202. package/operators/comparison/gte.js.map +0 -1
  203. package/operators/comparison/lt.d.ts +0 -3
  204. package/operators/comparison/lt.js +0 -24
  205. package/operators/comparison/lt.js.map +0 -1
  206. package/operators/comparison/lte.d.ts +0 -3
  207. package/operators/comparison/lte.js +0 -24
  208. package/operators/comparison/lte.js.map +0 -1
  209. package/operators/index.d.ts +0 -12
  210. package/operators/index.js +0 -28
  211. package/operators/index.js.map +0 -1
  212. package/operators/logical/and.d.ts +0 -3
  213. package/operators/logical/and.js +0 -58
  214. package/operators/logical/and.js.map +0 -1
  215. package/operators/logical/or.d.ts +0 -3
  216. package/operators/logical/or.js +0 -58
  217. package/operators/logical/or.js.map +0 -1
  218. package/plugins/definitions/NumberTransformPlugin.d.ts +0 -4
  219. package/plugins/definitions/NumberTransformPlugin.js +0 -34
  220. package/plugins/definitions/NumberTransformPlugin.js.map +0 -1
  221. package/statements/createKeyConditionExpressionArgs.d.ts +0 -15
  222. package/statements/createKeyConditionExpressionArgs.js +0 -45
  223. package/statements/createKeyConditionExpressionArgs.js.map +0 -1
  224. package/statements/processStatement.d.ts +0 -3
  225. package/statements/processStatement.js +0 -35
  226. package/statements/processStatement.js.map +0 -1
  227. package/utils/batchRead.d.ts +0 -15
  228. package/utils/batchRead.js.map +0 -1
  229. package/utils/batchWrite.d.ts +0 -17
  230. package/utils/batchWrite.js +0 -24
  231. package/utils/batchWrite.js.map +0 -1
  232. package/utils/createStandardEntity.d.ts +0 -2
  233. package/utils/createStandardEntity.js +0 -34
  234. package/utils/createStandardEntity.js.map +0 -1
  235. package/utils/table.d.ts +0 -7
  236. package/utils/table.js +0 -22
  237. package/utils/table.js.map +0 -1
@@ -1,35 +1,21 @@
1
- /**
2
- * Remove this when no apps are using our internal db drivers anymore
3
- */
4
- import { DocumentClient } from "aws-sdk/clients/dynamodb";
5
- import BatchProcess from "./BatchProcess";
6
- import { DbDriver, Args, Result, ArgsBatch } from "@webiny/db";
7
- declare type ConstructorArgs = {
8
- documentClient?: DocumentClient;
9
- };
10
- interface ReadLogsParams {
11
- table: string;
1
+ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ import type { DbDriver, GetValueResult, GetValuesResult, IListValuesParams, ListValuesResult, RemoveValueResult, RemoveValuesResult, StorageKey, StoreValueResult, StoreValuesResult } from "@webiny/db";
3
+ import type { GenericRecord } from "@webiny/api/types.js";
4
+ interface ConstructorArgs {
5
+ documentClient: DynamoDBDocument;
12
6
  }
13
- interface CreateLogParams {
14
- id: string;
15
- operation: string;
16
- /**
17
- * TODO: determine the data type.
18
- */
19
- data: any;
20
- table: string;
21
- }
22
- declare class DynamoDbDriver implements DbDriver {
23
- batchProcesses: Record<string, BatchProcess>;
24
- documentClient: DocumentClient;
25
- constructor({ documentClient }?: ConstructorArgs);
26
- getClient(): DocumentClient;
27
- create({ table, data, meta, __batch: batch }: Args): Promise<Result>;
28
- update({ query, data, table, meta, __batch: batch }: Args): Promise<Result>;
29
- delete({ query, table, meta, __batch: batch }: Args): Promise<Result>;
30
- read<T>({ table, query, sort, limit, keys, meta, __batch: batch }: Args): Promise<Result<T[]>>;
31
- createLog({ id, operation, data, table }: CreateLogParams): Promise<Result>;
32
- readLogs<T>({ table }: ReadLogsParams): Promise<Result<T[]>>;
33
- getBatchProcess(__batch: ArgsBatch): BatchProcess;
7
+ declare class DynamoDbDriver implements DbDriver<DynamoDBDocument> {
8
+ readonly documentClient: DynamoDBDocument;
9
+ readonly table: import("./utils").ITable<string, "PK", "SK">;
10
+ readonly entity: import("./store/types").IStoreEntity;
11
+ constructor({ documentClient }: ConstructorArgs);
12
+ getClient(): DynamoDBDocument;
13
+ storeValue<V>(key: string, input: V): Promise<StoreValueResult<V>>;
14
+ storeValues<V extends GenericRecord<StorageKey>>(values: V): Promise<StoreValuesResult<V>>;
15
+ getValue<V>(key: StorageKey): Promise<GetValueResult<V>>;
16
+ getValues<V extends GenericRecord<StorageKey>>(input: (keyof V)[]): Promise<GetValuesResult<V>>;
17
+ listValues<V extends GenericRecord<StorageKey>>(params?: IListValuesParams): Promise<ListValuesResult<V>>;
18
+ removeValue<V>(key: StorageKey): Promise<RemoveValueResult<V>>;
19
+ removeValues<V extends GenericRecord<StorageKey>>(input: (keyof V)[]): Promise<RemoveValuesResult<V>>;
34
20
  }
35
21
  export default DynamoDbDriver;
package/DynamoDbDriver.js CHANGED
@@ -1,239 +1,233 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = void 0;
8
- var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
9
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
10
- var _dynamodb = require("aws-sdk/clients/dynamodb");
11
- var _BatchProcess = _interopRequireDefault(require("./BatchProcess"));
12
- var _QueryGenerator = _interopRequireDefault(require("./QueryGenerator"));
13
- /**
14
- * Remove this when no apps are using our internal db drivers anymore
15
- */
16
- // @ts-nocheck
17
-
18
- const LOG_KEYS = [{
19
- primary: true,
20
- unique: true,
21
- name: "primary",
22
- fields: [{
23
- name: "PK"
24
- }, {
25
- name: "SK"
26
- }]
27
- }];
1
+ import { createTable } from "./utils/createTable.js";
2
+ import { createEntity } from "./store/entity.js";
3
+ import { createPartitionKey, createSortKey, createType } from "./store/keys.js";
28
4
  class DynamoDbDriver {
29
5
  constructor({
30
6
  documentClient
31
- } = {}) {
32
- (0, _defineProperty2.default)(this, "batchProcesses", void 0);
33
- (0, _defineProperty2.default)(this, "documentClient", void 0);
34
- this.batchProcesses = {};
35
- this.documentClient = documentClient || new _dynamodb.DocumentClient();
7
+ }) {
8
+ this.documentClient = documentClient;
9
+ this.table = createTable({
10
+ name: process.env.DB_TABLE,
11
+ documentClient
12
+ });
13
+ this.entity = createEntity({
14
+ table: this.table
15
+ });
36
16
  }
37
17
  getClient() {
38
18
  return this.documentClient;
39
19
  }
40
- async create({
41
- table,
42
- data,
43
- meta,
44
- __batch: batch
45
- }) {
46
- if (!batch) {
47
- const result = await this.documentClient.put({
48
- TableName: table,
49
- Item: data,
50
- ReturnConsumedCapacity: meta ? "TOTAL" : "NONE"
51
- }).promise();
52
- return [true, {
53
- response: result.$response
54
- }];
20
+ async storeValue(key, input) {
21
+ let value;
22
+ try {
23
+ value = JSON.stringify(input);
24
+ } catch (ex) {
25
+ return {
26
+ key,
27
+ error: ex
28
+ };
55
29
  }
56
- const batchProcess = this.getBatchProcess(batch);
57
- batchProcess.addBatchWrite({
58
- table,
59
- data
60
- });
61
- if (batchProcess.allOperationsAdded()) {
62
- batchProcess.startExecution();
63
- } else {
64
- await batchProcess.waitStartExecution();
30
+ try {
31
+ await this.entity.put({
32
+ PK: createPartitionKey(),
33
+ SK: createSortKey({
34
+ key
35
+ }),
36
+ TYPE: createType(),
37
+ data: {
38
+ key,
39
+ value
40
+ }
41
+ });
42
+ return {
43
+ key,
44
+ data: input
45
+ };
46
+ } catch (ex) {
47
+ return {
48
+ key,
49
+ error: ex
50
+ };
65
51
  }
66
- await batchProcess.waitExecution();
67
- return [true, {
68
- response: batchProcess.response
69
- }];
70
52
  }
71
- async update({
72
- query,
73
- data,
74
- table,
75
- meta,
76
- __batch: batch
77
- }) {
78
- if (!batch) {
79
- const update = {
80
- UpdateExpression: "SET ",
81
- ExpressionAttributeNames: {},
82
- ExpressionAttributeValues: {}
83
- };
84
- const updateExpression = [];
85
- for (const key in data) {
86
- updateExpression.push(`#${key} = :${key}`);
87
- update.ExpressionAttributeNames[`#${key}`] = key;
88
- update.ExpressionAttributeValues[`:${key}`] = data[key];
53
+ async storeValues(values) {
54
+ const keys = Object.keys(values);
55
+ const batchWrite = this.entity.createEntityWriter();
56
+ try {
57
+ for (const key of keys) {
58
+ const input = values[key];
59
+ let value;
60
+ try {
61
+ value = JSON.stringify(input);
62
+ } catch (ex) {
63
+ throw ex;
64
+ }
65
+ batchWrite.put({
66
+ PK: createPartitionKey(),
67
+ SK: createSortKey({
68
+ key
69
+ }),
70
+ TYPE: createType(),
71
+ data: {
72
+ key,
73
+ value
74
+ }
75
+ });
89
76
  }
90
- update.UpdateExpression += updateExpression.join(", ");
91
- const result = await this.documentClient.update((0, _objectSpread2.default)({
92
- TableName: table,
93
- Key: query,
94
- ReturnConsumedCapacity: meta ? "TOTAL" : "NONE"
95
- }, update)).promise();
96
- return [true, {
97
- response: result.$response
98
- }];
99
- }
100
- const batchProcess = this.getBatchProcess(batch);
101
- batchProcess.addBatchWrite({
102
- table,
103
- data
104
- });
105
- if (batchProcess.allOperationsAdded()) {
106
- batchProcess.startExecution();
107
- } else {
108
- await batchProcess.waitStartExecution();
77
+ await batchWrite.execute();
78
+ return {
79
+ keys,
80
+ data: values
81
+ };
82
+ } catch (ex) {
83
+ return {
84
+ keys,
85
+ error: ex
86
+ };
109
87
  }
110
- await batchProcess.waitExecution();
111
- return [true, {
112
- response: batchProcess.response
113
- }];
114
88
  }
115
- async delete({
116
- query,
117
- table,
118
- meta,
119
- __batch: batch
120
- }) {
121
- if (!batch) {
122
- const result = await this.documentClient.delete({
123
- TableName: table,
124
- Key: query,
125
- ReturnConsumedCapacity: meta ? "TOTAL" : "NONE"
126
- }).promise();
127
- return [true, {
128
- response: result.$response
129
- }];
89
+ async getValue(key) {
90
+ try {
91
+ const result = await this.entity.get({
92
+ PK: createPartitionKey(),
93
+ SK: createSortKey({
94
+ key
95
+ })
96
+ });
97
+ return {
98
+ key,
99
+ data: result?.data?.value ? JSON.parse(result.data.value) : null
100
+ };
101
+ } catch (ex) {
102
+ return {
103
+ key,
104
+ error: ex
105
+ };
130
106
  }
131
- const batchProcess = this.getBatchProcess(batch);
132
- batchProcess.addBatchDelete({
133
- table,
134
- query
107
+ }
108
+ async getValues(input) {
109
+ const keys = [...input];
110
+ const batchRead = this.entity.createEntityReader({
111
+ read: keys.map(key => {
112
+ return {
113
+ PK: createPartitionKey(),
114
+ SK: createSortKey({
115
+ key
116
+ })
117
+ };
118
+ })
135
119
  });
136
- if (batchProcess.allOperationsAdded()) {
137
- batchProcess.startExecution();
138
- } else {
139
- await batchProcess.waitStartExecution();
120
+ try {
121
+ const results = await batchRead.execute();
122
+ const data = keys.reduce((collection, initialKey) => {
123
+ const key = initialKey;
124
+ const result = results.find(item => {
125
+ return item.PK === createPartitionKey() && item.SK === createSortKey({
126
+ key
127
+ });
128
+ });
129
+ if (!result?.data?.value) {
130
+ collection[key] = null;
131
+ return collection;
132
+ }
133
+ try {
134
+ collection[key] = JSON.parse(result.data.value);
135
+ } catch {
136
+ collection[key] = null;
137
+ }
138
+ return collection;
139
+ }, {});
140
+ return {
141
+ keys,
142
+ data
143
+ };
144
+ } catch (ex) {
145
+ return {
146
+ keys,
147
+ error: ex
148
+ };
140
149
  }
141
- await batchProcess.waitExecution();
142
- return [true, {
143
- response: batchProcess.response
144
- }];
145
150
  }
146
- async read({
147
- table,
148
- query,
149
- sort,
150
- limit,
151
- keys,
152
- meta,
153
- __batch: batch
154
- }) {
155
- if (!batch) {
156
- const queryGenerator = new _QueryGenerator.default();
157
- const queryParams = queryGenerator.generate({
158
- query,
159
- keys,
160
- sort,
161
- limit,
162
- tableName: table
151
+ async listValues(params) {
152
+ try {
153
+ const partitionKey = createPartitionKey();
154
+ const options = {
155
+ ...params
156
+ };
157
+ const results = await this.entity.queryAll({
158
+ partitionKey,
159
+ options
163
160
  });
164
- const response = await this.documentClient.query((0, _objectSpread2.default)((0, _objectSpread2.default)({}, queryParams), {}, {
165
- ReturnConsumedCapacity: meta ? "TOTAL" : "NONE"
166
- })).promise();
167
- if (Array.isArray(response.Items)) {
168
- return [response.Items, {
169
- response: response.$response
170
- }];
171
- }
172
- return [[], {
173
- response: response.$response
174
- }];
161
+ const data = results.reduce((collection, item) => {
162
+ const key = item.data.key;
163
+ try {
164
+ collection[key] = JSON.parse(item.data.value);
165
+ } catch {
166
+ collection[key] = null;
167
+ }
168
+ return collection;
169
+ }, {});
170
+ return {
171
+ keys: Object.keys(data),
172
+ data
173
+ };
174
+ } catch (ex) {
175
+ return {
176
+ error: ex
177
+ };
175
178
  }
176
-
177
- // DynamoDb doesn't support batch queries, so we can immediately assume the GetRequest operation.
178
- const batchProcess = this.getBatchProcess(batch);
179
- const getResult = batchProcess.addBatchGet({
180
- table,
181
- query
182
- });
183
- if (batchProcess.allOperationsAdded()) {
184
- batchProcess.startExecution();
185
- } else {
186
- await batchProcess.waitStartExecution();
179
+ }
180
+ async removeValue(key) {
181
+ const result = await this.getValue(key);
182
+ if (result.error) {
183
+ return {
184
+ key,
185
+ error: result.error
186
+ };
187
187
  }
188
- await batchProcess.waitExecution();
189
- const result = getResult();
190
- if (result) {
191
- return [[result], {
192
- response: batchProcess.response
193
- }];
188
+ try {
189
+ await this.entity.delete({
190
+ PK: createPartitionKey(),
191
+ SK: createSortKey({
192
+ key
193
+ })
194
+ });
195
+ return {
196
+ key,
197
+ data: result.data
198
+ };
199
+ } catch (ex) {
200
+ return {
201
+ key,
202
+ error: ex
203
+ };
194
204
  }
195
- return [[], {
196
- response: batchProcess.response
197
- }];
198
205
  }
199
- async createLog({
200
- id,
201
- operation,
202
- data,
203
- table
204
- }) {
205
- await this.create({
206
- table: table,
207
- keys: LOG_KEYS,
208
- data: (0, _objectSpread2.default)({
209
- PK: "log",
210
- SK: id,
211
- id,
212
- operation
213
- }, data)
214
- });
215
- return [true, {}];
216
- }
217
- async readLogs({
218
- table
219
- }) {
220
- return this.read({
221
- table,
222
- keys: LOG_KEYS,
223
- query: {
224
- PK: "log",
225
- SK: {
226
- $gte: " "
227
- }
228
- }
206
+ async removeValues(input) {
207
+ const keys = [...input];
208
+ const batchDelete = this.entity.createEntityWriter({
209
+ delete: keys.map(key => {
210
+ return {
211
+ PK: createPartitionKey(),
212
+ SK: createSortKey({
213
+ key
214
+ })
215
+ };
216
+ })
229
217
  });
230
- }
231
- getBatchProcess(__batch) {
232
- if (!this.batchProcesses[__batch.instance.id]) {
233
- this.batchProcesses[__batch.instance.id] = new _BatchProcess.default(__batch.instance, this.documentClient);
218
+ try {
219
+ await batchDelete.execute();
220
+ return {
221
+ keys
222
+ };
223
+ } catch (ex) {
224
+ return {
225
+ keys,
226
+ error: ex
227
+ };
234
228
  }
235
- return this.batchProcesses[__batch.instance.id];
236
229
  }
237
230
  }
238
- var _default = DynamoDbDriver;
239
- exports.default = _default;
231
+ export default DynamoDbDriver;
232
+
233
+ //# sourceMappingURL=DynamoDbDriver.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["LOG_KEYS","primary","unique","name","fields","DynamoDbDriver","constructor","documentClient","batchProcesses","DocumentClient","getClient","create","table","data","meta","__batch","batch","result","put","TableName","Item","ReturnConsumedCapacity","promise","response","$response","batchProcess","getBatchProcess","addBatchWrite","allOperationsAdded","startExecution","waitStartExecution","waitExecution","update","query","UpdateExpression","ExpressionAttributeNames","ExpressionAttributeValues","updateExpression","key","push","join","Key","delete","addBatchDelete","read","sort","limit","keys","queryGenerator","QueryGenerator","queryParams","generate","tableName","Array","isArray","Items","getResult","addBatchGet","createLog","id","operation","PK","SK","readLogs","$gte","instance","BatchProcess"],"sources":["DynamoDbDriver.ts"],"sourcesContent":["/**\n * Remove this when no apps are using our internal db drivers anymore\n */\n// @ts-nocheck\nimport { DocumentClient } from \"aws-sdk/clients/dynamodb\";\nimport BatchProcess from \"./BatchProcess\";\nimport QueryGenerator from \"./QueryGenerator\";\nimport { DbDriver, Args, Result, ArgsBatch } from \"@webiny/db\";\nimport { QueryKeys } from \"~/types\";\n\ntype ConstructorArgs = {\n documentClient?: DocumentClient;\n};\n\nconst LOG_KEYS: QueryKeys = [\n {\n primary: true,\n unique: true,\n name: \"primary\",\n fields: [{ name: \"PK\" }, { name: \"SK\" }]\n }\n];\n\ninterface Update {\n UpdateExpression: string;\n ExpressionAttributeNames: Record<string, any>;\n ExpressionAttributeValues: Record<string, any>;\n}\n\ninterface ReadLogsParams {\n table: string;\n}\n\ninterface CreateLogParams {\n id: string;\n operation: string;\n /**\n * TODO: determine the data type.\n */\n data: any;\n table: string;\n}\n\nclass DynamoDbDriver implements DbDriver {\n batchProcesses: Record<string, BatchProcess>;\n documentClient: DocumentClient;\n constructor({ documentClient }: ConstructorArgs = {}) {\n this.batchProcesses = {};\n this.documentClient = documentClient || new DocumentClient();\n }\n\n getClient() {\n return this.documentClient;\n }\n\n async create({ table, data, meta, __batch: batch }: Args): Promise<Result> {\n if (!batch) {\n const result = await this.documentClient\n .put({\n TableName: table,\n Item: data,\n ReturnConsumedCapacity: meta ? \"TOTAL\" : \"NONE\"\n })\n .promise();\n return [true, { response: result.$response }];\n }\n\n const batchProcess = this.getBatchProcess(batch);\n batchProcess.addBatchWrite({ table, data });\n\n if (batchProcess.allOperationsAdded()) {\n batchProcess.startExecution();\n } else {\n await batchProcess.waitStartExecution();\n }\n\n await batchProcess.waitExecution();\n\n return [true, { response: batchProcess.response }];\n }\n\n async update({ query, data, table, meta, __batch: batch }: Args): Promise<Result> {\n if (!batch) {\n const update: Update = {\n UpdateExpression: \"SET \",\n ExpressionAttributeNames: {},\n ExpressionAttributeValues: {}\n };\n\n const updateExpression = [];\n for (const key in data) {\n updateExpression.push(`#${key} = :${key}`);\n update.ExpressionAttributeNames[`#${key}`] = key;\n update.ExpressionAttributeValues[`:${key}`] = data[key];\n }\n\n update.UpdateExpression += updateExpression.join(\", \");\n\n const result = await this.documentClient\n .update({\n TableName: table,\n Key: query,\n ReturnConsumedCapacity: meta ? \"TOTAL\" : \"NONE\",\n ...update\n })\n .promise();\n\n return [true, { response: result.$response }];\n }\n\n const batchProcess = this.getBatchProcess(batch);\n\n batchProcess.addBatchWrite({\n table,\n data\n });\n\n if (batchProcess.allOperationsAdded()) {\n batchProcess.startExecution();\n } else {\n await batchProcess.waitStartExecution();\n }\n\n await batchProcess.waitExecution();\n\n return [true, { response: batchProcess.response }];\n }\n\n async delete({ query, table, meta, __batch: batch }: Args): Promise<Result> {\n if (!batch) {\n const result = await this.documentClient\n .delete({\n TableName: table,\n Key: query,\n ReturnConsumedCapacity: meta ? \"TOTAL\" : \"NONE\"\n })\n .promise();\n\n return [true, { response: result.$response }];\n }\n\n const batchProcess = this.getBatchProcess(batch);\n batchProcess.addBatchDelete({\n table,\n query\n });\n\n if (batchProcess.allOperationsAdded()) {\n batchProcess.startExecution();\n } else {\n await batchProcess.waitStartExecution();\n }\n\n await batchProcess.waitExecution();\n\n return [true, { response: batchProcess.response }];\n }\n\n async read<T>({\n table,\n query,\n sort,\n limit,\n keys,\n meta,\n __batch: batch\n }: Args): Promise<Result<T[]>> {\n if (!batch) {\n const queryGenerator = new QueryGenerator();\n const queryParams = queryGenerator.generate({\n query,\n keys,\n sort,\n limit,\n tableName: table\n });\n\n const response = await this.documentClient\n .query({ ...queryParams, ReturnConsumedCapacity: meta ? \"TOTAL\" : \"NONE\" })\n .promise();\n\n if (Array.isArray(response.Items)) {\n return [response.Items as T[], { response: response.$response }];\n }\n return [[], { response: response.$response }];\n }\n\n // DynamoDb doesn't support batch queries, so we can immediately assume the GetRequest operation.\n const batchProcess = this.getBatchProcess(batch);\n const getResult = batchProcess.addBatchGet({\n table,\n query\n });\n\n if (batchProcess.allOperationsAdded()) {\n batchProcess.startExecution();\n } else {\n await batchProcess.waitStartExecution();\n }\n\n await batchProcess.waitExecution();\n\n const result = getResult() as T;\n if (result) {\n return [[result], { response: batchProcess.response }];\n }\n\n return [[], { response: batchProcess.response }];\n }\n\n async createLog({ id, operation, data, table }: CreateLogParams): Promise<Result> {\n await this.create({\n table: table,\n keys: LOG_KEYS,\n data: {\n PK: \"log\",\n SK: id,\n id,\n operation,\n ...data\n }\n });\n\n return [true, {}];\n }\n\n async readLogs<T>({ table }: ReadLogsParams) {\n return this.read<T>({\n table,\n keys: LOG_KEYS,\n query: {\n PK: \"log\",\n SK: { $gte: \" \" }\n }\n });\n }\n\n getBatchProcess(__batch: ArgsBatch): BatchProcess {\n if (!this.batchProcesses[__batch.instance.id]) {\n this.batchProcesses[__batch.instance.id] = new BatchProcess(\n __batch.instance,\n this.documentClient\n );\n }\n\n return this.batchProcesses[__batch.instance.id];\n }\n}\n\nexport default DynamoDbDriver;\n"],"mappings":";;;;;;;;;AAIA;AACA;AACA;AANA;AACA;AACA;AACA;;AAWA,MAAMA,QAAmB,GAAG,CACxB;EACIC,OAAO,EAAE,IAAI;EACbC,MAAM,EAAE,IAAI;EACZC,IAAI,EAAE,SAAS;EACfC,MAAM,EAAE,CAAC;IAAED,IAAI,EAAE;EAAK,CAAC,EAAE;IAAEA,IAAI,EAAE;EAAK,CAAC;AAC3C,CAAC,CACJ;AAsBD,MAAME,cAAc,CAAqB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I;IAEf,CAAC,CAAC;IAEF,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;EACrB;EAEA,MAAMkD,QAAQ,CAAI;IAAEnD;EAAsB,CAAC,EAAE;IACzC,OAAO,IAAI,CAACgC,IAAI,CAAI;MAChBhC,KAAK;MACLmC,IAAI,EAAE/C,QAAQ;MACdiC,KAAK,EAAE;QACH4B,EAAE,EAAE,KAAK;QACTC,EAAE,EAAE;UAAEE,IAAI,EAAE;QAAI;MACpB;IACJ,CAAC,CAAC;EACN;EAEAtC,eAAe,CAACX,OAAkB,EAAgB;IAC9C,IAAI,CAAC,IAAI,CAACP,cAAc,CAACO,OAAO,CAACkD,QAAQ,CAACN,EAAE,CAAC,EAAE;MAC3C,IAAI,CAACnD,cAAc,CAACO,OAAO,CAACkD,QAAQ,CAACN,EAAE,CAAC,GAAG,IAAIO,qBAAY,CACvDnD,OAAO,CAACkD,QAAQ,EAChB,IAAI,CAAC1D,cAAc,CACtB;IACL;IAEA,OAAO,IAAI,CAACC,cAAc,CAACO,OAAO,CAACkD,QAAQ,CAACN,EAAE,CAAC;EACnD;AACJ;AAAC,eAEctD,cAAc;AAAA"}
1
+ {"version":3,"names":["createTable","createEntity","createPartitionKey","createSortKey","createType","DynamoDbDriver","constructor","documentClient","table","name","process","env","DB_TABLE","entity","getClient","storeValue","key","input","value","JSON","stringify","ex","error","put","PK","SK","TYPE","data","storeValues","values","keys","Object","batchWrite","createEntityWriter","execute","getValue","result","get","parse","getValues","batchRead","createEntityReader","read","map","results","reduce","collection","initialKey","find","item","listValues","params","partitionKey","options","queryAll","removeValue","delete","removeValues","batchDelete"],"sources":["DynamoDbDriver.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type {\n DbDriver,\n GetValueResult,\n GetValuesResult,\n IListValuesParams,\n ListValuesResult,\n RemoveValueResult,\n RemoveValuesResult,\n StorageKey,\n StoreValueResult,\n StoreValuesResult\n} from \"@webiny/db\";\nimport { createTable } from \"~/utils/createTable.js\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport { createEntity } from \"~/store/entity.js\";\nimport { createPartitionKey, createSortKey, createType } from \"~/store/keys.js\";\n\ninterface ConstructorArgs {\n documentClient: DynamoDBDocument;\n}\n\nclass DynamoDbDriver implements DbDriver<DynamoDBDocument> {\n public readonly documentClient;\n\n public readonly table;\n public readonly entity;\n\n constructor({ documentClient }: ConstructorArgs) {\n this.documentClient = documentClient;\n this.table = createTable({\n name: process.env.DB_TABLE as string,\n documentClient\n });\n this.entity = createEntity({\n table: this.table\n });\n }\n\n public getClient() {\n return this.documentClient;\n }\n\n public async storeValue<V>(key: string, input: V): Promise<StoreValueResult<V>> {\n let value: string | undefined;\n try {\n value = JSON.stringify(input);\n } catch (ex) {\n return {\n key,\n error: ex\n };\n }\n\n try {\n await this.entity.put({\n PK: createPartitionKey(),\n SK: createSortKey({ key }),\n TYPE: createType(),\n data: {\n key,\n value\n }\n });\n\n return {\n key,\n data: input\n };\n } catch (ex) {\n return {\n key,\n error: ex\n };\n }\n }\n public async storeValues<V extends GenericRecord<StorageKey>>(\n values: V\n ): Promise<StoreValuesResult<V>> {\n const keys = Object.keys(values);\n\n const batchWrite = this.entity.createEntityWriter();\n try {\n for (const key of keys) {\n const input = values[key];\n let value: string | undefined;\n try {\n value = JSON.stringify(input);\n } catch (ex) {\n throw ex;\n }\n batchWrite.put({\n PK: createPartitionKey(),\n SK: createSortKey({ key }),\n TYPE: createType(),\n data: {\n key,\n value\n }\n });\n }\n\n await batchWrite.execute();\n return {\n keys,\n data: values\n };\n } catch (ex) {\n return {\n keys,\n error: ex\n };\n }\n }\n public async getValue<V>(key: StorageKey): Promise<GetValueResult<V>> {\n try {\n const result = await this.entity.get({\n PK: createPartitionKey(),\n SK: createSortKey({ key })\n });\n return {\n key,\n data: result?.data?.value ? JSON.parse(result.data.value) : null\n };\n } catch (ex) {\n return {\n key,\n error: ex\n };\n }\n }\n public async getValues<V extends GenericRecord<StorageKey>>(\n input: (keyof V)[]\n ): Promise<GetValuesResult<V>> {\n const keys = [...input] as string[];\n\n const batchRead = this.entity.createEntityReader({\n read: keys.map(key => {\n return {\n PK: createPartitionKey(),\n SK: createSortKey({ key })\n };\n })\n });\n\n try {\n const results = await batchRead.execute();\n const data = keys.reduce((collection, initialKey) => {\n const key = initialKey as keyof V;\n const result = results.find(item => {\n return item.PK === createPartitionKey() && item.SK === createSortKey({ key });\n });\n if (!result?.data?.value) {\n collection[key] = null;\n return collection;\n }\n try {\n collection[key] = JSON.parse(result.data.value);\n } catch {\n collection[key] = null;\n }\n\n return collection;\n }, {} as GenericRecord);\n return {\n keys,\n data\n };\n } catch (ex) {\n return {\n keys,\n error: ex\n };\n }\n }\n public async listValues<V extends GenericRecord<StorageKey>>(\n params?: IListValuesParams\n ): Promise<ListValuesResult<V>> {\n try {\n const partitionKey = createPartitionKey();\n const options = {\n ...params\n };\n const results = await this.entity.queryAll({\n partitionKey,\n options\n });\n\n const data = results.reduce((collection, item) => {\n const key = item.data.key as keyof V;\n try {\n collection[key] = JSON.parse(item.data.value);\n } catch {\n collection[key] = null;\n }\n\n return collection;\n }, {} as GenericRecord);\n\n return {\n keys: Object.keys(data),\n data\n };\n } catch (ex) {\n return {\n error: ex\n };\n }\n }\n\n public async removeValue<V>(key: StorageKey): Promise<RemoveValueResult<V>> {\n const result = await this.getValue<V>(key);\n if (result.error) {\n return {\n key,\n error: result.error\n };\n }\n try {\n await this.entity.delete({\n PK: createPartitionKey(),\n SK: createSortKey({ key })\n });\n return {\n key,\n data: result.data\n };\n } catch (ex) {\n return {\n key,\n error: ex\n };\n }\n }\n\n public async removeValues<V extends GenericRecord<StorageKey>>(\n input: (keyof V)[]\n ): Promise<RemoveValuesResult<V>> {\n const keys = [...input] as string[];\n\n const batchDelete = this.entity.createEntityWriter({\n delete: keys.map(key => {\n return {\n PK: createPartitionKey(),\n SK: createSortKey({ key })\n };\n })\n });\n\n try {\n await batchDelete.execute();\n return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AAC;IACL;IACA,IAAI;MACA,MAAM,IAAI,CAACT,MAAM,CAAC2C,MAAM,CAAC;QACrBhC,EAAE,EAAEtB,kBAAkB,CAAC,CAAC;QACxBuB,EAAE,EAAEtB,aAAa,CAAC;UAAEa;QAAI,CAAC;MAC7B,CAAC,CAAC;MACF,OAAO;QACHA,GAAG;QACHW,IAAI,EAAES,MAAM,CAACT;MACjB,CAAC;IACL,CAAC,CAAC,OAAON,EAAE,EAAE;MACT,OAAO;QACHL,GAAG;QACHM,KAAK,EAAED;MACX,CAAC;IACL;EACJ;EAEA,MAAaoC,YAAYA,CACrBxC,KAAkB,EACY;IAC9B,MAAMa,IAAI,GAAG,CAAC,GAAGb,KAAK,CAAa;IAEnC,MAAMyC,WAAW,GAAG,IAAI,CAAC7C,MAAM,CAACoB,kBAAkB,CAAC;MAC/CuB,MAAM,EAAE1B,IAAI,CAACa,GAAG,CAAC3B,GAAG,IAAI;QACpB,OAAO;UACHQ,EAAE,EAAEtB,kBAAkB,CAAC,CAAC;UACxBuB,EAAE,EAAEtB,aAAa,CAAC;YAAEa;UAAI,CAAC;QAC7B,CAAC;MACL,CAAC;IACL,CAAC,CAAC;IAEF,IAAI;MACA,MAAM0C,WAAW,CAACxB,OAAO,CAAC,CAAC;MAC3B,OAAO;QACHJ;MACJ,CAAC;IACL,CAAC,CAAC,OAAOT,EAAE,EAAE;MACT,OAAO;QACHS,IAAI;QACJR,KAAK,EAAED;MACX,CAAC;IACL;EACJ;AACJ;AAEA,eAAehB,cAAc","ignoreList":[]}
package/README.md CHANGED
@@ -1,67 +1,11 @@
1
1
  # @webiny/db-dynamodb
2
- [![](https://img.shields.io/npm/dw/webiny-data-dynamodb.svg)](https://www.npmjs.com/package/webiny-data-dynamodb)
3
- [![](https://img.shields.io/npm/v/webiny-data-dynamodb.svg)](https://www.npmjs.com/package/webiny-data-dynamodb)
4
- [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
2
 
7
- A set of frequently used data-dynamodb higher order functions.
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
8
6
 
9
- For more information, please visit
10
- [the official docs](https://github.com/doitadrian/data-dynamodb).
11
-
12
- ## Install
13
- ```
14
- yarn add @webiny/db-dynamodb
15
- ```
7
+ πŸ“˜ **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
16
8
 
9
+ ---
17
10
 
18
- ### Helper functions
19
- We have a number [helper](./src/utils) functions that ease the use of either dynamodb-toolbox, filtering, sorting or just creating proper response.
20
-
21
- #### [batchRead](./src/utils/batchRead.ts)
22
- Read a batch of records from the DynamoDB table.
23
-
24
- This function accepts [table](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Table.ts) and items, an array of objects created by [Entity.getBatch()](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts#L313).
25
-
26
- Internally it reads records until there are no more to read and returns a list of read records.
27
-
28
- #### [batchWrite](./src/utils/batchWrite.ts)
29
- Write a batch of records to the DynamoDB table.
30
-
31
- This function accepts [table](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Table.ts) and items, an array of objects created by [Entity.putBatch()](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts#L989).
32
- It also accepts a number which defines a number of items to be written in one request. DO NOT put that number over the official DynamoDB maximum.
33
-
34
- Internally it loops through the items received (in chunks of `maxChunks` parameter) and does not return anything.
35
-
36
-
37
- #### [cleanupItem and cleanupItems](./src/utils/cleanup.ts)
38
- Clean up records received from the DynamoDB table.
39
-
40
- This function accepts [entity](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts) and item to be cleaned up, in case of the cleanupItem.
41
- In case of `cleanupItems` it accepts an array of items to clean up.
42
-
43
- We use this to remove the properties that dynamodb-toolbox puts on the record automatically.
44
-
45
- #### [get](./src/utils/get.ts)
46
- Get a single record from the DynamoDB table with given keys.
47
-
48
- This function accepts [entity](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts) and keys to fetch the record by.
49
-
50
- It returns either record or null. By default, [entity.get()](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts#L281) returns a object with some meta data and `Item` property, which contains the record (or null if no record).
51
-
52
- #### [queryOne and queryAll](./src/utils/query.ts)
53
- Query the DynamoDB table for record(s) by given partition key and query options.
54
-
55
- This function accepts [entity](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Entity.ts) to perform the query on, `partitionKey` to query by and [options](https://github.com/jeremydaly/dynamodb-toolbox/blob/main/src/classes/Table.ts#L65) to define the query parameters with.
56
-
57
- The `queryAll` method accepts `limit`, a number with which you can load only a certain amount of records. The `queryOne` method does not have that property.
58
-
59
- #### [filter](./src/utils/filter.ts)
60
- Filter the DynamoDB records by given where condition.
61
-
62
- This function accepts items (records) to be filtered, a definition of fields to filter by (not required by default if no field modification is required), where conditions (eg. `{published: true, date_gte: "2021-01-01"}`) and filtering plugins.
63
-
64
- #### [sort](./src/utils/sort.ts)
65
- Sort the DynamoDB records by given sort condition.
66
-
67
- This function accepts items (records) to be sorted, sort options (eg. createdBy_ASC, id_DESC, etc.) and a definitions of fields to sort by (not required by default if no field modification is required).
11
+ _This README file is automatically generated during the publish process._
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { default as DynamoDbDriver } from "./DynamoDbDriver";
2
- export * from "./utils/createStandardEntity";
3
- export { DbItem } from "./types";
1
+ import { default as DynamoDbDriver } from "./DynamoDbDriver.js";
2
+ export * from "./utils/index.js";
3
+ export * from "./plugins/index.js";
4
+ export type { DbItem } from "./types.js";
4
5
  export { DynamoDbDriver };