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
Merged
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
41 changes: 40 additions & 1 deletion src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,16 @@
import {Agent} from 'http';
import {URL} from 'url';

/* eslint-disable @typescript-eslint/no-explicit-any */
import {pkg} from './util';

/**
* Support `instanceof` operator for `GaxiosError`s in different versions of this library.
*
* @see {@link GaxiosError[Symbol.hasInstance]}
*/
export const GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`);

/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export class GaxiosError<T = any> extends Error {
/**
* An Error code.
Expand All @@ -34,6 +42,37 @@
*/
status?: number;

/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[Symbol.hasInstance]}
* @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200}
* @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior}
*/
[GAXIOS_ERROR_SYMBOL] = pkg.version;

/**
* Support `instanceof` operator for `GaxiosError` across builds/duplicated files.
*
* @see {@link GAXIOS_ERROR_SYMBOL}
* @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]}
*/
static [Symbol.hasInstance](instance: unknown) {
if (
instance &&
typeof instance === 'object' &&
GAXIOS_ERROR_SYMBOL in instance &&
instance[GAXIOS_ERROR_SYMBOL] === pkg.version
) {
return true;
}

// fallback to native
return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance);
}

constructor(
message: string,
public config: GaxiosOptions,
Expand Down Expand Up @@ -80,15 +119,15 @@
}

export interface Headers {
[index: string]: any;

Check warning on line 122 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
}
export type GaxiosPromise<T = any> = Promise<GaxiosResponse<T>>;

Check warning on line 124 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

export interface GaxiosXMLHttpRequest {
responseURL: string;
}

export interface GaxiosResponse<T = any> {

Check warning on line 130 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
config: GaxiosOptions;
data: T;
status: number;
Expand All @@ -105,7 +144,7 @@
* Optional method to override making the actual HTTP request. Useful
* for writing tests.
*/
adapter?: <T = any>(

Check warning on line 147 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
options: GaxiosOptions,
defaultAdapter: (options: GaxiosOptions) => GaxiosPromise<T>
) => GaxiosPromise<T>;
Expand All @@ -123,8 +162,8 @@
| 'TRACE'
| 'PATCH';
headers?: Headers;
data?: any;

Check warning on line 165 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
body?: any;

Check warning on line 166 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
/**
* The maximum size of the http response content in bytes allowed.
*/
Expand All @@ -134,13 +173,13 @@
*/
maxRedirects?: number;
follow?: number;
params?: any;

Check warning on line 176 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
paramsSerializer?: (params: {[index: string]: string | number}) => string;
timeout?: number;
/**
* @deprecated ignored
*/
onUploadProgress?: (progressEvent: any) => void;

Check warning on line 182 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
responseType?:
| 'arraybuffer'
| 'blob'
Expand All @@ -154,7 +193,7 @@
retry?: boolean;
// Should be instance of https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
// interface. Left as 'any' due to incompatibility between spec and abort-controller.
signal?: any;

Check warning on line 196 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
size?: number;
/**
* Implementation of `fetch` to use when making the API call. By default,
Expand Down Expand Up @@ -186,7 +225,7 @@
*
* @experimental
*/
export type RedactableGaxiosResponse<T = any> = Pick<

Check warning on line 228 in src/common.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
GaxiosResponse<T>,
'config' | 'data' | 'headers'
>;
Expand Down
17 changes: 17 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2023 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export const pkg: {
name: string;
version: string;
} = require('../../package.json');
14 changes: 14 additions & 0 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {
GaxiosResponse,
GaxiosPromise,
} from '../src';
import {GAXIOS_ERROR_SYMBOL} from '../src/common';
import {pkg} from '../src/util';
import qs from 'querystring';
import fs from 'fs';
import {Blob} from 'node-fetch';
Expand Down Expand Up @@ -119,6 +121,18 @@ describe('🚙 error handling', () => {
assert(error.response, undefined);
assert.equal(error.response.data, notJSON);
});

it('should support `instanceof` for GaxiosErrors of the same version', () => {
class A extends GaxiosError {}

const wrongVersion = {[GAXIOS_ERROR_SYMBOL]: '0.0.0'};
const correctVersion = {[GAXIOS_ERROR_SYMBOL]: pkg.version};
const child = new A('', {});

assert.equal(wrongVersion instanceof GaxiosError, false);
assert.equal(correctVersion instanceof GaxiosError, true);
assert.equal(child instanceof GaxiosError, true);
});
});

describe('🥁 configuration options', () => {
Expand Down