* Wrap MongoDB Collection methods with artificial latency * @param {number} latencyMs - Delay in milliseconds to inject before each operation * @returns {Function} unwrap - Function to restore original methods
(latencyMs)
| 77 | * @returns {Function} unwrap - Function to restore original methods |
| 78 | */ |
| 79 | function wrapMongoDBWithLatency(latencyMs) { |
| 80 | if (typeof latencyMs !== 'number' || latencyMs < 0) { |
| 81 | throw new Error('latencyMs must be a non-negative number'); |
| 82 | } |
| 83 | |
| 84 | if (latencyMs === 0) { |
| 85 | // eslint-disable-next-line no-console |
| 86 | console.log('Latency is 0ms, skipping MongoDB wrapping'); |
| 87 | return () => {}; // No-op unwrap function |
| 88 | } |
| 89 | |
| 90 | // eslint-disable-next-line no-console |
| 91 | console.log(`Wrapping MongoDB operations with ${latencyMs}ms artificial latency`); |
| 92 | |
| 93 | // List of MongoDB Collection methods to wrap |
| 94 | const methodsToWrap = [ |
| 95 | 'find', |
| 96 | 'findOne', |
| 97 | 'countDocuments', |
| 98 | 'estimatedDocumentCount', |
| 99 | 'distinct', |
| 100 | 'aggregate', |
| 101 | 'insertOne', |
| 102 | 'insertMany', |
| 103 | 'updateOne', |
| 104 | 'updateMany', |
| 105 | 'replaceOne', |
| 106 | 'deleteOne', |
| 107 | 'deleteMany', |
| 108 | 'findOneAndUpdate', |
| 109 | 'findOneAndReplace', |
| 110 | 'findOneAndDelete', |
| 111 | 'createIndex', |
| 112 | 'createIndexes', |
| 113 | 'dropIndex', |
| 114 | 'dropIndexes', |
| 115 | 'drop', |
| 116 | ]; |
| 117 | |
| 118 | methodsToWrap.forEach(methodName => { |
| 119 | wrapMethod(methodName, latencyMs); |
| 120 | }); |
| 121 | |
| 122 | // Return unwrap function to restore original methods |
| 123 | return function unwrap() { |
| 124 | // eslint-disable-next-line no-console |
| 125 | console.log('Removing MongoDB latency wrapper, restoring original methods'); |
| 126 | |
| 127 | originalMethods.forEach((originalMethod, methodName) => { |
| 128 | Collection.prototype[methodName] = originalMethod; |
| 129 | }); |
| 130 | |
| 131 | originalMethods.clear(); |
| 132 | }; |
| 133 | } |
| 134 | |
| 135 | module.exports = { |
| 136 | wrapMongoDBWithLatency, |
no test coverage detected