MCPcopy
hub / github.com/parse-community/parse-server / wrapMethod

Function wrapMethod

benchmark/MongoLatencyWrapper.js:30–72  ·  view source on GitHub ↗

* Wrap a Collection method to add artificial latency * @param {string} methodName - Name of the method to wrap * @param {number} latencyMs - Delay in milliseconds

(methodName, latencyMs)

Source from the content-addressed store, hash-verified

28 * @param {number} latencyMs - Delay in milliseconds
29 */
30function wrapMethod(methodName, latencyMs) {
31 if (!originalMethods.has(methodName)) {
32 originalMethods.set(methodName, Collection.prototype[methodName]);
33 }
34
35 const originalMethod = originalMethods.get(methodName);
36
37 Collection.prototype[methodName] = function (...args) {
38 // For methods that return cursors (like find, aggregate), we need to delay the execution
39 // but still return a cursor-like object
40 const result = originalMethod.apply(this, args);
41
42 // Check if result has cursor methods (toArray, forEach, etc.)
43 if (result && typeof result.toArray === 'function') {
44 // Wrap cursor methods that actually execute the query
45 const originalToArray = result.toArray.bind(result);
46 result.toArray = function() {
47 // Wait for the original promise to settle, then delay the result
48 return originalToArray().then(
49 value => new Promise(resolve => setTimeout(() => resolve(value), latencyMs)),
50 error => new Promise((_, reject) => setTimeout(() => reject(error), latencyMs))
51 );
52 };
53 return result;
54 }
55
56 // For promise-returning methods, wrap the promise with delay
57 if (result && typeof result.then === 'function') {
58 // Wait for the original promise to settle, then delay the result
59 return result.then(
60 value => new Promise(resolve => setTimeout(() => resolve(value), latencyMs)),
61 error => new Promise((_, reject) => setTimeout(() => reject(error), latencyMs))
62 );
63 }
64
65 // For synchronous methods, just add delay
66 return new Promise((resolve) => {
67 setTimeout(() => {
68 resolve(result);
69 }, latencyMs);
70 });
71 };
72}
73
74/**
75 * Wrap MongoDB Collection methods with artificial latency

Callers 1

wrapMongoDBWithLatencyFunction · 0.85

Calls 2

resolveFunction · 0.50
getMethod · 0.45

Tested by

no test coverage detected