Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(common): apply decorators function #3999

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/@webex/common/src/apply-decorators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* This applies decorators to an ampersand state object
* It wraps the function in the order the decorators are provided
* This means that when you call the method, the decorators are applied in reverse order
* @param {*} object - The object to apply the decorators to
* @param {*} decoratedMethods
* @returns {undefined}
*/
export function applyDecorators(object, decoratedMethods) {
Object.entries(decoratedMethods).forEach(([method, decorators]) => {
object[method] = decorators.reduce(
(decorated, decorator) => decorator(decorated),
object[method]
);
});
}
Comment on lines +9 to +16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation to prevent runtime errors.

The function should validate its inputs to ensure robust operation and provide clear error messages.

 export function applyDecorators(object, decoratedMethods) {
+  if (!object || typeof object !== 'object') {
+    throw new TypeError('First argument must be an object');
+  }
+  if (!decoratedMethods || typeof decoratedMethods !== 'object') {
+    throw new TypeError('Second argument must be an object mapping methods to decorators');
+  }
+
   Object.entries(decoratedMethods).forEach(([method, decorators]) => {
+    if (!Array.isArray(decorators)) {
+      throw new TypeError(`Decorators for method "${method}" must be an array`);
+    }
+    if (typeof object[method] !== 'function') {
+      throw new TypeError(`"${method}" is not a method on the target object`);
+    }
+    if (!decorators.every((d) => typeof d === 'function')) {
+      throw new TypeError(`All decorators for method "${method}" must be functions`);
+    }
+
     object[method] = decorators.reduce(
       (decorated, decorator) => decorator(decorated),
       object[method]
     );
   });
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function applyDecorators(object, decoratedMethods) {
Object.entries(decoratedMethods).forEach(([method, decorators]) => {
object[method] = decorators.reduce(
(decorated, decorator) => decorator(decorated),
object[method]
);
});
}
export function applyDecorators(object, decoratedMethods) {
if (!object || typeof object !== 'object') {
throw new TypeError('First argument must be an object');
}
if (!decoratedMethods || typeof decoratedMethods !== 'object') {
throw new TypeError('Second argument must be an object mapping methods to decorators');
}
Object.entries(decoratedMethods).forEach(([method, decorators]) => {
if (!Array.isArray(decorators)) {
throw new TypeError(`Decorators for method "${method}" must be an array`);
}
if (typeof object[method] !== 'function') {
throw new TypeError(`"${method}" is not a method on the target object`);
}
if (!decorators.every((d) => typeof d === 'function')) {
throw new TypeError(`All decorators for method "${method}" must be functions`);
}
object[method] = decorators.reduce(
(decorated, decorator) => decorator(decorated),
object[method]
);
});
}


export default {
applyDecorators,
};
Comment on lines +18 to +20
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Consider removing default export since only named export is used

The codebase exclusively uses the named import {applyDecorators}, making the default export unnecessary. For better code maintainability and to avoid confusion, consider removing the default export and keeping only the named export.

  • packages/@webex/common/src/apply-decorators.js: Remove default export and keep only export { applyDecorators }
🔗 Analysis chain

Verify import usage consistency across the codebase.

Having both named and default exports is fine, but let's ensure they're used consistently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check how this module is imported across the codebase
rg -t js "import.*from.*apply-decorators" 

Length of output: 169

1 change: 1 addition & 0 deletions packages/@webex/common/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export {default as whileInFlight} from './while-in-flight';
export {default as Exception} from './exception';
export {default as deprecated} from './deprecated';
export {default as inBrowser} from './in-browser';
export {default as applyDecorators} from './apply-decorators';
export {
deviceType,
hydraTypes,
Expand Down
35 changes: 35 additions & 0 deletions packages/@webex/common/test/unit/spec/apply-decorators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {assert} from '@webex/test-helper-chai';
import sinon from 'sinon';
import {applyDecorators} from '@webex/common/src/apply-decorators';

describe('applyDecorators()', () => {
it('applies the decorators in order', () => {
Comment on lines +5 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding more test cases

The test suite currently only verifies the order of decorator application. Given that this PR addresses VSCode issues with ampersand state objects, consider adding test cases for:

  • Error handling scenarios
  • Edge cases (e.g., empty decorator array, undefined methods)
  • Integration with ampersand state objects

Would you like me to help generate these additional test cases?

const method = sinon.stub();

const obj = {
method
}

const decorator1 = (fn) => {
return function decorated1() {
fn.apply(this, [...arguments, 'decorated1']);
};
}

const decorator2 = (fn) => {
return function decorated2() {
fn.apply(this, [...arguments, 'decorated2']);
};
}

applyDecorators(obj, {
method: [decorator1, decorator2]
});

obj.method('arg');

assert.calledOnce(method);

assert.calledWithExactly(method, 'arg', 'decorated2', 'decorated1');
});
});
24 changes: 13 additions & 11 deletions packages/@webex/internal-plugin-device/src/device.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Internal Dependencies
import {deprecated, oneFlight} from '@webex/common';
import {deprecated, oneFlight, applyDecorators} from '@webex/common';
import {persist, waitForValue, WebexPlugin} from '@webex/webex-core';
import {safeSetTimeout} from '@webex/common-timers';

Expand Down Expand Up @@ -367,12 +367,10 @@ const Device = WebexPlugin.extend({
/**
* Refresh the current registered device if able.
*
* @param {DeviceRegistrationOptions} options - The options for refresh.
* @param {DeviceRegistrationOptions} deviceRegistrationOptions - The options for refresh.
* @param {CatalogDetails} options.includeDetails - The details to include in the refresh/register request.
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
refresh(deviceRegistrationOptions = {}) {
this.logger.info('device: refreshing');

Expand Down Expand Up @@ -445,12 +443,10 @@ const Device = WebexPlugin.extend({
* registration utilizes the services plugin to send the request to the
* **WDM** service.
*
* @param {Object} options - The options for registration.
* @param {Object} deviceRegistrationOptions - The options for registration.
* @param {CatalogDetails} options.includeDetails - The details to include in the refresh/register request.
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
register(deviceRegistrationOptions = {}) {
this.logger.info('device: registering');

Expand Down Expand Up @@ -535,8 +531,6 @@ const Device = WebexPlugin.extend({
*
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
unregister() {
this.logger.info('device: unregistering');

Expand Down Expand Up @@ -828,7 +822,6 @@ const Device = WebexPlugin.extend({
* @param {string} url - The url to mark as failed.
* @returns {Promise<string>} - The next priority url.
*/
@deprecated('device#markUrlFailedAndGetNew(): Use services#markFailedUrl()')
markUrlFailedAndGetNew(url) {
return Promise.resolve(this.webex.internal.services.markFailedUrl(url));
},
Expand All @@ -843,7 +836,6 @@ const Device = WebexPlugin.extend({
* @param {Array<any>} args - An array of items to be mapped as properties.
* @returns {void}
*/
@persist('@', decider)
initialize(...args) {
// Prototype the extended class in order to preserve the parent member.
Reflect.apply(WebexPlugin.prototype.initialize, this, args);
Expand Down Expand Up @@ -891,4 +883,14 @@ const Device = WebexPlugin.extend({
/* eslint-enable require-jsdoc */
});

applyDecorators(Device, {
register: [waitForValue('@'), oneFlight],
refresh: [waitForValue('@'), oneFlight],
unregister: [waitForValue('@'), oneFlight],
markUrlFailedAndGetNew: [
deprecated('device#markUrlFailedAndGetNew(): Use services#markFailedUrl()'),
],
initialize: [persist('@', decider)],
});

export default Device;
Loading