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

feat: Extend instanceof Support for GaxiosError #593

Merged
merged 1 commit into from
Dec 7, 2023

Conversation

danielbankhead
Copy link
Contributor

Improve instanceOf Support for GaxiosError

There are a number of reasons instanceof could provide false-negatives:

This PR aims to keep instanceof consistent and predictable across builds, in a supported, conventional way:

Background for why this is needed:

Future Follow-ups

In the future we could create a utility to support the functionality for any class. E.g.:

function addInstanceOfSupport<T extends Function>(
  constructor: T,
  pkgInfo: typeof pkg
) {
  // Generate unique, predictable symbol
  const symbol = Symbol.for(`${pkgInfo.name}-${constructor.name}`);
  // Set symbol on constructor
  const c = constructor as unknown as {[symbol]: string};
  c[symbol] = pkgInfo.version;

  // keep original call
  const original = constructor[Symbol.hasInstance];

  function instanceofWithSymbolCheck(instance: unknown) {
    if (
      instance &&
      typeof instance === 'object' &&
      symbol in instance &&
      instance[symbol] === pkgInfo.version
    ) {
      return true;
    }

    // fallback to original call
    return original.call(constructor, instance);
  }

  constructor[Symbol.hasInstance] = instanceofWithSymbolCheck;
}

// example
addInstanceOfSupport(GaxiosError, pkg);

🦕

@danielbankhead danielbankhead requested a review from a team as a code owner December 6, 2023 23:09
@product-auto-label product-auto-label bot added the size: m Pull request size is medium. label Dec 6, 2023
@danielbankhead danielbankhead changed the title feat: Extend instanceof Support for GaxiosError feat: Extend instanceof Support for GaxiosError Dec 6, 2023
@danielbankhead danielbankhead merged commit 4fd1fe2 into main Dec 7, 2023
15 checks passed
@danielbankhead danielbankhead deleted the extend-gaxios-error-instanceof-support branch December 7, 2023 18:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size: m Pull request size is medium.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants