Skip to content

Commit 22bd57f

Browse files
committed
feat(context): add singleValue to ContextView
1 parent 6733610 commit 22bd57f

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

packages/context/src/__tests__/unit/context-view.unit.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ describe('ContextView', () => {
4545
expect(await taggedAsFoo.asGetter()()).to.eql(['BAR', 'FOO']);
4646
});
4747

48+
it('reports error on singleValue() if multiple values exist', async () => {
49+
return expect(taggedAsFoo.singleValue()).to.be.rejectedWith(
50+
/The ContextView has more than one value\. Use values\(\) to access them\./,
51+
);
52+
});
53+
54+
it('supports singleValue() if only one value exist', async () => {
55+
server.unbind('bar');
56+
expect(await taggedAsFoo.singleValue()).to.eql('FOO');
57+
});
58+
4859
it('reloads bindings after refresh', async () => {
4960
taggedAsFoo.refresh();
5061
const abcBinding = server

packages/context/src/context-view.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,18 @@ export class ContextView<T = unknown> extends EventEmitter
157157
asGetter(session?: ResolutionSession): Getter<T[]> {
158158
return () => this.values(session);
159159
}
160+
161+
/**
162+
* Get the single value
163+
*/
164+
async singleValue(session?: ResolutionSession): Promise<T | undefined> {
165+
const values = await this.values(session);
166+
if (values.length === 0) return undefined;
167+
if (values.length === 1) return values[0];
168+
throw new Error(
169+
'The ContextView has more than one value. Use values() to access them.',
170+
);
171+
}
160172
}
161173

162174
/**

0 commit comments

Comments
 (0)