Skip to content

Commit

Permalink
feat: added option to bundleTarget to prevent deep clone of document (
Browse files Browse the repository at this point in the history
#99)

* feat: added option to `bundleTarget` to prevent deep clone of document
  • Loading branch information
lukasz-kuzynski-11sigma authored Aug 19, 2021
1 parent 0483fb4 commit 4e597d3
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
55 changes: 55 additions & 0 deletions src/__tests__/bundle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,61 @@ describe('bundleTargetPath()', () => {
});
});

it('should operate on original object if `cloneDocument` set to false', () => {
const document = {
definitions: {
user: {
id: 'foo',
address: {
$ref: '#/definitions/address',
},
},
address: {
street: 'foo',
user: {
$ref: '#/definitions/user',
},
},
card: {
zip: '20815',
},
},
__target__: {
entity: {
$ref: '#/definitions/user',
},
},
};

const result = bundleTarget({
document,
path: '#/__target__',
cloneDocument: false,
});

expect(document.__target__).toStrictEqual(result);

expect(result).toEqual({
entity: {
$ref: `#/${BUNDLE_ROOT}/user`,
},
[BUNDLE_ROOT]: {
user: {
id: 'foo',
address: {
$ref: `#/${BUNDLE_ROOT}/address`,
},
},
address: {
street: 'foo',
user: {
$ref: `#/${BUNDLE_ROOT}/user`,
},
},
},
});
});

it('should include falsy values', () => {
const document = {
definitions: {
Expand Down
6 changes: 4 additions & 2 deletions src/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ export const bundleTarget = <T = unknown>(
path,
bundleRoot = BUNDLE_ROOT,
errorsRoot = ERRORS_ROOT,
}: { document: T; path: string; bundleRoot?: string; errorsRoot?: string },
cloneDocument = true,
}: { document: T; path: string; bundleRoot?: string; errorsRoot?: string; cloneDocument?: boolean },
cur?: unknown,
) => {
if (path === bundleRoot || path === errorsRoot) {
throw new Error(`Roots do not make any sense`);
}

return bundle(cloneDeep(document), pointerToPath(bundleRoot), pointerToPath(errorsRoot))(path, { [path]: true }, cur);
const workingDocument = cloneDocument ? cloneDeep(document) : document;
return bundle(workingDocument, pointerToPath(bundleRoot), pointerToPath(errorsRoot))(path, { [path]: true }, cur);
};

const bundle = (document: unknown, bundleRoot: JsonPath, errorsRoot: JsonPath) => {
Expand Down

0 comments on commit 4e597d3

Please sign in to comment.