Skip to content

Commit

Permalink
feat(#796): add support for better Buffer JSON stringify
Browse files Browse the repository at this point in the history
  • Loading branch information
AnWeber committed Nov 3, 2024
1 parent 7905f2d commit 10d03fd
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## [unreleased]

### Features
- add support for better Buffer JSON stringify (#796)

### Fix
- handle dom parser exception for invalid xml (#821)
- do not log stack on assertions error (AnWeber/vscode-httpyac#338)
Expand Down
37 changes: 36 additions & 1 deletion src/utils/stringUtils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { stateGenerator } from './stringUtils';
import { stateGenerator, stringifySafe } from './stringUtils';

describe('state generator', () => {
it('generates strings of the expected length', () => {
Expand All @@ -12,3 +12,38 @@ describe('state generator', () => {
expect(encoded).toBe(result);
});
});

describe('stringifySafe', () => {
it('should return json representation', () => {
expect(
stringifySafe({
foo: 'bar',
foo2: 2,
foo3: true,
})
).toEqual('{"foo":"bar","foo2":2,"foo3":true}');
});
it('should convert buffer to base64', () => {
expect(
stringifySafe({
value: Buffer.from('\n\x17outbound|3000||test0629'),
})
).toEqual('{"value":"ChdvdXRib3VuZHwzMDAwfHx0ZXN0MDYyOQ=="}');
});
it('should return base64 for buffer object', () => {
expect(stringifySafe(Buffer.from('\n\x17outbound|3000||test0629'))).toEqual(
'"ChdvdXRib3VuZHwzMDAwfHx0ZXN0MDYyOQ=="'
);
});
it('should handle circular object', () => {
const foo: Record<string, unknown> = {
foo: 'foo',
};
const bar: Record<string, unknown> = {
bar: 'bar',
foo,
};
foo.bar = bar;
expect(stringifySafe(foo)).toEqual('{"foo":"foo","bar":{"bar":"bar"}}');
});
});
16 changes: 15 additions & 1 deletion src/utils/stringUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,16 @@ export function toString(value: unknown): string | undefined {

export function stringifySafe(obj: unknown, indent = 0) {
try {
return JSON.stringify(obj, null, indent);
return JSON.stringify(
obj,
(_, value) => {
if (isJsonBuffer(value)) {
return Buffer.from(value.data).toString('base64');
}
return value;
},
indent
);
} catch (err) {
log.debug(`JSON.stringify error`, err);
const getCircularReplacer = () => {
Expand Down Expand Up @@ -86,3 +95,8 @@ export function ensureString(value: unknown): string | null | undefined {
}
return `${value}`;
}

function isJsonBuffer(value: unknown): value is { type: string; data: Array<number> } {
const val = value as { type: string; data: Array<number> };
return val?.type === 'Buffer' && Array.isArray(val.data) && !!val.data.length;
}

0 comments on commit 10d03fd

Please sign in to comment.