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

Debounce new requests changes coming from the callback #90

Merged
merged 3 commits into from
Dec 22, 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
36 changes: 31 additions & 5 deletions src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import NetworkRequestInfo from './NetworkRequestInfo';
import { Headers, RequestMethod, StartNetworkLoggingOptions } from './types';
import extractHost from './utils/extractHost';
import { warn } from './utils/logger';
import debounce from './utils/debounce';
import { LOGGER_REFRESH_RATE, LOGGER_MAX_REQUESTS } from './constant';

let nextXHRId = 0;

Expand All @@ -14,19 +16,32 @@ type XHR = {
export default class Logger {
private requests: NetworkRequestInfo[] = [];
private xhrIdMap: Map<number, () => number> = new Map();
private maxRequests: number = 500;
private maxRequests: number = LOGGER_MAX_REQUESTS;
private refreshRate: number = LOGGER_REFRESH_RATE;
private latestRequestUpdatedAt: number = 0;
private ignoredHosts: Set<string> | undefined;
private ignoredUrls: Set<string> | undefined;
private ignoredPatterns: RegExp[] | undefined;
public enabled = false;
public paused = false;

callback = (_: any[]) => null;
callback = (_: NetworkRequestInfo[]) => null;

setCallback = (callback: any) => {
this.callback = callback;
};

debouncedCallback = debounce(() => {
if (
!this.latestRequestUpdatedAt ||
this.requests.some((r) => r.updatedAt > this.latestRequestUpdatedAt)
) {
this.latestRequestUpdatedAt = Date.now();
// prevent mutation of requests for all subscribers
this.callback([...this.requests]);
}
}, this.refreshRate);

private getRequest = (xhrIndex?: number) => {
if (xhrIndex === undefined) return undefined;
if (!this.xhrIdMap.has(xhrIndex)) return undefined;
Expand Down Expand Up @@ -114,7 +129,7 @@ export default class Logger {
startTime: Date.now(),
dataSent: data,
});
this.callback(this.requests);
this.debouncedCallback();
};

private responseCallback = (
Expand All @@ -133,7 +148,7 @@ export default class Logger {
responseURL,
responseType,
});
this.callback(this.requests);
this.debouncedCallback();
};

enableXHRInterception = (options?: StartNetworkLoggingOptions) => {
Expand Down Expand Up @@ -172,6 +187,16 @@ export default class Logger {
this.ignoredHosts = new Set(options.ignoredHosts);
}

if (options?.refreshRate) {
if (typeof options.refreshRate !== 'number' || options.refreshRate < 1) {
warn(
'refreshRate must be a number greater than 0. The logger has not been started.'
);
return;
}
this.refreshRate = options.refreshRate;
}

if (options?.ignoredPatterns) {
this.ignoredPatterns = options.ignoredPatterns;
}
Expand Down Expand Up @@ -205,7 +230,8 @@ export default class Logger {

clearRequests = () => {
this.requests = [];
this.callback(this.requests);
this.latestRequestUpdatedAt = 0;
this.debouncedCallback();
};

// dispose in tests
Expand Down
3 changes: 3 additions & 0 deletions src/NetworkRequestInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ export default class NetworkRequestInfo {
startTime: number = 0;
endTime: number = 0;
gqlOperation?: string;
updatedAt: number = 0;

constructor(id: string, type: string, method: RequestMethod, url: string) {
this.id = id;
this.type = type;
this.method = method;
this.url = url;
this.updatedAt = Date.now();
}

get duration() {
Expand Down Expand Up @@ -61,6 +63,7 @@ export default class NetworkRequestInfo {
const data = this.parseData(values.dataSent);
this.gqlOperation = data?.operationName;
}
this.updatedAt = Date.now();
}

private escapeQuotes(value: string) {
Expand Down
7 changes: 7 additions & 0 deletions src/__tests__/Logger.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import XHRInterceptor from 'react-native/Libraries/Network/XHRInterceptor';
import { warn } from '../utils/logger';
import Logger from '../Logger';
import { LOGGER_REFRESH_RATE } from '../constant';

jest.mock('react-native/Libraries/Blob/FileReader', () => ({}));
jest.mock('react-native/Libraries/Network/XHRInterceptor', () => ({
Expand Down Expand Up @@ -168,6 +169,8 @@ describe('getRequests', () => {

describe('clearRequests', () => {
it('should clear the requests', () => {
jest.useFakeTimers();

const logger = new Logger();

logger.callback = jest.fn();
Expand All @@ -177,9 +180,13 @@ describe('clearRequests', () => {

logger.clearRequests();

jest.advanceTimersByTime(LOGGER_REFRESH_RATE);

expect(logger.getRequests()).toEqual([]);
expect(logger.callback).toHaveBeenCalledTimes(1);
expect(logger.callback).toHaveBeenCalledWith([]);

jest.useRealTimers();
});
});

Expand Down
10 changes: 4 additions & 6 deletions src/components/NetworkLogger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ const sortRequests = (requests: NetworkRequestInfo[], sort: 'asc' | 'desc') => {
};

const NetworkLogger: React.FC<Props> = ({ theme = 'light', sort = 'desc' }) => {
const [requests, setRequests] = useState(
sortRequests(logger.getRequests(), sort)
);
const [requests, setRequests] = useState(logger.getRequests());
const [request, setRequest] = useState<NetworkRequestInfo>();
const [showDetails, _setShowDetails] = useState(false);
const [mounted, setMounted] = useState(false);
Expand All @@ -43,7 +41,7 @@ const NetworkLogger: React.FC<Props> = ({ theme = 'light', sort = 'desc' }) => {

useEffect(() => {
logger.setCallback((updatedRequests: NetworkRequestInfo[]) => {
setRequests(sortRequests(updatedRequests, sort));
setRequests([...updatedRequests]);
});

logger.enableXHRInterception();
Expand Down Expand Up @@ -104,8 +102,8 @@ const NetworkLogger: React.FC<Props> = ({ theme = 'light', sort = 'desc' }) => {
}, [paused, getHar]);

const requestsInfo = useMemo(() => {
return requests.map((r) => r.toRow());
}, [requests]);
return sortRequests(requests, sort).map((r) => r.toRow());
}, [sort, requests]);

return (
<ThemeContext.Provider value={theme}>
Expand Down
3 changes: 3 additions & 0 deletions src/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// StartNetworkLoggingOptions
export const LOGGER_MAX_REQUESTS: number = 500;
export const LOGGER_REFRESH_RATE: number = 50;
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export type StartNetworkLoggingOptions = {
* e.g. a dev/debuging program
*/
forceEnable?: boolean;
/**
* Refresh rate of the logger in milliseconds
* @default 50
*/
refreshRate?: number;
};

export type NetworkRequestInfoRow = Pick<
Expand Down
17 changes: 17 additions & 0 deletions src/utils/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_debounce
function debounce(func: Function, wait: number, immediate: boolean = false) {
let timeout: ReturnType<typeof setTimeout> | undefined;
return function () {
const args = arguments;
clearTimeout(timeout);
// @ts-ignore
if (immediate && !timeout) func.apply(this, args);
timeout = setTimeout(function () {
timeout = undefined;
// @ts-ignore
if (!immediate) func.apply(this, args);
}, wait);
};
}

export default debounce;
Loading