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: Add options to ignore specific urls and regex patterns #70

Merged
merged 1 commit into from
Jan 5, 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
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,39 @@ startNetworkLogging({ maxRequests: 500 });

#### Ignored Hosts

You can configure urls/hosts that should be ignored by calling `startNetworkLogging` with the `ignoredHosts` option.
You can configure hosts that should be ignored by calling `startNetworkLogging` with the `ignoredHosts` option.

```ts
startNetworkLogging({ ignoredHosts: ['test.example.com'] });
```

#### Ignored Urls

You can configure urls that should be ignored by calling `startNetworkLogging` with the `ignoredUrls` option.

```ts
startNetworkLogging({ ignoredUrls: ['https://test.example.com/page'] });
```

#### Ignored Patterns

You can configure url patterns, including methods that should be ignored by calling `startNetworkLogging` with the `ignoredPatterns` option.

```ts
startNetworkLogging({
ignoredPatterns: [/^GET http:\/\/test\.example\.com\/pages\/.*$/],
});
```

The pattern to match with is the method followed by the url, e.g. `GET http://example.com/test` so you can use the pattern to match anything, e.g. ignoring all HEAD requests.

```ts
startNetworkLogging({
// Ignore all HEAD requests
ignoredPatterns: [/^HEAD /],
});
```

#### Sorting

Set the sort order of requests. Options are `asc` or `desc`, default is `desc` (most recent at the top).
Expand Down
7 changes: 7 additions & 0 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export default function App() {
method: 'POST',
body: formData,
});
fetch('https://httpstat.us/200', { method: 'HEAD' });
fetch('https://postman-echo.com/put', {
method: 'PUT',
body: JSON.stringify({ test: 'hello' }),
});
fetch('https://httpstat.us/302');
fetch('https://httpstat.us/400');
fetch('https://httpstat.us/500');
Expand All @@ -45,6 +50,8 @@ export default function App() {
startNetworkLogging({
ignoredHosts: ['192.168.1.28', '127.0.0.1'],
maxRequests: 500,
ignoredUrls: ['https://httpstat.us/other'],
ignoredPatterns: [/^POST http:\/\/(192|10)/],
});

const [theme, setTheme] = useState<ThemeName>('dark');
Expand Down
31 changes: 31 additions & 0 deletions src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export default class Logger {
private xhrIdMap: { [key: number]: number } = {};
private maxRequests: number = 500;
private ignoredHosts: Set<string> | undefined;
private ignoredUrls: Set<string> | undefined;
private ignoredPatterns: RegExp[] | undefined;
public enabled = false;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -52,6 +54,18 @@ export default class Logger {
}
}

if (this.ignoredUrls && this.ignoredUrls.has(url)) {
return;
}

if (this.ignoredPatterns) {
if (
this.ignoredPatterns.some((pattern) => pattern.test(`${method} ${url}`))
) {
return;
}
}

const newRequest = new NetworkRequestInfo(
`${nextXHRId}`,
'XMLHttpRequest',
Expand Down Expand Up @@ -152,6 +166,23 @@ export default class Logger {
this.ignoredHosts = new Set(options.ignoredHosts);
}

if (options?.ignoredPatterns) {
Copy link

Choose a reason for hiding this comment

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

this.ignoredPatterns = options?.ignoredPatterns ?? [];

Would shrink the code down

Copy link
Owner Author

Choose a reason for hiding this comment

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

The code above where it gets used actually relies on it being undefined. I might just leave it to keep it consistent with the ignoredHosts option.

this.ignoredPatterns = options.ignoredPatterns;
}

if (options?.ignoredUrls) {
if (
!Array.isArray(options.ignoredUrls) ||
typeof options.ignoredUrls[0] !== 'string'
) {
warn(
Copy link

Choose a reason for hiding this comment

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

this may be better as a throw Error() rather than a warning. This will prompt the developer to fix their code.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Yeah, I can't remember why I did the warning as it was a while ago when I set it up. I would probably accept a PR updating it.

'ignoredUrls must be an array of strings. The logger has not been started.'
);
return;
}
this.ignoredUrls = new Set(options.ignoredUrls);
}

XHRInterceptor.setOpenCallback(this.openCallback);
XHRInterceptor.setRequestHeaderCallback(this.requestHeadersCallback);
XHRInterceptor.setHeaderReceivedCallback(this.headerReceivedCallback);
Expand Down
67 changes: 67 additions & 0 deletions src/__tests__/Logger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ describe('enableXHRInterception', () => {
expect(ignoredHosts?.has('test.example.com')).toBeTruthy();
});

it('should update the ignoredUrls if provided', () => {
const logger = new Logger();

logger.enableXHRInterception({
ignoredUrls: ['http://test.example.com/test'],
});
// @ts-ignore
const ignoredUrls = logger.ignoredUrls;

expect(ignoredUrls).toBeInstanceOf(Set);
expect(ignoredUrls?.has('http://test.example.com/test')).toBeTruthy();
});

it('should update the ignoredPatterns if provided', () => {
const logger = new Logger();

logger.enableXHRInterception({
ignoredPatterns: [/^HEAD /],
});
// @ts-ignore
const ignoredPatterns = logger.ignoredPatterns;

expect(ignoredPatterns).toEqual([/^HEAD /]);
});

it('should call setOpenCallback', () => {
const logger = new Logger();
logger.enableXHRInterception();
Expand Down Expand Up @@ -225,4 +250,46 @@ describe('openCallback', () => {
expect(logger.getRequests()[0].url).toEqual(url1);
expect(logger.getRequests()).toHaveLength(1);
});

it('should ignore requests that have ignored urls', () => {
const logger = new Logger();
logger.enableXHRInterception({ ignoredUrls: ['http://ignored.com/test'] });

const xhr = {};
const url1 = 'http://ignored.com/1';
const url2 = 'http://ignored.com/test';

// @ts-expect-error
logger.openCallback('POST', url1, xhr);
// @ts-expect-error
logger.openCallback('POST', url2, xhr);
expect(logger.getRequests()[0].url).toEqual(url1);
expect(logger.getRequests()).toHaveLength(1);
});

it('should ignore requests that match pattern', () => {
const logger = new Logger();
logger.enableXHRInterception({
ignoredPatterns: [/^HEAD /, /^POST http:\/\/ignored/],
});

const xhr = {};
const url1 = 'http://allowed.com/1';
const url2 = 'http://ignored.com/test';

// @ts-expect-error
logger.openCallback('POST', url1, xhr);
// @ts-expect-error
logger.openCallback('POST', url2, xhr);
// @ts-expect-error
logger.openCallback('HEAD', url2, xhr);
// @ts-expect-error
logger.openCallback('PUT', url2, xhr);
// Requests should be in reverse order
expect(logger.getRequests()[1].url).toEqual(url1);
expect(logger.getRequests()[1].method).toEqual('POST');
expect(logger.getRequests()[0].url).toEqual(url2);
expect(logger.getRequests()[0].method).toEqual('PUT');
expect(logger.getRequests()).toHaveLength(2);
});
});
18 changes: 14 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
export type Headers = { [header: string]: string };

// export type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export type RequestMethod = 'GET' | 'POST' | 'UPDATE' | 'DELETE';
export type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';

export type StartNetworkLoggingOptions = {
/** Max number of requests to keep before overwriting, default 500 */
/**
* Max number of requests to keep before overwriting
* @default 500
*/
maxRequests?: number;
/** List of hosts to ignore, e.g. services.test.com */
/** List of hosts to ignore, e.g. `services.test.com` */
ignoredHosts?: string[];
/** List of urls to ignore, e.g. `https://services.test.com/test` */
ignoredUrls?: string[];
/**
* List of url patterns to ignore, e.g. `/^GET https://test.com\/pages\/.*$/`
*
* Url to match with is in the format: `${method} ${url}`, e.g. `GET https://test.com/pages/123`
*/
ignoredPatterns?: RegExp[];
/**
* Force the network logger to start even if another program is using the network interceptor
* e.g. a dev/debuging program
Expand Down