Skip to content

Commit

Permalink
feat: abstract stringify utility
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Nov 16, 2023
1 parent 49e4d1a commit 47fba2b
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Roarr.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createLogger } from './factories/createLogger';
import { createRoarrInitialGlobalState } from './factories/createRoarrInitialGlobalState';
import { type MessageSerializer, type RoarrGlobalState } from './types';
import safeStringify from 'safe-stable-stringify';
import { stringify } from './utilities/stringify';

const ROARR = createRoarrInitialGlobalState(
(globalThis.ROARR as RoarrGlobalState) || {},
Expand All @@ -10,7 +10,7 @@ const ROARR = createRoarrInitialGlobalState(
globalThis.ROARR = ROARR;

const serializeMessage: MessageSerializer = (message) => {
return safeStringify(message);
return stringify(message);
};

const Roarr = createLogger((message) => {
Expand Down
4 changes: 2 additions & 2 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createLogger } from './factories/createLogger';
import { createRoarrInitialGlobalStateBrowser } from './factories/createRoarrInitialGlobalStateBrowser';
import { type MessageSerializer, type RoarrGlobalState } from './types';
import safeStringify from 'safe-stable-stringify';
import { stringify } from './utilities/stringify';

const ROARR = createRoarrInitialGlobalStateBrowser(
(globalThis.ROARR as RoarrGlobalState) || {},
Expand All @@ -10,7 +10,7 @@ const ROARR = createRoarrInitialGlobalStateBrowser(
globalThis.ROARR = ROARR;

const serializeMessage: MessageSerializer = (message) => {
return safeStringify(message);
return stringify(message);
};

const Roarr = createLogger((message) => {
Expand Down
18 changes: 18 additions & 0 deletions src/utilities/stringify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { configure } from 'safe-stable-stringify';

const safeStringify = configure({
circularValue: 'Magic circle!',
deterministic: false,
strict: false,
});

export const stringify = (value: unknown): string => {
try {
return safeStringify(value) ?? '';
} catch (error) {
// eslint-disable-next-line no-console
console.error('could not serialize value', value);

throw error;
}
};
17 changes: 17 additions & 0 deletions test/roarr/utilities/stringify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { stringify } from '../../../src/utilities/stringify';
import test from 'ava';

test('stringifies key=value', (t) => {
t.is(
stringify({
foo: 'bar',
}),
'{"foo":"bar"}',
);
t.is(
stringify({
foo: undefined,
}),
'{}',
);
});

0 comments on commit 47fba2b

Please sign in to comment.