Skip to content

Commit

Permalink
feat(context): Add toJSON() for Context and Binding
Browse files Browse the repository at this point in the history
Provide customization to serialize Context and Binding objects to JSON
  • Loading branch information
Raymond Feng committed Sep 27, 2017
1 parent 3286bc6 commit 43f2471
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
13 changes: 12 additions & 1 deletion packages/context/src/binding.ts
Expand Up @@ -243,8 +243,9 @@ export class Binding {
return this;
}

inScope(scope: BindingScope) {
inScope(scope: BindingScope): this {
this.scope = scope;
return this;
}

/**
Expand Down Expand Up @@ -335,4 +336,14 @@ export class Binding {
this.isLocked = false;
return this;
}

toJSON(): Object {
const json = {
key: this.key,
scope: this.scope,
tags: Array.from(this.tags),
isLocked: this.isLocked,
};
return json;
}
}
11 changes: 11 additions & 0 deletions packages/context/src/context.ts
Expand Up @@ -193,6 +193,17 @@ export class Context {

return getDeepProperty(boundValue, path);
}

/**
* Create a plain JSON object for the context
*/
toJSON(): Object {
const json: {[key: string]: Object} = {};
for (const [k, v] of this.registry) {
json[k] = v.toJSON();
}
return json;
}
}

function getDeepProperty(value: BoundValue, path: string) {
Expand Down
25 changes: 25 additions & 0 deletions packages/context/test/unit/binding.ts
Expand Up @@ -98,6 +98,31 @@ describe('Binding', () => {
});
});

describe('toJSON()', () => {
it('converts to plain JSON object', () => {
const json = binding.toJSON();
expect(json).to.eql({
key: key,
scope: BindingScope.TRANSIENT,
tags: [],
isLocked: false,
});
});

it('converts to plain JSON object', () => {
const myBinding = new Binding(key, true)
.inScope(BindingScope.CONTEXT)
.tag('model');
const json = myBinding.toJSON();
expect(json).to.eql({
key: key,
scope: BindingScope.CONTEXT,
tags: ['model'],
isLocked: true,
});
});
});

function givenBinding() {
ctx = new Context();
binding = new Binding(key);
Expand Down
17 changes: 17 additions & 0 deletions packages/context/test/unit/context.ts
Expand Up @@ -375,6 +375,23 @@ describe('Context', () => {
});
});

describe('toJSON()', () => {
it('converts to plain JSON object', () => {
ctx.bind('a').to('1').lock();
ctx.bind('b').toDynamicValue(() => 2).inScope(BindingScope.SINGLETON)
.tag(['X', 'Y']);
ctx.bind('c').to(3).tag('Z');
expect(ctx.toJSON()).to.eql({
a: {key: 'a', scope: BindingScope.TRANSIENT,
tags: [], isLocked: true},
b: {key: 'b', scope: BindingScope.SINGLETON,
tags: ['X', 'Y'], isLocked: false},
c: {key: 'c', scope: BindingScope.TRANSIENT,
tags: ['Z'], isLocked: false},
});
});
});

function createContext() {
ctx = new Context();
}
Expand Down

0 comments on commit 43f2471

Please sign in to comment.