Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active June 24, 2021 11:39
Show Gist options
  • Save karol-majewski/7b8738d42921b833484325e1ec535a9a to your computer and use it in GitHub Desktop.
Save karol-majewski/7b8738d42921b833484325e1ec535a9a to your computer and use it in GitHub Desktop.
Using JavaScript Proxies with TypeScript
import LR from 'logrocket';
/**
* Fails silently if `LogRocket#init` throws.
*
* @see https://stackoverflow.com/a/43823282/10325032
*/
export const LogRocket = new Proxy(LR, {
get(target, property: keyof typeof LR, receiver) {
if (property === 'init') {
return new Proxy(target[property], {
apply(applyTarget, thisArg, args) {
try {
return Reflect.apply(applyTarget, thisArg, args);
} catch (error: unknown) {
console.error(`Failed to call ${thisArg.constructor.name}.${property} with arguments ${args}`, error);
}
},
});
}
return Reflect.get(target, property, receiver);
},
});
LogRocket.init('<some-invalid-app-ID>');
@karol-majewski
Copy link
Author

karol-majewski commented Jun 24, 2021

A revokable version:

import LR from 'logrocket';

/**
 * Fails silently if `LogRocket#init` throws.
 *
 * @see https://stackoverflow.com/a/43823282/10325032
 */
export const { proxy: LogRocket, revoke: prime } = Proxy.revocable(LR, {
  get(target, property: keyof typeof LR, receiver) {
    if (property === 'init') {
      return new Proxy(target[property], {
        apply(applyTarget, thisArg, args) {
          try {
            return Reflect.apply(applyTarget, thisArg, args);
          } catch (error: unknown) {
            console.error(`Failed to call ${thisArg.constructor.name}.${property} with arguments ${args}`, error);
          }
        },
      });
    }

    return Reflect.get(target, property, receiver);
  },
});

LogRocket.init('<some-invalid-app-ID>');

prime();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment