Skip to content

Commit

Permalink
feat: remove in class and add to Utils getCircularReplacer(), ref: ht…
Browse files Browse the repository at this point in the history
  • Loading branch information
aomkoyo committed Nov 6, 2024
1 parent e1c751d commit a0453d0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
19 changes: 19 additions & 0 deletions src/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,22 @@ export function mergeDefault<T extends Record<string, any>>(def: T, given: T): R
export function wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}


export function getCircularReplacer(): (key: string, value: any) => any {
const ancestors: any[] = [];
return function (this: any, key: string, value: any): any {
if (typeof value !== "object" || value === null) {
return value;
}
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return "[Circular]";
}
ancestors.push(value);
return value;
};
}

15 changes: 2 additions & 13 deletions src/node/Rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { Versions } from '../Constants';
import { FilterOptions } from '../guild/Player';
import { NodeOption } from '../Shoukaku';
import { getCircularReplacer } from '../Utils';
import { Node, NodeInfo, Stats } from './Node';

export type Severity = 'common' | 'suspicious' | 'fault';
Expand Down Expand Up @@ -379,7 +380,7 @@ export class Rest {
};

if (!['GET', 'HEAD'].includes(method) && options.body)
finalFetchOptions.body = JSON.stringify(options.body, this.removeCircularReferences());
finalFetchOptions.body = JSON.stringify(options.body, getCircularReplacer());

const request = await fetch(url.toString(), finalFetchOptions)
.finally(() => clearTimeout(timeout));
Expand All @@ -402,18 +403,6 @@ export class Rest {
return;
}
}
private removeCircularReferences() {
const seen = new WeakSet();
return (key: string, value: unknown) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return; // Skip circular reference
}
seen.add(value);
}
return value;
};
}
}

interface LavalinkRestError {
Expand Down

0 comments on commit a0453d0

Please sign in to comment.