|
1 | 1 | import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' |
2 | 2 | import { logger } from '@socketsecurity/registry/lib/logger' |
| 3 | +import { isObject } from '@socketsecurity/registry/lib/objects' |
3 | 4 |
|
4 | 5 | import type { CResult } from '../types.mts' |
5 | 6 |
|
6 | 7 | // Serialize the final result object before printing it |
7 | 8 | // All commands that support the --json flag should call this before printing |
8 | 9 | export function serializeResultJson(data: CResult<unknown>): string { |
9 | | - if (typeof data !== 'object' || !data) { |
| 10 | + if (!isObject(data)) { |
10 | 11 | process.exitCode = 1 |
11 | | - debugFn('inspect', 'typeof data=', typeof data) |
12 | 12 |
|
13 | | - if (typeof data !== 'object' && data) { |
14 | | - debugFn('inspect', 'data:\n', data) |
15 | | - } |
| 13 | + debugFn('inspect', { data }) |
16 | 14 |
|
17 | 15 | // We should not allow the JSON value to be "null", or a boolean/number/string, |
18 | 16 | // even if they are valid "json". |
19 | | - const message = |
20 | | - 'There was a problem converting the data set to JSON. The JSON was not an object. Please try again without --json' |
21 | | - |
22 | | - return ( |
23 | | - JSON.stringify({ |
24 | | - ok: false, |
25 | | - message: 'Unable to serialize JSON', |
26 | | - cause: message, |
27 | | - }).trim() + '\n' |
28 | | - ) |
| 17 | + return `${JSON.stringify({ |
| 18 | + ok: false, |
| 19 | + message: 'Unable to serialize JSON', |
| 20 | + cause: |
| 21 | + 'There was a problem converting the data set to JSON. The JSON was not an object. Please try again without --json', |
| 22 | + }).trim()}\n` |
29 | 23 | } |
30 | 24 |
|
31 | 25 | try { |
32 | | - return JSON.stringify(data, null, 2).trim() + '\n' |
| 26 | + return `${JSON.stringify(data, null, 2).trim()}\n` |
33 | 27 | } catch (e) { |
34 | 28 | process.exitCode = 1 |
35 | 29 |
|
36 | | - // This could be caused by circular references, which is an "us" problem |
37 | 30 | const message = |
38 | 31 | 'There was a problem converting the data set to JSON. Please try again without --json' |
| 32 | + |
39 | 33 | logger.fail(message) |
40 | 34 | debugDir('inspect', { error: e }) |
41 | | - return ( |
42 | | - JSON.stringify({ |
43 | | - ok: false, |
44 | | - message: 'Unable to serialize JSON', |
45 | | - cause: message, |
46 | | - }).trim() + '\n' |
47 | | - ) |
| 35 | + |
| 36 | + // This could be caused by circular references, which is an "us" problem. |
| 37 | + return `${JSON.stringify({ |
| 38 | + ok: false, |
| 39 | + message: 'Unable to serialize JSON', |
| 40 | + cause: message, |
| 41 | + }).trim()}\n` |
48 | 42 | } |
49 | 43 | } |
0 commit comments