/proxy-hooks

⚓ A zero dependency JS proxy wrapper for ease of use with first class TS support!

Primary LanguageTypeScriptMIT LicenseMIT

⚓ proxy-hooks

All Contributors License Last Commit Stars Forks

Philosophy

I built this pkg with the primary intention of making the use of Proxy simple and easy. Additionally it also provides the functionality api of other projects like tinyspy and nanospy via the hooks methodArguments and methodReturn

Usage

import Spy from "proxy-hooks";
const originalSource = {
  name: "Joe",
  printName(name) {
    return name;
  },
  printObjName() {
    return this.name;
  },
}; // originalSource can also be a function
const handler = {
  canGet() {
    return true;
  },
  tapGet(target, prop, receiver) {
    return Reflect.get(...arguments);
  },
  methodArguments(cachedInfo, args) {
    args[0] = args[0] + "Wallace";
    return args;
  },
  methodReturn(cachedInfo, returnVal) {
    if (cachedInfo.propName === "printObjName") {
      return "Joe Biden Modified";
    }
    return returnVal;
  },
};
const [proxy, revokeProxy] = Spy(orignalSource, handler);
expect(obj.printName("Jipy")).toBe("JipyWallace");
expect(obj.printObjName()).toBe("Joe Biden Modified");
revokeProxy.revoke();

The Handler object has the following type signature. It can accept other native proxy methods as well other than get,set and apply.

type Handler<T extends Object> = Partial<
  {
    canGet: (descriptor: Descriptor) => boolean;
    canSet: (descriptor: Descriptor, oldValue: any, newValue: any) => boolean;
    tapGet: TapSignature<T>;
    tapSet: TapSignature<T>;
    methodArguments: (
      cachedKnowledge: {
        propName: string | symbol;
        calls: number;
        results: any[];
      },
      args: any[],
    ) => any[];
    methodReturn: (
      cachedKnowledge: {
        propName: string | symbol;
        calls: number;
        results: any[];
      },
      result: any,
    ) => any | void;
  } & Omit<ProxyHandler<T>, "get" | "set" | "apply">
>;

Checks its types.d.ts file for complete API.

Installation

npm i proxy-hookified or yarn add proxy-hookified

🎉 Contributing

Contributions are welcome! Whether it is a small documentation change or a breaking feature, we welcome it!

Please note: All contributions are taken under the MIT license

👥 Contributors