@vibe-flats/booking-engine-common-server 1.0.113 → 1.0.116

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/build/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './src/config/app';
3
3
  export * from './src/utils/vibe-price';
4
4
  export * from './src/utils/monthly-diff';
5
5
  export * from './src/utils/purge-unit-cache';
6
+ export * from './src/utils/cache';
package/build/index.js CHANGED
@@ -19,3 +19,4 @@ __exportStar(require("./src/config/app"), exports);
19
19
  __exportStar(require("./src/utils/vibe-price"), exports);
20
20
  __exportStar(require("./src/utils/monthly-diff"), exports);
21
21
  __exportStar(require("./src/utils/purge-unit-cache"), exports);
22
+ __exportStar(require("./src/utils/cache"), exports);
@@ -19,6 +19,9 @@ export interface MarketDocument extends mongoose.Document {
19
19
  answer: string;
20
20
  }[];
21
21
  };
22
+ furnishedFinder: {
23
+ extractString: string;
24
+ };
22
25
  createdAt: Date;
23
26
  updatedAt: Date;
24
27
  }
@@ -52,6 +52,13 @@ const schema = new mongoose_1.default.Schema({
52
52
  ]
53
53
  }),
54
54
  _id: false
55
+ },
56
+ furnishedFinder: {
57
+ type: new mongoose_1.default.Schema({
58
+ extractString: { type: String }
59
+ }),
60
+ required: false,
61
+ _id: false
55
62
  }
56
63
  }, {
57
64
  timestamps: true
@@ -0,0 +1,51 @@
1
+ /**
2
+ * MongoDB Cache Implementation using Keyv
3
+ *
4
+ * This module provides a MongoDB-based caching solution using Keyv with full TypeScript support.
5
+ * Keyv provides a simple key-value interface with automatic TTL expiration in MongoDB.
6
+ *
7
+ * Usage Examples:
8
+ *
9
+ * 1. Simple caching with default TTL:
10
+ * const data = await withCache('user_123', () => fetchUserData('123'));
11
+ *
12
+ * 2. Custom TTL (5 minutes):
13
+ * const data = await withCache('expensive_calc', () => performCalculation(), 300);
14
+ *
15
+ * 3. In a controller:
16
+ * export const myFunction = async (req, res) => {
17
+ * const data = await withCache(
18
+ * `user_${req.params.id}`,
19
+ * () => fetchUserData(req.params.id),
20
+ * 300 // 5 minutes
21
+ * );
22
+ * res.json(data);
23
+ * };
24
+ *
25
+ * Environment Variables Required:
26
+ * - MONGO_URL: MongoDB connection string base
27
+ * - MONGO_URL_PARAMS: Additional connection parameters (optional)
28
+ *
29
+ *
30
+ * When using this, need to stop the usage of gReq and pass the req as a param so it passes to withCache fetchFn
31
+ */
32
+ interface CacheConfig {
33
+ defaultTTL: number;
34
+ keyPrefix: string;
35
+ mongoUri?: string;
36
+ }
37
+ declare class CacheManager {
38
+ private cache;
39
+ private config;
40
+ private isEnabled;
41
+ private collection;
42
+ constructor(config: CacheConfig);
43
+ private initializeCache;
44
+ get<T>(key: string): Promise<T | null>;
45
+ set<T>(key: string, value: T, ttl?: number): Promise<boolean>;
46
+ del(key: string): Promise<boolean>;
47
+ clear(): Promise<boolean>;
48
+ }
49
+ export declare const mongoCacheManager: CacheManager;
50
+ export declare const withMongoCache: <T>(key: string, fetchFn: () => Promise<T>, ttl?: number) => Promise<T>;
51
+ export default mongoCacheManager;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * MongoDB Cache Implementation using Keyv
4
+ *
5
+ * This module provides a MongoDB-based caching solution using Keyv with full TypeScript support.
6
+ * Keyv provides a simple key-value interface with automatic TTL expiration in MongoDB.
7
+ *
8
+ * Usage Examples:
9
+ *
10
+ * 1. Simple caching with default TTL:
11
+ * const data = await withCache('user_123', () => fetchUserData('123'));
12
+ *
13
+ * 2. Custom TTL (5 minutes):
14
+ * const data = await withCache('expensive_calc', () => performCalculation(), 300);
15
+ *
16
+ * 3. In a controller:
17
+ * export const myFunction = async (req, res) => {
18
+ * const data = await withCache(
19
+ * `user_${req.params.id}`,
20
+ * () => fetchUserData(req.params.id),
21
+ * 300 // 5 minutes
22
+ * );
23
+ * res.json(data);
24
+ * };
25
+ *
26
+ * Environment Variables Required:
27
+ * - MONGO_URL: MongoDB connection string base
28
+ * - MONGO_URL_PARAMS: Additional connection parameters (optional)
29
+ *
30
+ *
31
+ * When using this, need to stop the usage of gReq and pass the req as a param so it passes to withCache fetchFn
32
+ */
33
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
34
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
35
+ return new (P || (P = Promise))(function (resolve, reject) {
36
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
37
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
38
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
39
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
40
+ });
41
+ };
42
+ var __importDefault = (this && this.__importDefault) || function (mod) {
43
+ return (mod && mod.__esModule) ? mod : { "default": mod };
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.withMongoCache = exports.mongoCacheManager = void 0;
47
+ const keyv_1 = __importDefault(require("keyv"));
48
+ const mongo_1 = __importDefault(require("@keyv/mongo"));
49
+ class CacheManager {
50
+ constructor(config) {
51
+ this.cache = null;
52
+ this.isEnabled = false;
53
+ this.collection = 'cache';
54
+ this.config = config;
55
+ this.initializeCache();
56
+ }
57
+ initializeCache() {
58
+ try {
59
+ // Use provided MongoDB URI or build from environment variables
60
+ const mongoUri = this.config.mongoUri || `${process.env.MONGO_URL}${this.collection}${process.env.MONGO_URL_PARAMS || ''}`;
61
+ if (!mongoUri || !process.env.MONGO_URL) {
62
+ console.warn('MongoDB URL not provided. Cache will be disabled.');
63
+ return;
64
+ }
65
+ // Create Keyv instance with MongoDB store
66
+ const store = new mongo_1.default(mongoUri, {
67
+ collection: this.collection
68
+ });
69
+ this.cache = new keyv_1.default({
70
+ store,
71
+ ttl: this.config.defaultTTL,
72
+ namespace: this.config.keyPrefix
73
+ });
74
+ // Handle connection events
75
+ this.cache.on('error', error => {
76
+ console.warn('Cache error:', error);
77
+ this.isEnabled = false;
78
+ });
79
+ this.isEnabled = true;
80
+ console.log('MongoDB cache initialized successfully with Keyv');
81
+ }
82
+ catch (error) {
83
+ console.warn('Failed to initialize MongoDB cache:', error);
84
+ this.isEnabled = false;
85
+ }
86
+ }
87
+ get(key) {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ if (!this.isEnabled || !this.cache) {
90
+ return null;
91
+ }
92
+ try {
93
+ const value = yield this.cache.get(key);
94
+ return value || null;
95
+ }
96
+ catch (error) {
97
+ console.warn('Cache get error:', error);
98
+ return null;
99
+ }
100
+ });
101
+ }
102
+ set(key, value, ttl) {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ if (!this.isEnabled || !this.cache) {
105
+ return false;
106
+ }
107
+ try {
108
+ const timeToLive = ttl ? ttl * 1000 : this.config.defaultTTL; // Convert seconds to milliseconds
109
+ yield this.cache.set(key, value, timeToLive);
110
+ return true;
111
+ }
112
+ catch (error) {
113
+ console.warn('Cache set error:', error);
114
+ return false;
115
+ }
116
+ });
117
+ }
118
+ del(key) {
119
+ return __awaiter(this, void 0, void 0, function* () {
120
+ if (!this.isEnabled || !this.cache) {
121
+ return false;
122
+ }
123
+ try {
124
+ const result = yield this.cache.delete(key);
125
+ return result;
126
+ }
127
+ catch (error) {
128
+ console.warn('Cache delete error:', error);
129
+ return false;
130
+ }
131
+ });
132
+ }
133
+ clear() {
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ if (!this.isEnabled || !this.cache) {
136
+ return false;
137
+ }
138
+ try {
139
+ // Keyv's clear() method respects the namespace/prefix
140
+ // So this will only clear items with our prefix
141
+ yield this.cache.clear();
142
+ console.log(`Cleared all cache entries with prefix: ${this.config.keyPrefix}`);
143
+ return true;
144
+ }
145
+ catch (error) {
146
+ console.warn('Cache clear error:', error);
147
+ return false;
148
+ }
149
+ });
150
+ }
151
+ }
152
+ // Create a singleton cache manager instance
153
+ exports.mongoCacheManager = new CacheManager({
154
+ defaultTTL: 600000, // 10 minutes in milliseconds
155
+ keyPrefix: process.env.npm_package_name || 'no-process.env.npm_package_name'
156
+ });
157
+ // Helper function for caching with fallback (exactly like your example)
158
+ const withMongoCache = (key_1, fetchFn_1, ...args_1) => __awaiter(void 0, [key_1, fetchFn_1, ...args_1], void 0, function* (key, fetchFn, ttl = 600) {
159
+ let result = yield exports.mongoCacheManager.get(key);
160
+ if (result) {
161
+ console.log(`Cache hit for key: ${key}`);
162
+ return result;
163
+ }
164
+ console.log(`Cache miss for key: ${key}`);
165
+ result = yield fetchFn();
166
+ yield exports.mongoCacheManager.set(key, result, ttl);
167
+ console.log(`Cached data for key: ${key}`);
168
+ return result;
169
+ });
170
+ exports.withMongoCache = withMongoCache;
171
+ // Alternative export for convenience
172
+ exports.default = exports.mongoCacheManager;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibe-flats/booking-engine-common-server",
3
- "version": "1.0.113",
3
+ "version": "1.0.116",
4
4
  "description": "",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -21,8 +21,10 @@
21
21
  "typescript": "^5.1.6"
22
22
  },
23
23
  "dependencies": {
24
+ "@keyv/mongo": "^3.0.3",
24
25
  "axios": "^1.7.9",
25
26
  "dayjs": "^1.11.13",
27
+ "keyv": "^5.5.0",
26
28
  "mongoose": "^8.5.2"
27
29
  }
28
30
  }