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

fix: JSON.stringify cannot serialize cyclic structures. #205

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
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;
};
}

9 changes: 5 additions & 4 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 @@ -204,7 +205,7 @@ export class Rest {
public resolve(identifier: string): Promise<LavalinkResponse | undefined> {
const options = {
endpoint: '/loadtracks',
options: { params: { identifier }}
options: { params: { identifier } }
};
return this.fetch(options);
}
Expand All @@ -217,7 +218,7 @@ export class Rest {
public decode(track: string): Promise<Track | undefined> {
const options = {
endpoint: '/decodetrack',
options: { params: { track }}
options: { params: { track } }
};
return this.fetch<Track>(options);
}
Expand Down Expand Up @@ -378,8 +379,8 @@ export class Rest {
signal: abortController.signal
};

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

const request = await fetch(url.toString(), finalFetchOptions)
.finally(() => clearTimeout(timeout));
Expand Down