@heliyos/heliyos-api-core 1.0.17 → 1.0.18

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.
package/dist/index.d.ts CHANGED
@@ -20,4 +20,4 @@ export type { BaseError, CustomAxiosError } from "./@types/globals/customError";
20
20
  export { HttpError } from "./@types/globals/customError";
21
21
  export type { ICoreAppOptions } from "./@types/globals/middleware";
22
22
  export type { RolesPermissionsType, ResourcePolicyActionsType, } from "./static/auth_policy_file";
23
- export { Schema, Document, Model, FilterQuery, UpdateQuery, Connection, Pagination, Types, createModel, mongooseConnection, mongooseReplicaConnection, createBulkOperations, ensureIndexes, closeConnections, withTransaction, upsertDocument, checkDatabaseHealth, safeDelete, } from "./mongoose";
23
+ export { Schema, Document, Model, FilterQuery, UpdateQuery, Connection, Pagination, Types, createModel, mongooseConnection, createBulkOperations, ensureIndexes, closeConnections, withTransaction, upsertDocument, safeDelete, } from "./mongoose";
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.safeDelete = exports.checkDatabaseHealth = exports.upsertDocument = exports.withTransaction = exports.closeConnections = exports.ensureIndexes = exports.createBulkOperations = exports.mongooseReplicaConnection = exports.mongooseConnection = exports.createModel = exports.Types = exports.Connection = exports.Model = exports.Document = exports.Schema = exports.HttpError = exports.getSecretsManagerSecret = exports.resendSendEmail = exports.pusherTriggerBatch = exports.pusherTrigger = exports.pusher = exports.emailTemplates = exports.getEmailTemplate = exports.allowed_origin = exports.logger = exports.SQSUtil = exports.createRedisClient = exports.authorize_user = exports.database_config = exports.auth_policy = exports.loadAppEnv = exports.joiObject = exports.validate = exports.core_replica_knex = exports.core_knex = exports.axios = exports.core_app = exports.authentication = void 0;
26
+ exports.safeDelete = exports.upsertDocument = exports.withTransaction = exports.closeConnections = exports.ensureIndexes = exports.createBulkOperations = exports.mongooseConnection = exports.createModel = exports.Types = exports.Connection = exports.Model = exports.Document = exports.Schema = exports.HttpError = exports.getSecretsManagerSecret = exports.resendSendEmail = exports.pusherTriggerBatch = exports.pusherTrigger = exports.pusher = exports.emailTemplates = exports.getEmailTemplate = exports.allowed_origin = exports.logger = exports.SQSUtil = exports.createRedisClient = exports.authorize_user = exports.database_config = exports.auth_policy = exports.loadAppEnv = exports.joiObject = exports.validate = exports.core_replica_knex = exports.core_knex = exports.axios = exports.core_app = exports.authentication = void 0;
27
27
  const dotenv = __importStar(require("dotenv"));
28
28
  dotenv.config();
29
29
  // Core exports
@@ -78,11 +78,9 @@ Object.defineProperty(exports, "Connection", { enumerable: true, get: function (
78
78
  Object.defineProperty(exports, "Types", { enumerable: true, get: function () { return mongoose_1.Types; } });
79
79
  Object.defineProperty(exports, "createModel", { enumerable: true, get: function () { return mongoose_1.createModel; } });
80
80
  Object.defineProperty(exports, "mongooseConnection", { enumerable: true, get: function () { return mongoose_1.mongooseConnection; } });
81
- Object.defineProperty(exports, "mongooseReplicaConnection", { enumerable: true, get: function () { return mongoose_1.mongooseReplicaConnection; } });
82
81
  Object.defineProperty(exports, "createBulkOperations", { enumerable: true, get: function () { return mongoose_1.createBulkOperations; } });
83
82
  Object.defineProperty(exports, "ensureIndexes", { enumerable: true, get: function () { return mongoose_1.ensureIndexes; } });
84
83
  Object.defineProperty(exports, "closeConnections", { enumerable: true, get: function () { return mongoose_1.closeConnections; } });
85
84
  Object.defineProperty(exports, "withTransaction", { enumerable: true, get: function () { return mongoose_1.withTransaction; } });
86
85
  Object.defineProperty(exports, "upsertDocument", { enumerable: true, get: function () { return mongoose_1.upsertDocument; } });
87
- Object.defineProperty(exports, "checkDatabaseHealth", { enumerable: true, get: function () { return mongoose_1.checkDatabaseHealth; } });
88
86
  Object.defineProperty(exports, "safeDelete", { enumerable: true, get: function () { return mongoose_1.safeDelete; } });
package/dist/knex.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -15,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
6
  exports.core_replica_knex = exports.core_knex = void 0;
16
7
  const knexfile_1 = require("./knexfile");
17
8
  const logger_1 = require("./logger");
18
- const ssm_1 = require("./ssm");
19
9
  const knex_1 = __importDefault(require("knex"));
20
10
  const Builder = require("knex/lib/query/querybuilder");
21
11
  // Create Knex connection based on the environment
@@ -34,6 +24,10 @@ const knex_connected = () => {
34
24
  logger_1.logger.error(`Failed to get knex configuration for env:${process.env.NODE_ENV}`);
35
25
  return null;
36
26
  }
27
+ if (!process.env.POSTGRES_DATABASE_URL) {
28
+ logger_1.logger.error(`POSTGRES_DATABASE_URL not set, cannot establish connection`);
29
+ return null;
30
+ }
37
31
  logger_1.logger.info("New Connection");
38
32
  const connection = (0, knex_1.default)(cachedConfigEnvironment || configByEnvironment);
39
33
  cachedConnection = connection;
@@ -49,23 +43,11 @@ const replica_knex_connected = () => {
49
43
  logger_1.logger.error(`Failed to get knex configuration for env:${process.env.NODE_ENV}`);
50
44
  return null;
51
45
  }
52
- if (process.env.NODE_ENV === "local") {
53
- if (process.env.REPLICA_DATABASE_URL) {
54
- configByEnvironment.connection = process.env.REPLICA_DATABASE_URL;
55
- }
56
- else {
57
- logger_1.logger.info(`REPLICA_DATABASE_URL not set, cannot establish replica connection`);
58
- return null;
59
- }
60
- }
61
- else if (["development", "production"].includes(process.env.NODE_ENV)) {
62
- configByEnvironment.connection = () => __awaiter(void 0, void 0, void 0, function* () {
63
- const ENV_SECRETS = yield (0, ssm_1.getSecretsManagerSecret)(process.env.ENV_SECRET_NAME);
64
- return ENV_SECRETS.REPLICA_DATABASE_URL;
65
- });
46
+ if (process.env.POSTGRES_REPLICA_DATABASE_URL) {
47
+ configByEnvironment.connection = process.env.POSTGRES_REPLICA_DATABASE_URL;
66
48
  }
67
49
  else {
68
- logger_1.logger.info(`Replica not supported for this NODE_ENV=${process.env.NODE_ENV}`);
50
+ logger_1.logger.info(`POSTGRES_REPLICA_DATABASE_URL not set, cannot establish replica connection`);
69
51
  return null;
70
52
  }
71
53
  logger_1.logger.info("New Replica Connection");
package/dist/knexfile.js CHANGED
@@ -1,29 +1,12 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var _a, _b;
12
3
  Object.defineProperty(exports, "__esModule", { value: true });
13
4
  exports.database_config = void 0;
14
- const ssm_1 = require("./ssm");
15
- const getSecrets = (isTest = false) => __awaiter(void 0, void 0, void 0, function* () {
16
- const ENV_SECRETS = yield (0, ssm_1.getSecretsManagerSecret)(process.env.ENV_SECRET_NAME);
17
- if (isTest) {
18
- return ENV_SECRETS.TEST_DATABASE_URL;
19
- }
20
- return ENV_SECRETS.DATABASE_URL;
21
- });
22
5
  // Config settings for Knex
23
- const DATABASE_URL = process.env.DATABASE_URL;
24
- const TEST_DATABASE_URL = process.env.TEST_DATABASE_URL;
25
- const CONNECTION_POOL_MIN = parseInt((_a = process.env.CONNECTION_POOL_MIN) !== null && _a !== void 0 ? _a : "1", 10);
26
- const CONNECTION_POOL_MAX = parseInt((_b = process.env.CONNECTION_POOL_MAX) !== null && _b !== void 0 ? _b : "10", 10);
6
+ const DATABASE_URL = process.env.POSTGRES_DATABASE_URL;
7
+ const TEST_DATABASE_URL = process.env.POSTGRES_TEST_DATABASE_URL;
8
+ const CONNECTION_POOL_MIN = parseInt((_a = process.env.POSTGRES_CONNECTION_POOL_MIN) !== null && _a !== void 0 ? _a : "1", 10);
9
+ const CONNECTION_POOL_MAX = parseInt((_b = process.env.POSTGRES_CONNECTION_POOL_MAX) !== null && _b !== void 0 ? _b : "10", 10);
27
10
  const config = {
28
11
  local: {
29
12
  client: "postgresql",
@@ -39,7 +22,7 @@ const config = {
39
22
  },
40
23
  development: {
41
24
  client: "postgresql",
42
- connection: () => __awaiter(void 0, void 0, void 0, function* () { return yield getSecrets(); }),
25
+ connection: DATABASE_URL,
43
26
  ssl: true,
44
27
  migrations: {
45
28
  tableName: "knex_migrations",
@@ -51,7 +34,7 @@ const config = {
51
34
  },
52
35
  staging: {
53
36
  client: "postgresql",
54
- connection: () => __awaiter(void 0, void 0, void 0, function* () { return yield getSecrets(); }),
37
+ connection: DATABASE_URL,
55
38
  ssl: true,
56
39
  migrations: {
57
40
  tableName: "knex_migrations",
@@ -63,7 +46,7 @@ const config = {
63
46
  },
64
47
  production: {
65
48
  client: "postgresql",
66
- connection: () => __awaiter(void 0, void 0, void 0, function* () { return yield getSecrets(); }),
49
+ connection: DATABASE_URL,
67
50
  ssl: true,
68
51
  migrations: {
69
52
  tableName: "knex_migrations",
@@ -15,7 +15,6 @@ declare module "mongoose" {
15
15
  }
16
16
  }
17
17
  export declare const mongooseConnection: Promise<mongoose.Connection>;
18
- export declare const mongooseReplicaConnection: Promise<mongoose.Connection>;
19
18
  export declare const createModel: <T extends mongoose.Document<unknown, any, any>>(name: string, schema: Schema) => mongoose.Model<T, {}, {}, {}, mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & mongoose.Default__v<mongoose.Require_id<T>>>, any>;
20
19
  export declare const createBulkOperations: <T>(operations: {
21
20
  updateOne?: {
@@ -38,8 +37,4 @@ export declare const ensureIndexes: (models: Model<any>[]) => Promise<void>;
38
37
  export declare const withTransaction: <T>(callback: (session: mongoose.ClientSession) => Promise<T>) => Promise<T>;
39
38
  export declare const safeDelete: <T extends mongoose.Document<unknown, any, any>>(model: mongoose.Model<T, {}, {}, {}, mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & mongoose.Default__v<mongoose.Require_id<T>>>, any>, filter: mongoose.FilterQuery<T>) => Promise<boolean>;
40
39
  export declare const upsertDocument: <T extends mongoose.Document<unknown, any, any>>(model: mongoose.Model<T, {}, {}, {}, mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & mongoose.Default__v<mongoose.Require_id<T>>>, any>, filter: mongoose.FilterQuery<T>, update: mongoose.UpdateQuery<T>) => Promise<T>;
41
- export declare const checkDatabaseHealth: () => Promise<{
42
- primary: boolean;
43
- replica: boolean;
44
- }>;
45
40
  export declare const closeConnections: () => Promise<void>;
package/dist/mongoose.js CHANGED
@@ -26,9 +26,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.closeConnections = exports.checkDatabaseHealth = exports.upsertDocument = exports.safeDelete = exports.withTransaction = exports.ensureIndexes = exports.createBulkOperations = exports.createModel = exports.mongooseReplicaConnection = exports.mongooseConnection = void 0;
29
+ exports.closeConnections = exports.upsertDocument = exports.safeDelete = exports.withTransaction = exports.ensureIndexes = exports.createBulkOperations = exports.createModel = exports.mongooseConnection = void 0;
30
30
  const mongoose_1 = __importDefault(require("mongoose"));
31
- const ssm_1 = require("./ssm");
32
31
  const logger_1 = require("./logger");
33
32
  // Export commonly used mongoose types
34
33
  __exportStar(require("mongoose"), exports);
@@ -36,21 +35,9 @@ __exportStar(require("mongoose"), exports);
36
35
  let cachedConnection;
37
36
  let cachedReplicaConnection;
38
37
  const connectionOptions = {
39
- // Timeouts
40
- serverSelectionTimeoutMS: 60000,
41
- connectTimeoutMS: 60000,
42
- socketTimeoutMS: 360000,
43
38
  // Connection pool settings
44
- maxPoolSize: 10,
45
- minPoolSize: 1,
46
- // Heartbeat monitoring
47
- heartbeatFrequencyMS: 10000,
48
- // Modern reliability settings
49
- retryWrites: true,
50
- retryReads: true,
51
- // Required for newer MongoDB versions
52
- useNewUrlParser: true,
53
- useUnifiedTopology: true,
39
+ maxPoolSize: parseInt(process.env.MONGO_MAX_POOL_SIZE || "10", 10) || 10,
40
+ minPoolSize: parseInt(process.env.MONGO_MIN_POOL_SIZE || "1", 10) || 1,
54
41
  };
55
42
  const MAX_RETRY_ATTEMPTS = 10; // Increased from 5
56
43
  const INITIAL_RETRY_DELAY = 2000; // Increased from 1000
@@ -82,7 +69,7 @@ const connectWithRetry = (mongoUrl, attempt = 1) => __awaiter(void 0, void 0, vo
82
69
  connection.once("connected", () => resolve());
83
70
  connection.once("error", (err) => reject(err));
84
71
  }),
85
- new Promise((_, reject) => setTimeout(() => reject(new Error("Connection timeout")), connectionOptions.connectTimeoutMS)),
72
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Connection timeout")), 60000)),
86
73
  ]);
87
74
  return connection;
88
75
  }
@@ -121,21 +108,15 @@ const mongooseConnected = () => __awaiter(void 0, void 0, void 0, function* () {
121
108
  }
122
109
  let mongoUrl;
123
110
  const nodeEnv = process.env.NODE_ENV;
124
- if (nodeEnv === "local") {
111
+ if (process.env.MONGO_DATABASE_URL) {
125
112
  mongoUrl = process.env.MONGO_DATABASE_URL || "";
126
113
  // Add logging to debug URL
127
114
  }
128
- else if (["development", "production"].includes(nodeEnv)) {
129
- const secrets = yield (0, ssm_1.getSecretsManagerSecret)(process.env.ENV_SECRET_NAME);
130
- mongoUrl = secrets.MONGO_DATABASE_URL;
131
- }
132
115
  else {
133
116
  logger_1.logger.error(`Invalid NODE_ENV: ${nodeEnv}`);
134
117
  return null;
135
118
  }
136
- if (nodeEnv === "development") {
137
- logger_1.logger.info(`Connecting to MongoDB URL: ${mongoUrl === null || mongoUrl === void 0 ? void 0 : mongoUrl.replace(/\/\/[^@]*@/, "//****:****@")}`);
138
- }
119
+ logger_1.logger.info(`Connecting to MongoDB URL: ${mongoUrl === null || mongoUrl === void 0 ? void 0 : mongoUrl.replace(/\/\/[^@]*@/, "//****:****@")}`);
139
120
  if (!mongoUrl) {
140
121
  logger_1.logger.error("MONGO_DATABASE_URL not set");
141
122
  return null;
@@ -178,40 +159,6 @@ const mongooseConnected = () => __awaiter(void 0, void 0, void 0, function* () {
178
159
  return null;
179
160
  }
180
161
  });
181
- const replicaMongooseConnected = () => __awaiter(void 0, void 0, void 0, function* () {
182
- if (cachedReplicaConnection) {
183
- logger_1.logger.info("Cached MongoDB Replica Connection");
184
- return cachedReplicaConnection;
185
- }
186
- const nodeEnv = process.env.NODE_ENV;
187
- let replicaUrl;
188
- if (nodeEnv === "local") {
189
- replicaUrl = process.env.MONGO_REPLICA_DATABASE_URL;
190
- }
191
- else if (["development", "production"].includes(nodeEnv)) {
192
- const secrets = yield (0, ssm_1.getSecretsManagerSecret)(process.env.ENV_SECRET_NAME);
193
- replicaUrl = secrets.MONGO_REPLICA_DATABASE_URL;
194
- }
195
- else {
196
- logger_1.logger.info(`Failed to get mongoose configuration for env:${nodeEnv}`);
197
- return null;
198
- }
199
- if (!replicaUrl) {
200
- logger_1.logger.info("MONGO_REPLICA_DATABASE_URL not set");
201
- return null;
202
- }
203
- logger_1.logger.info("New MongoDB Replica Connection");
204
- const connection = yield connectWithRetry(replicaUrl);
205
- if (!connection) {
206
- logger_1.logger.error("Failed to establish MongoDB replica connection after retries");
207
- return null;
208
- }
209
- connection.on("error", (err) => {
210
- console.error("MongoDB replica connection error:", err);
211
- });
212
- cachedReplicaConnection = connection;
213
- return connection;
214
- });
215
162
  mongoose_1.default.Query.prototype.paginate = function (page = 1, limit = 10) {
216
163
  return __awaiter(this, void 0, void 0, function* () {
217
164
  const offset = (page - 1) * limit;
@@ -228,7 +175,7 @@ mongoose_1.default.Query.prototype.paginate = function (page = 1, limit = 10) {
228
175
  };
229
176
  // Initialize and export connections
230
177
  exports.mongooseConnection = mongooseConnected();
231
- exports.mongooseReplicaConnection = replicaMongooseConnected();
178
+ // export const mongooseReplicaConnection = replicaMongooseConnected();
232
179
  // Helper for creating typed models
233
180
  const createModel = (name, schema) => {
234
181
  logger_1.logger.info(`Creating model ${name}`);
@@ -308,21 +255,6 @@ const upsertDocument = (model, filter, update) => __awaiter(void 0, void 0, void
308
255
  return model.findOneAndUpdate(filter, update, { upsert: true, new: true });
309
256
  });
310
257
  exports.upsertDocument = upsertDocument;
311
- // Connection health check utility
312
- const checkDatabaseHealth = () => __awaiter(void 0, void 0, void 0, function* () {
313
- try {
314
- const [primary, replica] = yield Promise.all([
315
- exports.mongooseConnection.then((conn) => conn.readyState === mongoose_1.default.ConnectionStates.connected),
316
- exports.mongooseReplicaConnection.then((conn) => { var _a; return (_a = (conn === null || conn === void 0 ? void 0 : conn.readyState) === mongoose_1.default.ConnectionStates.connected) !== null && _a !== void 0 ? _a : false; }),
317
- ]);
318
- return { primary, replica };
319
- }
320
- catch (error) {
321
- console.error("Database health check failed:", error);
322
- return { primary: false, replica: false };
323
- }
324
- });
325
- exports.checkDatabaseHealth = checkDatabaseHealth;
326
258
  // Graceful shutdown helper
327
259
  const closeConnections = () => __awaiter(void 0, void 0, void 0, function* () {
328
260
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heliyos/heliyos-api-core",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
4
4
  "description": "Heliyos's core api functions and middlewares. Its a private package hosted on npm.",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {