[KIbana Utils] createGetterSetter should work with optional plugins (#114128)

This commit is contained in:
Alexey Antonov 2021-10-07 13:47:28 +03:00 committed by GitHub
parent 855d2f1094
commit 3291e85119
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 2 deletions

View 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();
});
});

View file

@ -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;
};