Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: lazyInlineResolver util #72

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/__tests__/lazyInlineRefResolver.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { lazyInlineRefResolver } from '../lazyInlineRefResolver';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Obviously more tests will be added.
Http-spec had a decent coverage (I think) and all tests pass there + a few issues were fixed.


describe('lazyInlineResolver', () => {
test('should work', () => {
const doc = {
a: {
$ref: '#/b/foo',
},
b: {
foo: {
$ref: '#/c',
},
bar: {
$ref: '#/e',
},
},
c: {
$ref: '#/b/bar',
},
e: 'woo!',
};

expect((lazyInlineRefResolver(doc) as any).b.foo).toBe('woo!');
});
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from './getLastPathSegment';
export * from './getLocationForJsonPath';
export * from './hasRef';
export * from './isLocalRef';
export * from './lazyInlineRefResolver';
export * from './parseWithPointers';
export * from './pathToPointer';
export * from './pointerToPath';
Expand Down
38 changes: 38 additions & 0 deletions src/lazyInlineRefResolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { resolveInlineRef } from './resolveInlineRef';

const ROOT_MAP = new WeakMap();

type Root = Record<PropertyKey, unknown>;

// todo: handle circular? might be not needed, as simply pass the responsibility onto consumer
const traps: ProxyHandler<Root> = {
get(target, key, recv) {
const value = Reflect.get(target, key, recv);

if (typeof value === 'object' && value !== null) {
const root = ROOT_MAP.get(target);

if (!('$ref' in value)) {
return _lazyInlineRefResolver(value, root);
}

const resolved = resolveInlineRef(root, value.$ref);
if (typeof resolved === 'object' && resolved !== null) {
return _lazyInlineRefResolver(resolved, root);
}

return resolved;
}

return value;
},
};

function _lazyInlineRefResolver(obj: object, root: Root) {
ROOT_MAP.set(obj, root);
return new Proxy(obj, traps);
}

export function lazyInlineRefResolver(root: Root) {
return _lazyInlineRefResolver(root, root);
}