| 14 | export function stringify(value: Promise<any>, options?: { format?: boolean; types?: (new () => any)[] }): Promise<string>; |
| 15 | export function stringify(value: any, options?: { format?: boolean; types?: (new () => any)[] }): string; |
| 16 | export function stringify(value: any, options?: { format?: boolean; types?: (new () => any)[] }): string | Promise<string> { |
| 17 | if (is.promise(value)) { |
| 18 | return value.then(v => stringify(v)); |
| 19 | } |
| 20 | const types = options?.types ?? []; |
| 21 | const format = options?.format ?? false; |
| 22 | |
| 23 | const visited = new WeakSet(); |
| 24 | |
| 25 | return JSON.stringify(value, (key: any, value: any) => { |
| 26 | if (typeof value === 'object' && value !== null) { |
| 27 | if (visited.has(value)) { |
| 28 | return '[\'Circular\']'; |
| 29 | } |
| 30 | visited.add(value); |
| 31 | } |
| 32 | if (value?.constructor?.name === 'Error' || types.filter(each => value instanceof each).length) { |
| 33 | const result = {} as Record<string, any>; |
| 34 | Object.getOwnPropertyNames(value).forEach((propName) => result[propName] = (value as any)[propName]); |
| 35 | return result; |
| 36 | } |
| 37 | return value; |
| 38 | }, format ? 2 : undefined); |
| 39 | } |