@diia-inhouse/db 10.8.12 → 12.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -0,0 +1,12 @@
1
+ import { MigrateMongoConfig } from "./interfaces/migrateMongoConfig.js";
2
+ //#region src/mongo.d.ts
3
+ declare const MongoHelper: {
4
+ getMigrateMongoConfig(): Promise<MigrateMongoConfig>;
5
+ buildMongoUrl(user: string | null, password: string | null): string;
6
+ getMongoErrorDupField(msg: string, fields: string[]): string | undefined;
7
+ handleMongoUniqError(err: Error & {
8
+ code?: number;
9
+ }, params: Record<string, unknown>, uniqFieldNames: string[], modelName: string): void;
10
+ };
11
+ //#endregion
12
+ export { MongoHelper };
package/dist/mongo.js CHANGED
@@ -1,90 +1,72 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
1
+ import "./interfaces/errors.js";
2
+ import "./interfaces/index.js";
3
+ import { DatabaseError, UnprocessableEntityError } from "@diia-inhouse/errors";
4
+ import { DiiaLogger } from "@diia-inhouse/diia-logger";
5
+ import { EnvService } from "@diia-inhouse/env";
6
+ //#region src/mongo.ts
7
+ const MongoHelper = {
8
+ async getMigrateMongoConfig() {
9
+ const logger = new DiiaLogger();
10
+ const envService = new EnvService(logger);
11
+ await envService.init();
12
+ const originalExit = process.exit.bind(process);
13
+ process.exit = (code) => {
14
+ logger.info("Destroying the Env service on process exit...", { code });
15
+ return envService.onDestroy().then(() => {
16
+ logger.info("Env service destroyed, exiting the process...", { code });
17
+ return originalExit(code);
18
+ }).catch((err) => {
19
+ logger.error("Env service destroy error", { err });
20
+ originalExit(code);
21
+ });
22
+ };
23
+ const user = await envService.getSecret("MONGO_USER", {
24
+ accessor: "username",
25
+ nullable: true
26
+ });
27
+ const password = await envService.getSecret("MONGO_PASSWORD", {
28
+ accessor: "password",
29
+ nullable: true
30
+ });
31
+ return {
32
+ mongodb: {
33
+ url: this.buildMongoUrl(user, password),
34
+ databaseName: `${process.env.MONGO_DATABASE}`
35
+ },
36
+ migrationsDir: "migrations",
37
+ changelogCollectionName: "migrations",
38
+ migrationFileExtension: ".ts",
39
+ useFileHash: false,
40
+ moduleSystem: "commonjs"
41
+ };
42
+ },
43
+ buildMongoUrl(user, password) {
44
+ let mongoUrl = "mongodb://";
45
+ if (user && password) mongoUrl += `${user}:${password}@`;
46
+ mongoUrl += `${process.env.MONGO_HOST}:${process.env.MONGO_PORT}/`;
47
+ if (process.env.MONGO_AUTH_SOURCE) mongoUrl += process.env.MONGO_AUTH_SOURCE;
48
+ const query = [];
49
+ if (process.env.MONGO_REPLICA_SET) query.push(`replicaSet=${process.env.MONGO_REPLICA_SET}`);
50
+ if (process.env.MONGO_AUTH_MECHANISM) query.push(`authMechanism=${process.env.MONGO_AUTH_MECHANISM}`);
51
+ if (query.length > 0) mongoUrl += `?${query.join("&")}`;
52
+ return mongoUrl;
53
+ },
54
+ getMongoErrorDupField(msg, fields) {
55
+ for (const field of fields) if (new RegExp(`${field}_[0-9] dup key`).test(msg)) return field;
56
+ },
57
+ handleMongoUniqError(err, params, uniqFieldNames, modelName) {
58
+ if (err.name === "MongoError" && err.code === 11e3) {
59
+ const field = MongoHelper.getMongoErrorDupField(err.message, uniqFieldNames);
60
+ if (field) throw new UnprocessableEntityError(`${modelName} with ${field} '${String(params[field])}' already exists`, {
61
+ field,
62
+ message: `${field} field unique constraint`,
63
+ type: "unique",
64
+ value: params[field]
65
+ });
66
+ throw new Error(`Unexpected error while entity processing. ${err.message}`);
67
+ }
68
+ throw new DatabaseError(err.toString());
69
+ }
4
70
  };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MongoHelper = void 0;
7
- const diia_logger_1 = __importDefault(require("@diia-inhouse/diia-logger"));
8
- const env_1 = require("@diia-inhouse/env");
9
- const errors_1 = require("@diia-inhouse/errors");
10
- const interfaces_1 = require("./interfaces");
11
- exports.MongoHelper = {
12
- async getMigrateMongoConfig() {
13
- const logger = new diia_logger_1.default();
14
- const envService = new env_1.EnvService(logger);
15
- await envService.init();
16
- const originalExit = process.exit;
17
- process.exit = (code) => {
18
- logger.info('Destroying the Env service on process exit...', { code });
19
- return envService
20
- .onDestroy()
21
- .then(() => {
22
- logger.info('Env service destroyed, exiting the process...', { code });
23
- return originalExit(code);
24
- })
25
- .catch((err) => {
26
- logger.error('Env service destroy error', { err });
27
- originalExit(code);
28
- });
29
- };
30
- const user = await envService.getSecret('MONGO_USER', { accessor: 'username', nullable: true });
31
- const password = await envService.getSecret('MONGO_PASSWORD', { accessor: 'password', nullable: true });
32
- return {
33
- mongodb: {
34
- url: this.buildMongoUrl(user, password),
35
- databaseName: `${process.env.MONGO_DATABASE}`,
36
- },
37
- migrationsDir: 'migrations',
38
- changelogCollectionName: 'migrations',
39
- migrationFileExtension: '.ts',
40
- useFileHash: false,
41
- moduleSystem: 'commonjs',
42
- };
43
- },
44
- buildMongoUrl(user, password) {
45
- let mongoUrl = 'mongodb://';
46
- if (user && password) {
47
- mongoUrl += `${user}:${password}@`;
48
- }
49
- mongoUrl += `${process.env.MONGO_HOST}:${process.env.MONGO_PORT}/`;
50
- if (process.env.MONGO_AUTH_SOURCE) {
51
- mongoUrl += process.env.MONGO_AUTH_SOURCE;
52
- }
53
- const query = [];
54
- if (process.env.MONGO_REPLICA_SET) {
55
- query.push(`replicaSet=${process.env.MONGO_REPLICA_SET}`);
56
- }
57
- if (process.env.MONGO_AUTH_MECHANISM) {
58
- query.push(`authMechanism=${process.env.MONGO_AUTH_MECHANISM}`);
59
- }
60
- if (query.length > 0) {
61
- mongoUrl += `?${query.join('&')}`;
62
- }
63
- return mongoUrl;
64
- },
65
- getMongoErrorDupField(msg, fields) {
66
- for (const field of fields) {
67
- // eslint-disable-next-line security/detect-non-literal-regexp
68
- const fieldRegExp = new RegExp(`${field}_[0-9] dup key`); // nosemgrep: eslint.detect-non-literal-regexp
69
- if (fieldRegExp.test(msg)) {
70
- return field;
71
- }
72
- }
73
- },
74
- handleMongoUniqError(err, params, uniqFieldNames, modelName) {
75
- if (err.name === 'MongoError' && err.code === interfaces_1.MongoDBErrorCode.DuplicateKey) {
76
- const field = exports.MongoHelper.getMongoErrorDupField(err.message, uniqFieldNames);
77
- if (field) {
78
- throw new errors_1.UnprocessableEntityError(`${modelName} with ${field} '${params[field]}' already exists`, {
79
- field,
80
- message: `${field} field unique constraint`,
81
- type: 'unique',
82
- value: params[field],
83
- });
84
- }
85
- throw new Error(`Unexpected error while entity processing. ${err.message}`);
86
- }
87
- throw new errors_1.DatabaseError(err.toString());
88
- },
89
- };
90
- //# sourceMappingURL=mongo.js.map
71
+ //#endregion
72
+ export { MongoHelper };
@@ -0,0 +1,4 @@
1
+ import { counter } from "./tables/counter.js";
2
+ import { encryptedStorage } from "./tables/encryptedStorage.js";
3
+ import { expiringTimestamp, timestamps } from "./postgresUtils.js";
4
+ export { counter, encryptedStorage, expiringTimestamp, timestamps };
package/dist/postgres.js CHANGED
@@ -1,19 +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("./tables"), exports);
18
- __exportStar(require("./postgresUtils"), exports);
19
- //# sourceMappingURL=postgres.js.map
1
+ import { expiringTimestamp, timestamps } from "./postgresUtils.js";
2
+ import { encryptedStorage } from "./tables/encryptedStorage.js";
3
+ import { counter } from "./tables/counter.js";
4
+ import "./tables/index.js";
5
+ export { counter, encryptedStorage, expiringTimestamp, timestamps };
@@ -0,0 +1,8 @@
1
+ //#region src/postgresUtils.d.ts
2
+ declare const timestamps: {
3
+ createdAt: any;
4
+ updatedAt: any;
5
+ };
6
+ declare const expiringTimestamp: any;
7
+ //#endregion
8
+ export { expiringTimestamp, timestamps };
@@ -1,20 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.expiringTimestamp = exports.timestamps = void 0;
4
- const pg_core_1 = require("drizzle-orm/pg-core");
5
- exports.timestamps = {
6
- createdAt: (0, pg_core_1.timestamp)('created_at').defaultNow().notNull(),
7
- updatedAt: (0, pg_core_1.timestamp)('updated_at')
8
- .defaultNow()
9
- .$onUpdate(() => new Date())
10
- .notNull(),
1
+ import { customType, timestamp } from "drizzle-orm/pg-core";
2
+ //#region src/postgresUtils.ts
3
+ const timestamps = {
4
+ createdAt: timestamp("created_at").defaultNow().notNull(),
5
+ updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
11
6
  };
12
- exports.expiringTimestamp = (0, pg_core_1.customType)({
13
- dataType() {
14
- return `timestamp`;
15
- },
16
- fromDriver(value) {
17
- return new Date(value);
18
- },
7
+ const expiringTimestamp = customType({
8
+ dataType() {
9
+ return `timestamp`;
10
+ },
11
+ fromDriver(value) {
12
+ return new Date(value);
13
+ }
19
14
  });
20
- //# sourceMappingURL=postgresUtils.js.map
15
+ //#endregion
16
+ export { expiringTimestamp, timestamps };
@@ -0,0 +1,7 @@
1
+ import { Counter } from "../interfaces/models/counter.js";
2
+ import { Schema } from "mongoose";
3
+
4
+ //#region src/schemas/counter.d.ts
5
+ declare const counterSchema: Schema<Counter>;
6
+ //#endregion
7
+ export { counterSchema };
@@ -1,14 +1,19 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.counterSchema = void 0;
4
- const mongoose_1 = require("mongoose");
5
- const counterSchema = new mongoose_1.Schema({
6
- code: { type: String, required: true },
7
- value: { type: Number, required: true },
8
- date: { type: Date },
9
- }, {
10
- timestamps: true,
11
- });
12
- exports.counterSchema = counterSchema;
13
- counterSchema.index({ code: 1, date: -1 }, { unique: true });
14
- //# sourceMappingURL=counter.js.map
1
+ import { Schema } from "mongoose";
2
+ //#region src/schemas/counter.ts
3
+ const counterSchema = new Schema({
4
+ code: {
5
+ type: String,
6
+ required: true
7
+ },
8
+ value: {
9
+ type: Number,
10
+ required: true
11
+ },
12
+ date: { type: Date }
13
+ }, { timestamps: true });
14
+ counterSchema.index({
15
+ code: 1,
16
+ date: -1
17
+ }, { unique: true });
18
+ //#endregion
19
+ export { counterSchema };
@@ -0,0 +1,7 @@
1
+ import { EncryptedStorage } from "../interfaces/models/encryptedStorage.js";
2
+ import { Schema } from "mongoose";
3
+
4
+ //#region src/schemas/encryptedStorage.d.ts
5
+ declare const encryptedStorageSchema: Schema<EncryptedStorage>;
6
+ //#endregion
7
+ export { encryptedStorageSchema };
@@ -1,15 +1,17 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.encryptedStorageSchema = void 0;
4
- const mongoose_1 = require("mongoose");
5
- const types_1 = require("@diia-inhouse/types");
6
- const encryptedStorageSchema = new mongoose_1.Schema({
7
- data: { type: String, required: true },
8
- expiresAt: { type: Date, required: true },
9
- source: { type: {} },
10
- }, {
11
- timestamps: true,
12
- });
13
- exports.encryptedStorageSchema = encryptedStorageSchema;
14
- encryptedStorageSchema.index({ expiresAt: 1 }, { expireAfterSeconds: types_1.DurationS.Day });
15
- //# sourceMappingURL=encryptedStorage.js.map
1
+ import { Schema } from "mongoose";
2
+ import { DurationS } from "@diia-inhouse/types";
3
+ //#region src/schemas/encryptedStorage.ts
4
+ const encryptedStorageSchema = new Schema({
5
+ data: {
6
+ type: String,
7
+ required: true
8
+ },
9
+ expiresAt: {
10
+ type: Date,
11
+ required: true
12
+ },
13
+ source: { type: {} }
14
+ }, { timestamps: true });
15
+ encryptedStorageSchema.index({ expiresAt: 1 }, { expireAfterSeconds: DurationS.Day });
16
+ //#endregion
17
+ export { encryptedStorageSchema };
@@ -0,0 +1,3 @@
1
+ import { counterSchema } from "./counter.js";
2
+ import { encryptedStorageSchema } from "./encryptedStorage.js";
3
+ import { createStatusHistoryItemSchema } from "./statusHistoryItem.js";
@@ -1,20 +1,4 @@
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
- __exportStar(require("./statusHistoryItem"), exports);
20
- //# sourceMappingURL=index.js.map
1
+ import "./counter.js";
2
+ import "./encryptedStorage.js";
3
+ import "./statusHistoryItem.js";
4
+ export {};
@@ -0,0 +1,7 @@
1
+ import { Schema } from "mongoose";
2
+ import { StatusHistoryItem } from "@diia-inhouse/types";
3
+
4
+ //#region src/schemas/statusHistoryItem.d.ts
5
+ declare function createStatusHistoryItemSchema(statuses: string[]): Schema<StatusHistoryItem<string>>;
6
+ //#endregion
7
+ export { createStatusHistoryItemSchema };
@@ -1,12 +1,18 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createStatusHistoryItemSchema = createStatusHistoryItemSchema;
4
- const mongoose_1 = require("mongoose");
1
+ import { Schema } from "mongoose";
2
+ //#region src/schemas/statusHistoryItem.ts
5
3
  function createStatusHistoryItemSchema(statuses) {
6
- return new mongoose_1.Schema({
7
- traceId: { type: String },
8
- date: { type: Date, required: true },
9
- status: { type: String, enum: statuses, required: true },
10
- }, { _id: false });
4
+ return new Schema({
5
+ traceId: { type: String },
6
+ date: {
7
+ type: Date,
8
+ required: true
9
+ },
10
+ status: {
11
+ type: String,
12
+ enum: statuses,
13
+ required: true
14
+ }
15
+ }, { _id: false });
11
16
  }
12
- //# sourceMappingURL=statusHistoryItem.js.map
17
+ //#endregion
18
+ export { createStatusHistoryItemSchema };
@@ -0,0 +1,19 @@
1
+ import { DatabaseAdapterType, PostgresDatabase } from "../interfaces/database.js";
2
+ import { Counter } from "../interfaces/models/counter.js";
3
+ import { Model } from "mongoose";
4
+
5
+ //#region src/services/counter.d.ts
6
+ declare class CounterService {
7
+ private readonly databaseAdapter;
8
+ private readonly counterModel;
9
+ private readonly postgresDatabase;
10
+ private readonly getNextValueStrategy;
11
+ private readonly getNextDailyValueStrategy;
12
+ constructor(databaseAdapter: DatabaseAdapterType, counterModel?: Model<Counter> | null, postgresDatabase?: PostgresDatabase | null);
13
+ getNextValue(code: string): Promise<number>;
14
+ getNextDailyValue(code: string): Promise<number>;
15
+ private getModel;
16
+ private getPostgresDatabase;
17
+ }
18
+ //#endregion
19
+ export { CounterService };
@@ -1,72 +1,70 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CounterService = void 0;
4
- const drizzle_orm_1 = require("drizzle-orm");
5
- const luxon_1 = require("luxon");
6
- const tables_1 = require("../tables");
7
- class CounterService {
8
- databaseAdapter;
9
- counterModel;
10
- postgresDatabase;
11
- getNextValueStrategy = {
12
- postgres: async (code) => {
13
- const result = await this.getPostgresDatabase()
14
- .insert(tables_1.counter)
15
- .values({ code, value: 1, date: luxon_1.DateTime.now().startOf('day').toJSDate() })
16
- .onConflictDoUpdate({
17
- target: [tables_1.counter.code, tables_1.counter.date],
18
- set: { value: (0, drizzle_orm_1.sql) `${tables_1.counter.value} + 1` },
19
- })
20
- .returning()
21
- .then((rows) => rows[0]);
22
- return result.value;
23
- },
24
- mongo: async (code) => {
25
- const result = await this.getModel().findOneAndUpdate({ code }, { $inc: { value: 1 } }, { new: true, upsert: true });
26
- return result.value;
27
- },
28
- };
29
- getNextDailyValueStrategy = {
30
- postgres: async (code) => {
31
- const result = await this.getPostgresDatabase()
32
- .insert(tables_1.counter)
33
- .values({ code, value: 1, date: luxon_1.DateTime.now().startOf('day').toJSDate() })
34
- .onConflictDoUpdate({
35
- target: [tables_1.counter.code, tables_1.counter.date],
36
- set: { value: (0, drizzle_orm_1.sql) `${tables_1.counter.value} + 1` },
37
- })
38
- .returning()
39
- .then((rows) => rows[0]);
40
- return result.value;
41
- },
42
- mongo: async (code) => {
43
- const result = await this.getModel().findOneAndUpdate({ code, date: luxon_1.DateTime.now().startOf('day').toJSDate() }, { $inc: { value: 1 } }, { new: true, upsert: true });
44
- return result.value;
45
- },
46
- };
47
- constructor(databaseAdapter, counterModel = null, postgresDatabase = null) {
48
- this.databaseAdapter = databaseAdapter;
49
- this.counterModel = counterModel;
50
- this.postgresDatabase = postgresDatabase;
51
- }
52
- async getNextValue(code) {
53
- return await this.getNextValueStrategy[this.databaseAdapter](code);
54
- }
55
- async getNextDailyValue(code) {
56
- return await this.getNextDailyValueStrategy[this.databaseAdapter](code);
57
- }
58
- getModel() {
59
- if (!this.counterModel) {
60
- throw new Error('Counter model is not provided');
61
- }
62
- return this.counterModel;
63
- }
64
- getPostgresDatabase() {
65
- if (!this.postgresDatabase) {
66
- throw new Error('Postgres database is not provided');
67
- }
68
- return this.postgresDatabase;
69
- }
70
- }
71
- exports.CounterService = CounterService;
72
- //# sourceMappingURL=counter.js.map
1
+ import { counter } from "../tables/counter.js";
2
+ import "../tables/index.js";
3
+ import { sql } from "drizzle-orm";
4
+ import { DateTime } from "luxon";
5
+ //#region src/services/counter.ts
6
+ var CounterService = class {
7
+ databaseAdapter;
8
+ counterModel;
9
+ postgresDatabase;
10
+ getNextValueStrategy = {
11
+ postgres: async (code) => {
12
+ return (await this.getPostgresDatabase().insert(counter).values({
13
+ code,
14
+ value: 1,
15
+ date: DateTime.now().startOf("day").toJSDate()
16
+ }).onConflictDoUpdate({
17
+ target: [counter.code, counter.date],
18
+ set: { value: sql`${counter.value} + 1` }
19
+ }).returning().then((rows) => rows[0])).value;
20
+ },
21
+ mongo: async (code) => {
22
+ return (await this.getModel().findOneAndUpdate({ code }, { $inc: { value: 1 } }, {
23
+ returnDocument: "after",
24
+ upsert: true
25
+ })).value;
26
+ }
27
+ };
28
+ getNextDailyValueStrategy = {
29
+ postgres: async (code) => {
30
+ return (await this.getPostgresDatabase().insert(counter).values({
31
+ code,
32
+ value: 1,
33
+ date: DateTime.now().startOf("day").toJSDate()
34
+ }).onConflictDoUpdate({
35
+ target: [counter.code, counter.date],
36
+ set: { value: sql`${counter.value} + 1` }
37
+ }).returning().then((rows) => rows[0])).value;
38
+ },
39
+ mongo: async (code) => {
40
+ return (await this.getModel().findOneAndUpdate({
41
+ code,
42
+ date: DateTime.now().startOf("day").toJSDate()
43
+ }, { $inc: { value: 1 } }, {
44
+ returnDocument: "after",
45
+ upsert: true
46
+ })).value;
47
+ }
48
+ };
49
+ constructor(databaseAdapter, counterModel = null, postgresDatabase = null) {
50
+ this.databaseAdapter = databaseAdapter;
51
+ this.counterModel = counterModel;
52
+ this.postgresDatabase = postgresDatabase;
53
+ }
54
+ async getNextValue(code) {
55
+ return await this.getNextValueStrategy[this.databaseAdapter](code);
56
+ }
57
+ async getNextDailyValue(code) {
58
+ return await this.getNextDailyValueStrategy[this.databaseAdapter](code);
59
+ }
60
+ getModel() {
61
+ if (!this.counterModel) throw new Error("Counter model is not provided");
62
+ return this.counterModel;
63
+ }
64
+ getPostgresDatabase() {
65
+ if (!this.postgresDatabase) throw new Error("Postgres database is not provided");
66
+ return this.postgresDatabase;
67
+ }
68
+ };
69
+ //#endregion
70
+ export { CounterService };
@@ -0,0 +1,50 @@
1
+ import { DatabaseAdapterType } from "../interfaces/database.js";
2
+ import { AppDb, AppDbConfig, DbType } from "../interfaces/dbConfig.js";
3
+ import { MongoDbStatus } from "../interfaces/mongoStatus.js";
4
+ import { MongodbOperationsLabelsMap } from "../interfaces/metrics.js";
5
+ import mongoose, { ClientSession } from "mongoose";
6
+ import { Histogram, Observer } from "@diia-inhouse/diia-metrics";
7
+ import { HealthCheckResult, Logger, OnDestroy, OnHealthCheck, OnInit } from "@diia-inhouse/types";
8
+ import { EnvService } from "@diia-inhouse/env";
9
+
10
+ //#region src/services/database.d.ts
11
+ declare class DatabaseService implements OnInit, OnHealthCheck, OnDestroy {
12
+ private readonly databaseAdapter;
13
+ private readonly dbConfigs;
14
+ private readonly envService;
15
+ private readonly logger;
16
+ readonly defaultModelsDir = "models";
17
+ db: Partial<Record<DbType, AppDb>>;
18
+ dbOperationsHistogram?: Histogram<MongodbOperationsLabelsMap>;
19
+ dbOplogObserver?: Observer<object>;
20
+ observerInterval: NodeJS.Timeout | undefined;
21
+ private dbOplog;
22
+ private readonly isMonitoringEnabled;
23
+ private readonly dbStateCodeToName;
24
+ /**
25
+ * https://www.mongodb.com/docs/manual/core/transactions/#read-concern-write-concern-read-preference
26
+ */
27
+ private readonly defaultTransactionOptions;
28
+ constructor(databaseAdapter: DatabaseAdapterType, dbConfigs: Partial<Record<DbType, AppDbConfig>>, envService: EnvService, logger: Logger);
29
+ onInit(): Promise<void>;
30
+ onDestroy(): Promise<void>;
31
+ onHealthCheck(): Promise<HealthCheckResult<MongoDbStatus>>;
32
+ createDbConnection(type: DbType, config: AppDbConfig): Promise<AppDb | undefined>;
33
+ /**
34
+ * Begins a new MongoDB transaction by starting a session and transaction
35
+ *
36
+ * @param options - Optional transaction options to override the default transaction settings
37
+ * @returns A ClientSession with an active transaction
38
+ * @throws {DatabaseError} If the database connection is undefined or transaction fails to start
39
+ *
40
+ * @remarks
41
+ * - Uses the main database connection to start the session
42
+ * - Applies default transaction options (readPreference: primary)
43
+ * - Will abort transaction and end session if any errors occur during setup
44
+ */
45
+ beginTransaction(options?: mongoose.mongo.TransactionOptions): Promise<ClientSession>;
46
+ private connectMonitor;
47
+ private oplogObserver;
48
+ }
49
+ //#endregion
50
+ export { DatabaseService };