mirror of
https://github.com/elastic/kibana.git
synced 2025-04-24 01:38:56 -04:00
[KIbana Utils] createGetterSetter should work with optional plugins (#114128)
This commit is contained in:
parent
855d2f1094
commit
3291e85119
2 changed files with 45 additions and 2 deletions
38
src/plugins/kibana_utils/common/create_getter_setter.test.ts
Normal file
38
src/plugins/kibana_utils/common/create_getter_setter.test.ts
Normal file
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the Elastic License
|
||||
* 2.0 and the Server Side Public License, v 1; you may not use this file except
|
||||
* in compliance with, at your election, the Elastic License 2.0 or the Server
|
||||
* Side Public License, v 1.
|
||||
*/
|
||||
|
||||
import { createGetterSetter } from './create_getter_setter';
|
||||
|
||||
describe('createGetterSetter', () => {
|
||||
test('should be able to create getter/setter', () => {
|
||||
const [getString, setString] = createGetterSetter<{}>('string');
|
||||
|
||||
expect(getString).toBeInstanceOf(Function);
|
||||
expect(setString).toBeInstanceOf(Function);
|
||||
});
|
||||
|
||||
test('getter should return the set value', () => {
|
||||
const [getString, setString] = createGetterSetter<{}>('string');
|
||||
|
||||
setString('test');
|
||||
expect(getString()).toBe('test');
|
||||
});
|
||||
|
||||
test('getter should throw an exception', () => {
|
||||
const [getString] = createGetterSetter<{}>('string');
|
||||
|
||||
expect(() => getString()).toThrowErrorMatchingInlineSnapshot(`"string was not set."`);
|
||||
});
|
||||
|
||||
test('getter should not throw an exception (isValueRequired is false)', () => {
|
||||
const [getString] = createGetterSetter<{}>('string', false);
|
||||
const value = getString();
|
||||
|
||||
expect(value).toBeUndefined();
|
||||
});
|
||||
});
|
|
@ -9,11 +9,16 @@
|
|||
export type Get<T> = () => T;
|
||||
export type Set<T> = (value: T) => void;
|
||||
|
||||
export const createGetterSetter = <T extends object>(name: string): [Get<T>, Set<T>] => {
|
||||
export const createGetterSetter = <T extends object>(
|
||||
name: string,
|
||||
isValueRequired: boolean = true
|
||||
): [Get<T>, Set<T>] => {
|
||||
let value: T;
|
||||
|
||||
const get: Get<T> = () => {
|
||||
if (!value) throw new Error(`${name} was not set.`);
|
||||
if (!value && isValueRequired) {
|
||||
throw new Error(`${name} was not set.`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue