@diia-inhouse/db 10.8.14 → 12.3.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 (118) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +27 -0
  2. package/dist/cli/cleanupExpiredData.js +83 -136
  3. package/dist/cli/index.d.ts +1 -0
  4. package/dist/cli/index.js +85 -100
  5. package/dist/cli/runMigration.js +64 -105
  6. package/dist/cli/syncIndexes.js +38 -77
  7. package/dist/index.d.ts +28 -0
  8. package/dist/index.js +23 -22
  9. package/dist/interfaces/database.d.ts +10 -0
  10. package/dist/interfaces/dbConfig.d.ts +37 -0
  11. package/dist/interfaces/dbConfig.js +8 -9
  12. package/dist/interfaces/errors.d.ts +43 -0
  13. package/dist/interfaces/errors.js +42 -50
  14. package/dist/interfaces/index.d.ts +15 -0
  15. package/dist/interfaces/index.js +11 -25
  16. package/dist/interfaces/metrics.d.ts +22 -0
  17. package/dist/interfaces/metrics.js +38 -19
  18. package/dist/interfaces/migrateMongoConfig.d.ts +17 -0
  19. package/dist/interfaces/models/counter.d.ts +8 -0
  20. package/dist/interfaces/models/encryptedStorage.d.ts +9 -0
  21. package/dist/interfaces/mongoStatus.d.ts +16 -0
  22. package/dist/interfaces/mongoStatus.js +11 -12
  23. package/dist/mongo.d.ts +12 -0
  24. package/dist/mongo.js +71 -89
  25. package/dist/postgres.d.ts +4 -0
  26. package/dist/postgres.js +5 -19
  27. package/dist/postgresUtils.d.ts +8 -0
  28. package/dist/postgresUtils.js +14 -18
  29. package/dist/schemas/counter.d.ts +7 -0
  30. package/dist/schemas/counter.js +19 -14
  31. package/dist/schemas/encryptedStorage.d.ts +7 -0
  32. package/dist/schemas/encryptedStorage.js +17 -15
  33. package/dist/schemas/index.d.ts +3 -0
  34. package/dist/schemas/index.js +4 -20
  35. package/dist/schemas/statusHistoryItem.d.ts +7 -0
  36. package/dist/schemas/statusHistoryItem.js +16 -10
  37. package/dist/services/counter.d.ts +19 -0
  38. package/dist/services/counter.js +70 -72
  39. package/dist/services/database.d.ts +50 -0
  40. package/dist/services/database.js +255 -281
  41. package/dist/services/encryptedStorage.d.ts +73 -0
  42. package/dist/services/encryptedStorage.js +178 -214
  43. package/dist/services/index.d.ts +4 -0
  44. package/dist/services/index.js +5 -21
  45. package/dist/services/postgresDatabase.d.ts +12 -0
  46. package/dist/services/postgresDatabase.js +20 -25
  47. package/dist/tables/counter.d.ts +4 -0
  48. package/dist/tables/counter.js +11 -12
  49. package/dist/tables/encryptedStorage.d.ts +4 -0
  50. package/dist/tables/encryptedStorage.js +12 -13
  51. package/dist/tables/index.d.ts +9 -0
  52. package/dist/tables/index.js +3 -19
  53. package/package.json +47 -48
  54. package/dist/cli/cleanupExpiredData.js.map +0 -1
  55. package/dist/cli/index.js.map +0 -1
  56. package/dist/cli/runMigration.js.map +0 -1
  57. package/dist/cli/syncIndexes.js.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/interfaces/database.js +0 -3
  60. package/dist/interfaces/database.js.map +0 -1
  61. package/dist/interfaces/dbConfig.js.map +0 -1
  62. package/dist/interfaces/errors.js.map +0 -1
  63. package/dist/interfaces/index.js.map +0 -1
  64. package/dist/interfaces/metrics.js.map +0 -1
  65. package/dist/interfaces/migrateMongoConfig.js +0 -3
  66. package/dist/interfaces/migrateMongoConfig.js.map +0 -1
  67. package/dist/interfaces/models/counter.js +0 -3
  68. package/dist/interfaces/models/counter.js.map +0 -1
  69. package/dist/interfaces/models/encryptedStorage.js +0 -3
  70. package/dist/interfaces/models/encryptedStorage.js.map +0 -1
  71. package/dist/interfaces/models/index.js +0 -19
  72. package/dist/interfaces/models/index.js.map +0 -1
  73. package/dist/interfaces/mongoStatus.js.map +0 -1
  74. package/dist/mongo.js.map +0 -1
  75. package/dist/postgres.js.map +0 -1
  76. package/dist/postgresUtils.js.map +0 -1
  77. package/dist/schemas/counter.js.map +0 -1
  78. package/dist/schemas/encryptedStorage.js.map +0 -1
  79. package/dist/schemas/index.js.map +0 -1
  80. package/dist/schemas/statusHistoryItem.js.map +0 -1
  81. package/dist/services/counter.js.map +0 -1
  82. package/dist/services/database.js.map +0 -1
  83. package/dist/services/encryptedStorage.js.map +0 -1
  84. package/dist/services/index.js.map +0 -1
  85. package/dist/services/postgresDatabase.js.map +0 -1
  86. package/dist/tables/counter.js.map +0 -1
  87. package/dist/tables/encryptedStorage.js.map +0 -1
  88. package/dist/tables/index.js.map +0 -1
  89. package/dist/types/cli/cleanupExpiredData.d.ts +0 -11
  90. package/dist/types/cli/index.d.ts +0 -2
  91. package/dist/types/cli/runMigration.d.ts +0 -11
  92. package/dist/types/cli/syncIndexes.d.ts +0 -7
  93. package/dist/types/index.d.ts +0 -5
  94. package/dist/types/interfaces/database.d.ts +0 -8
  95. package/dist/types/interfaces/dbConfig.d.ts +0 -33
  96. package/dist/types/interfaces/errors.d.ts +0 -40
  97. package/dist/types/interfaces/index.d.ts +0 -8
  98. package/dist/types/interfaces/metrics.d.ts +0 -20
  99. package/dist/types/interfaces/migrateMongoConfig.d.ts +0 -13
  100. package/dist/types/interfaces/models/counter.d.ts +0 -5
  101. package/dist/types/interfaces/models/encryptedStorage.d.ts +0 -6
  102. package/dist/types/interfaces/models/index.d.ts +0 -2
  103. package/dist/types/interfaces/mongoStatus.d.ts +0 -12
  104. package/dist/types/mongo.d.ts +0 -9
  105. package/dist/types/postgres.d.ts +0 -2
  106. package/dist/types/postgresUtils.d.ts +0 -26
  107. package/dist/types/schemas/counter.d.ts +0 -12
  108. package/dist/types/schemas/encryptedStorage.d.ts +0 -12
  109. package/dist/types/schemas/index.d.ts +0 -3
  110. package/dist/types/schemas/statusHistoryItem.d.ts +0 -3
  111. package/dist/types/services/counter.d.ts +0 -15
  112. package/dist/types/services/database.d.ts +0 -43
  113. package/dist/types/services/encryptedStorage.d.ts +0 -69
  114. package/dist/types/services/index.d.ts +0 -4
  115. package/dist/types/services/postgresDatabase.d.ts +0 -8
  116. package/dist/types/tables/counter.d.ts +0 -94
  117. package/dist/types/tables/encryptedStorage.d.ts +0 -111
  118. package/dist/types/tables/index.d.ts +0 -2
@@ -1,215 +1,179 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EncryptedStorageService = void 0;
4
- const drizzle_orm_1 = require("drizzle-orm");
5
- const errors_1 = require("@diia-inhouse/errors");
6
- const utils_1 = require("@diia-inhouse/utils");
7
- const encryptedStorage_1 = require("../tables/encryptedStorage");
1
+ import { encryptedStorage } from "../tables/encryptedStorage.js";
2
+ import { NotFoundError } from "@diia-inhouse/errors";
3
+ import { eq, inArray } from "drizzle-orm";
4
+ import { utils } from "@diia-inhouse/utils";
5
+ //#region src/services/encryptedStorage.ts
8
6
  /**
9
- * EncryptedStorageService provides CRUD operations for managing encrypted storage entries
10
- * in both Postgres and MongoDB databases. The service abstracts database implementation details
11
- * using a strategy pattern depending on the configured database adapter type.
12
- *
13
- * Suitable for storing and managing sensitive data in an encrypted manner with specific expiration time.
14
- *
15
- * This service should be wrapped in a repository.
16
- *
17
- * Register this service in the DI container with the following (MongoDB) configuration (AuthService is located in @diia-inhouse/crypto):
18
- * ```typescript
19
- * // src/deps.ts
20
- * encryptedStorage: asClass(EncryptedStorageService, { injector: () => ({ encryptedStorageModel }) }).singleton(),
21
- * auth: asClass(AuthService, { injector: () => ({ authConfig: config.auth }) }).singleton()
22
- * ```
23
- *
24
- * ```typescript
25
- * // src/config.ts
26
- * auth: {
27
- * jwk: await envService.getSecret('JWE_SECRET_DATA_JWK'),
28
- * }
29
- * ```
30
- *
31
- * ```typescript
32
- * // src/models/encryptedStorage.ts
33
- * import { EncryptedStorage, Model, encryptedStorageSchema, model, models } from '@diia-inhouse/db'
34
- *
35
- * export default (models.EncryptedStorage as Model<EncryptedStorage>) || model('EncryptedStorage', encryptedStorageSchema)
36
- * ```
37
- *
38
- * Use the following command to generate a JWE secret data JWK:
39
- * node -e "const crypto = require('crypto'); const { privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); const jwk = privateKey.export({ format: 'jwk' }); jwk.use = 'enc'; console.log(JSON.stringify(jwk));"
40
- * ```typescript
41
- * // .env.example
42
- * JWE_SECRET_DATA_JWK={your-jwk-here}
43
- * ```
44
- */
45
- class EncryptedStorageService {
46
- logger;
47
- auth;
48
- envService;
49
- databaseAdapter;
50
- encryptedStorageModel;
51
- postgresDatabase;
52
- saveEntityStrategy = {
53
- postgres: async (storageItem) => {
54
- const result = await this.getPostgresDatabase()
55
- .insert(encryptedStorage_1.encryptedStorage)
56
- .values(storageItem)
57
- .returning()
58
- .then((rows) => rows[0]);
59
- return result.id;
60
- },
61
- mongo: async (storageItem) => {
62
- const result = await this.getModel().create(storageItem);
63
- return result._id.toString();
64
- },
65
- };
66
- updateEntityStrategy = {
67
- postgres: async (id, updateData) => {
68
- await this.getPostgresDatabase().update(encryptedStorage_1.encryptedStorage).set(updateData).where((0, drizzle_orm_1.eq)(encryptedStorage_1.encryptedStorage.id, id));
69
- },
70
- mongo: async (id, updateData) => {
71
- await this.getModel().findByIdAndUpdate(id, updateData);
72
- },
73
- };
74
- findEntityStrategy = {
75
- postgres: async (id) => {
76
- return await this.getPostgresDatabase()
77
- .select()
78
- .from(encryptedStorage_1.encryptedStorage)
79
- .where((0, drizzle_orm_1.eq)(encryptedStorage_1.encryptedStorage.id, id))
80
- .then((rows) => rows[0]);
81
- },
82
- mongo: async (id, options) => {
83
- return await this.getModel().findById(id, undefined, options);
84
- },
85
- };
86
- deleteManyStrategy = {
87
- postgres: async (ids) => {
88
- const result = await this.getPostgresDatabase().delete(encryptedStorage_1.encryptedStorage).where((0, drizzle_orm_1.inArray)(encryptedStorage_1.encryptedStorage.id, ids));
89
- return result.rowCount;
90
- },
91
- mongo: async (ids) => {
92
- const result = await this.getModel().deleteMany({ _id: { $in: ids } });
93
- return result.deletedCount;
94
- },
95
- };
96
- removeEntityStrategy = {
97
- postgres: async (id) => {
98
- return await this.getPostgresDatabase()
99
- .delete(encryptedStorage_1.encryptedStorage)
100
- .where((0, drizzle_orm_1.eq)(encryptedStorage_1.encryptedStorage.id, id))
101
- .returning()
102
- .then((rows) => rows[0]);
103
- },
104
- mongo: async (id) => {
105
- return await this.getModel().findOneAndDelete({ _id: id });
106
- },
107
- };
108
- findExpirationStrategy = {
109
- postgres: async (id) => {
110
- return await this.getPostgresDatabase()
111
- .select({ expiresAt: encryptedStorage_1.encryptedStorage.expiresAt })
112
- .from(encryptedStorage_1.encryptedStorage)
113
- .where((0, drizzle_orm_1.eq)(encryptedStorage_1.encryptedStorage.id, id))
114
- .then((rows) => rows[0].expiresAt);
115
- },
116
- mongo: async (id) => {
117
- const result = await this.getModel().findById(id, { expiresAt: 1 });
118
- return result?.expiresAt;
119
- },
120
- };
121
- constructor(logger, auth, envService, databaseAdapter, encryptedStorageModel = null, postgresDatabase = null) {
122
- this.logger = logger;
123
- this.auth = auth;
124
- this.envService = envService;
125
- this.databaseAdapter = databaseAdapter;
126
- this.encryptedStorageModel = encryptedStorageModel;
127
- this.postgresDatabase = postgresDatabase;
128
- }
129
- async save(data, expiration) {
130
- const encryptedData = await this.auth.encryptJWE(utils_1.utils.encodeObjectToBase64(data));
131
- const storageItem = {
132
- data: encryptedData,
133
- expiresAt: new Date(Date.now() + expiration),
134
- };
135
- if (!this.envService.isProd()) {
136
- storageItem.source = data;
137
- }
138
- return await this.saveEntityStrategy[this.databaseAdapter](storageItem);
139
- }
140
- async get(id, options = {}) {
141
- const storageItem = await this.getStorageItemById(id, options);
142
- const decryptedData = await this.auth.decryptJWE(storageItem.data);
143
- return await utils_1.utils.decodeObjectFromBase64(decryptedData);
144
- }
145
- async getSafe(id, options = {}) {
146
- try {
147
- return await this.get(id, options);
148
- }
149
- catch (err) {
150
- this.logger.log('Unable to retrieve data from encrypted storage', { err });
151
- return undefined;
152
- }
153
- }
154
- async update(id, data) {
155
- const storageItem = await this.getStorageItemById(id);
156
- const encryptedData = await this.auth.encryptJWE(utils_1.utils.encodeObjectToBase64(data));
157
- storageItem.data = encryptedData;
158
- if (!this.envService.isProd()) {
159
- storageItem.source = data;
160
- }
161
- await this.updateEntityStrategy[this.databaseAdapter](id, storageItem);
162
- }
163
- async remove(id) {
164
- const storageItem = await this.removeEntityStrategy[this.databaseAdapter](id);
165
- if (!storageItem) {
166
- this.logger.info('Encrypted data is not removed from storage: data not found', { id });
167
- return;
168
- }
169
- this.logger.info('Encrypted data removed from storage', { id });
170
- }
171
- async deleteMany(ids) {
172
- const deletedCount = await this.deleteManyStrategy[this.databaseAdapter](ids);
173
- this.logger.info(`Encrypted data removed from storage: ${deletedCount}`);
174
- }
175
- async setExpiration(id, expiration) {
176
- const expiresAt = await this.findExpirationStrategy[this.databaseAdapter](id);
177
- if (!expiresAt) {
178
- this.logger.error('Encrypted data is not found in storage', { id });
179
- throw new errors_1.NotFoundError('Missing data');
180
- }
181
- const newExpiresAt = new Date(Date.now() + expiration);
182
- await this.updateEntityStrategy[this.databaseAdapter](id, { expiresAt: newExpiresAt });
183
- this.logger.info('Updated encrypted data expiration date', { id });
184
- }
185
- async getExpiration(id) {
186
- const expiresAt = await this.findExpirationStrategy[this.databaseAdapter](id);
187
- if (!expiresAt) {
188
- this.logger.error('Encrypted data is not found in storage', { id });
189
- throw new errors_1.NotFoundError('Missing data');
190
- }
191
- return expiresAt;
192
- }
193
- async getStorageItemById(id, options = {}) {
194
- const storageItem = await this.findEntityStrategy[this.databaseAdapter](id, options);
195
- if (!storageItem) {
196
- this.logger.error('Encrypted data is not found in storage', { id });
197
- throw new errors_1.NotFoundError('Missing data');
198
- }
199
- return storageItem;
200
- }
201
- getModel() {
202
- if (!this.encryptedStorageModel) {
203
- throw new Error('Encrypted storage model is not provided');
204
- }
205
- return this.encryptedStorageModel;
206
- }
207
- getPostgresDatabase() {
208
- if (!this.postgresDatabase) {
209
- throw new Error('Postgres database is not provided');
210
- }
211
- return this.postgresDatabase;
212
- }
213
- }
214
- exports.EncryptedStorageService = EncryptedStorageService;
215
- //# sourceMappingURL=encryptedStorage.js.map
7
+ * EncryptedStorageService provides CRUD operations for managing encrypted storage entries
8
+ * in both Postgres and MongoDB databases. The service abstracts database implementation details
9
+ * using a strategy pattern depending on the configured database adapter type.
10
+ *
11
+ * Suitable for storing and managing sensitive data in an encrypted manner with specific expiration time.
12
+ *
13
+ * This service should be wrapped in a repository.
14
+ *
15
+ * Register this service in the DI container with the following (MongoDB) configuration (AuthService is located in @diia-inhouse/crypto):
16
+ * ```typescript
17
+ * // src/deps.ts
18
+ * encryptedStorage: asClass(EncryptedStorageService, { injector: () => ({ encryptedStorageModel }) }).singleton(),
19
+ * auth: asClass(AuthService, { injector: () => ({ authConfig: config.auth }) }).singleton()
20
+ * ```
21
+ *
22
+ * ```typescript
23
+ * // src/config.ts
24
+ * auth: {
25
+ * jwk: await envService.getSecret('JWE_SECRET_DATA_JWK'),
26
+ * }
27
+ * ```
28
+ *
29
+ * ```typescript
30
+ * // src/models/encryptedStorage.ts
31
+ * import { EncryptedStorage, Model, encryptedStorageSchema, model, models } from '@diia-inhouse/db'
32
+ *
33
+ * export default (models.EncryptedStorage as Model<EncryptedStorage>) || model('EncryptedStorage', encryptedStorageSchema)
34
+ * ```
35
+ *
36
+ * Use the following command to generate a JWE secret data JWK:
37
+ * node -e "const crypto = require('crypto'); const { privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); const jwk = privateKey.export({ format: 'jwk' }); jwk.use = 'enc'; console.log(JSON.stringify(jwk));"
38
+ * ```typescript
39
+ * // .env.example
40
+ * JWE_SECRET_DATA_JWK={your-jwk-here}
41
+ * ```
42
+ */
43
+ var EncryptedStorageService = class {
44
+ logger;
45
+ auth;
46
+ envService;
47
+ databaseAdapter;
48
+ encryptedStorageModel;
49
+ postgresDatabase;
50
+ saveEntityStrategy = {
51
+ postgres: async (storageItem) => {
52
+ return (await this.getPostgresDatabase().insert(encryptedStorage).values(storageItem).returning().then((rows) => rows[0])).id;
53
+ },
54
+ mongo: async (storageItem) => {
55
+ return (await this.getModel().create(storageItem))._id.toString();
56
+ }
57
+ };
58
+ updateEntityStrategy = {
59
+ postgres: async (id, updateData) => {
60
+ await this.getPostgresDatabase().update(encryptedStorage).set(updateData).where(eq(encryptedStorage.id, id));
61
+ },
62
+ mongo: async (id, updateData) => {
63
+ await this.getModel().findByIdAndUpdate(id, updateData);
64
+ }
65
+ };
66
+ findEntityStrategy = {
67
+ postgres: async (id) => {
68
+ return await this.getPostgresDatabase().select().from(encryptedStorage).where(eq(encryptedStorage.id, id)).then((rows) => rows[0]);
69
+ },
70
+ mongo: async (id, options) => {
71
+ return await this.getModel().findById(id, void 0, options);
72
+ }
73
+ };
74
+ deleteManyStrategy = {
75
+ postgres: async (ids) => {
76
+ return (await this.getPostgresDatabase().delete(encryptedStorage).where(inArray(encryptedStorage.id, ids))).rowCount;
77
+ },
78
+ mongo: async (ids) => {
79
+ return (await this.getModel().deleteMany({ _id: { $in: ids } })).deletedCount;
80
+ }
81
+ };
82
+ removeEntityStrategy = {
83
+ postgres: async (id) => {
84
+ return await this.getPostgresDatabase().delete(encryptedStorage).where(eq(encryptedStorage.id, id)).returning().then((rows) => rows[0]);
85
+ },
86
+ mongo: async (id) => {
87
+ return await this.getModel().findOneAndDelete({ _id: id });
88
+ }
89
+ };
90
+ findExpirationStrategy = {
91
+ postgres: async (id) => {
92
+ return await this.getPostgresDatabase().select({ expiresAt: encryptedStorage.expiresAt }).from(encryptedStorage).where(eq(encryptedStorage.id, id)).then((rows) => rows[0].expiresAt);
93
+ },
94
+ mongo: async (id) => {
95
+ return (await this.getModel().findById(id, { expiresAt: 1 }))?.expiresAt;
96
+ }
97
+ };
98
+ constructor(logger, auth, envService, databaseAdapter, encryptedStorageModel = null, postgresDatabase = null) {
99
+ this.logger = logger;
100
+ this.auth = auth;
101
+ this.envService = envService;
102
+ this.databaseAdapter = databaseAdapter;
103
+ this.encryptedStorageModel = encryptedStorageModel;
104
+ this.postgresDatabase = postgresDatabase;
105
+ }
106
+ async save(data, expiration) {
107
+ const storageItem = {
108
+ data: await this.auth.encryptJWE(utils.encodeObjectToBase64(data)),
109
+ expiresAt: new Date(Date.now() + expiration)
110
+ };
111
+ if (!this.envService.isProd()) storageItem.source = data;
112
+ return await this.saveEntityStrategy[this.databaseAdapter](storageItem);
113
+ }
114
+ async get(id, options = {}) {
115
+ const storageItem = await this.getStorageItemById(id, options);
116
+ const decryptedData = await this.auth.decryptJWE(storageItem.data);
117
+ return await utils.decodeObjectFromBase64(decryptedData);
118
+ }
119
+ async getSafe(id, options = {}) {
120
+ try {
121
+ return await this.get(id, options);
122
+ } catch (err) {
123
+ this.logger.log("Unable to retrieve data from encrypted storage", { err });
124
+ return;
125
+ }
126
+ }
127
+ async update(id, data) {
128
+ const storageItem = await this.getStorageItemById(id);
129
+ storageItem.data = await this.auth.encryptJWE(utils.encodeObjectToBase64(data));
130
+ if (!this.envService.isProd()) storageItem.source = data;
131
+ await this.updateEntityStrategy[this.databaseAdapter](id, storageItem);
132
+ }
133
+ async remove(id) {
134
+ if (!await this.removeEntityStrategy[this.databaseAdapter](id)) {
135
+ this.logger.info("Encrypted data is not removed from storage: data not found", { id });
136
+ return;
137
+ }
138
+ this.logger.info("Encrypted data removed from storage", { id });
139
+ }
140
+ async deleteMany(ids) {
141
+ const deletedCount = await this.deleteManyStrategy[this.databaseAdapter](ids);
142
+ this.logger.info(`Encrypted data removed from storage: ${deletedCount}`);
143
+ }
144
+ async setExpiration(id, expiration) {
145
+ if (!await this.findExpirationStrategy[this.databaseAdapter](id)) {
146
+ this.logger.error("Encrypted data is not found in storage", { id });
147
+ throw new NotFoundError("Missing data");
148
+ }
149
+ const newExpiresAt = new Date(Date.now() + expiration);
150
+ await this.updateEntityStrategy[this.databaseAdapter](id, { expiresAt: newExpiresAt });
151
+ this.logger.info("Updated encrypted data expiration date", { id });
152
+ }
153
+ async getExpiration(id) {
154
+ const expiresAt = await this.findExpirationStrategy[this.databaseAdapter](id);
155
+ if (!expiresAt) {
156
+ this.logger.error("Encrypted data is not found in storage", { id });
157
+ throw new NotFoundError("Missing data");
158
+ }
159
+ return expiresAt;
160
+ }
161
+ async getStorageItemById(id, options = {}) {
162
+ const storageItem = await this.findEntityStrategy[this.databaseAdapter](id, options);
163
+ if (!storageItem) {
164
+ this.logger.error("Encrypted data is not found in storage", { id });
165
+ throw new NotFoundError("Missing data");
166
+ }
167
+ return storageItem;
168
+ }
169
+ getModel() {
170
+ if (!this.encryptedStorageModel) throw new Error("Encrypted storage model is not provided");
171
+ return this.encryptedStorageModel;
172
+ }
173
+ getPostgresDatabase() {
174
+ if (!this.postgresDatabase) throw new Error("Postgres database is not provided");
175
+ return this.postgresDatabase;
176
+ }
177
+ };
178
+ //#endregion
179
+ export { EncryptedStorageService };
@@ -0,0 +1,4 @@
1
+ import { DatabaseService } from "./database.js";
2
+ import { PostgresDatabaseService } from "./postgresDatabase.js";
3
+ import { EncryptedStorageService } from "./encryptedStorage.js";
4
+ import { CounterService } from "./counter.js";
@@ -1,21 +1,5 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./database"), exports);
18
- __exportStar(require("./postgresDatabase"), exports);
19
- __exportStar(require("./encryptedStorage"), exports);
20
- __exportStar(require("./counter"), exports);
21
- //# sourceMappingURL=index.js.map
1
+ import "./database.js";
2
+ import "./postgresDatabase.js";
3
+ import "./encryptedStorage.js";
4
+ import "./counter.js";
5
+ export {};
@@ -0,0 +1,12 @@
1
+ import { DatabaseAdapterType, PostgresDatabase } from "../interfaces/database.js";
2
+ import { OnInit } from "@diia-inhouse/types";
3
+
4
+ //#region src/services/postgresDatabase.d.ts
5
+ declare class PostgresDatabaseService implements OnInit {
6
+ private readonly databaseAdapter;
7
+ private readonly postgresDatabase;
8
+ constructor(databaseAdapter: DatabaseAdapterType, postgresDatabase: PostgresDatabase);
9
+ onInit(): Promise<void>;
10
+ }
11
+ //#endregion
12
+ export { PostgresDatabaseService };
@@ -1,25 +1,20 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PostgresDatabaseService = void 0;
4
- const errors_1 = require("@diia-inhouse/errors");
5
- class PostgresDatabaseService {
6
- databaseAdapter;
7
- postgresDatabase;
8
- constructor(databaseAdapter, postgresDatabase) {
9
- this.databaseAdapter = databaseAdapter;
10
- this.postgresDatabase = postgresDatabase;
11
- }
12
- async onInit() {
13
- if (this.databaseAdapter !== 'postgres') {
14
- return;
15
- }
16
- try {
17
- await this.postgresDatabase.execute('SELECT 1');
18
- }
19
- catch (err) {
20
- throw new errors_1.DatabaseError('Failed to connect to postgres database', { err });
21
- }
22
- }
23
- }
24
- exports.PostgresDatabaseService = PostgresDatabaseService;
25
- //# sourceMappingURL=postgresDatabase.js.map
1
+ import { DatabaseError } from "@diia-inhouse/errors";
2
+ //#region src/services/postgresDatabase.ts
3
+ var PostgresDatabaseService = class {
4
+ databaseAdapter;
5
+ postgresDatabase;
6
+ constructor(databaseAdapter, postgresDatabase) {
7
+ this.databaseAdapter = databaseAdapter;
8
+ this.postgresDatabase = postgresDatabase;
9
+ }
10
+ async onInit() {
11
+ if (this.databaseAdapter !== "postgres") return;
12
+ try {
13
+ await this.postgresDatabase.execute("SELECT 1");
14
+ } catch (err) {
15
+ throw new DatabaseError("Failed to connect to postgres database", { err });
16
+ }
17
+ }
18
+ };
19
+ //#endregion
20
+ export { PostgresDatabaseService };
@@ -0,0 +1,4 @@
1
+ //#region src/tables/counter.d.ts
2
+ declare const counter: any;
3
+ //#endregion
4
+ export { counter };
@@ -1,12 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.counter = void 0;
4
- const pg_core_1 = require("drizzle-orm/pg-core");
5
- const postgresUtils_1 = require("../postgresUtils");
6
- exports.counter = (0, pg_core_1.pgTable)('counter', {
7
- code: (0, pg_core_1.varchar)().notNull(),
8
- value: (0, pg_core_1.integer)().notNull(),
9
- date: (0, pg_core_1.timestamp)().notNull(),
10
- ...postgresUtils_1.timestamps,
11
- }, (table) => [(0, pg_core_1.unique)('counter_code_date_idx').on(table.code, table.date)]);
12
- //# sourceMappingURL=counter.js.map
1
+ import { timestamps } from "../postgresUtils.js";
2
+ import { integer, pgTable, timestamp, unique, varchar } from "drizzle-orm/pg-core";
3
+ //#region src/tables/counter.ts
4
+ const counter = pgTable("counter", {
5
+ code: varchar().notNull(),
6
+ value: integer().notNull(),
7
+ date: timestamp().notNull(),
8
+ ...timestamps
9
+ }, (table) => [unique("counter_code_date_idx").on(table.code, table.date)]);
10
+ //#endregion
11
+ export { counter };
@@ -0,0 +1,4 @@
1
+ //#region src/tables/encryptedStorage.d.ts
2
+ declare const encryptedStorage: any;
3
+ //#endregion
4
+ export { encryptedStorage };
@@ -1,14 +1,13 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.encryptedStorage = void 0;
4
- const pg_core_1 = require("drizzle-orm/pg-core");
5
- const types_1 = require("@diia-inhouse/types");
6
- const postgresUtils_1 = require("../postgresUtils");
7
- exports.encryptedStorage = (0, pg_core_1.pgTable)('encrypted_storage', {
8
- id: (0, pg_core_1.uuid)('id').primaryKey().defaultRandom(),
9
- data: (0, pg_core_1.text)('data').notNull(),
10
- expiresAt: (0, postgresUtils_1.expiringTimestamp)('expires_at', { expireAfterSeconds: types_1.DurationS.Day }).notNull(),
11
- source: (0, pg_core_1.jsonb)('source'),
12
- ...postgresUtils_1.timestamps,
1
+ import { expiringTimestamp, timestamps } from "../postgresUtils.js";
2
+ import { DurationS } from "@diia-inhouse/types";
3
+ import { jsonb, pgTable, text, uuid } from "drizzle-orm/pg-core";
4
+ //#region src/tables/encryptedStorage.ts
5
+ const encryptedStorage = pgTable("encrypted_storage", {
6
+ id: uuid("id").primaryKey().defaultRandom(),
7
+ data: text("data").notNull(),
8
+ expiresAt: expiringTimestamp("expires_at", { expireAfterSeconds: DurationS.Day }).notNull(),
9
+ source: jsonb("source"),
10
+ ...timestamps
13
11
  });
14
- //# sourceMappingURL=encryptedStorage.js.map
12
+ //#endregion
13
+ export { encryptedStorage };
@@ -0,0 +1,9 @@
1
+ import { counter } from "./counter.js";
2
+ import { encryptedStorage } from "./encryptedStorage.js";
3
+
4
+ //#region src/tables/index.d.ts
5
+ declare namespace index_d_exports {
6
+ export { counter, encryptedStorage };
7
+ }
8
+ //#endregion
9
+ export { index_d_exports };
@@ -1,19 +1,3 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./counter"), exports);
18
- __exportStar(require("./encryptedStorage"), exports);
19
- //# sourceMappingURL=index.js.map
1
+ import "./encryptedStorage.js";
2
+ import "./counter.js";
3
+ export {};