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

[Security][Lists] Add API functions and react hooks for value list APIs #69603

Merged
merged 18 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from 14 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
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const deleteListSchema = t.exact(
);

export type DeleteListSchema = t.TypeOf<typeof deleteListSchema>;
export type DeleteListSchemaEncoded = t.OutputOf<typeof deleteListSchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export const exportListItemQuerySchema = t.exact(
);

export type ExportListItemQuerySchema = t.TypeOf<typeof exportListItemQuerySchema>;
export type ExportListItemQuerySchemaEncoded = t.OutputOf<typeof exportListItemQuerySchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import * as t from 'io-ts';

import { cursor, filter, sort_field, sort_order } from '../common/schemas';
import { RequiredKeepUndefined } from '../../types';
import { StringToPositiveNumber } from '../types/string_to_positive_number';

export const findListSchema = t.exact(
Expand All @@ -23,6 +22,5 @@ export const findListSchema = t.exact(
})
);

export type FindListSchemaPartial = t.TypeOf<typeof findListSchema>;

export type FindListSchema = RequiredKeepUndefined<t.TypeOf<typeof findListSchema>>;
export type FindListSchema = t.TypeOf<typeof findListSchema>;
export type FindListSchemaEncoded = t.OutputOf<typeof findListSchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
import * as t from 'io-ts';

import { list_id, type } from '../common/schemas';
import { Identity, RequiredKeepUndefined } from '../../types';
import { Identity } from '../../types';

export const importListItemQuerySchema = t.exact(t.partial({ list_id, type }));

export type ImportListItemQuerySchemaPartial = Identity<t.TypeOf<typeof importListItemQuerySchema>>;
export type ImportListItemQuerySchema = RequiredKeepUndefined<
t.TypeOf<typeof importListItemQuerySchema>
>;

export type ImportListItemQuerySchema = t.TypeOf<typeof importListItemQuerySchema>;
export type ImportListItemQuerySchemaEncoded = t.OutputOf<typeof importListItemQuerySchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const importListItemSchema = t.exact(
);

export type ImportListItemSchema = t.TypeOf<typeof importListItemSchema>;
export type ImportListItemSchemaEncoded = t.OutputOf<typeof importListItemSchema>;
2 changes: 1 addition & 1 deletion x-pack/plugins/lists/common/siem_common_deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ export { DefaultUuid } from '../../security_solution/common/detection_engine/sch
export { DefaultStringArray } from '../../security_solution/common/detection_engine/schemas/types/default_string_array';
export { exactCheck } from '../../security_solution/common/exact_check';
export { getPaths, foldLeftRight } from '../../security_solution/common/test_utils';
export { validate } from '../../security_solution/common/validate';
export { validate, validateEither } from '../../security_solution/common/validate';
export { formatErrors } from '../../security_solution/common/format_errors';
23 changes: 23 additions & 0 deletions x-pack/plugins/lists/public/common/fp_utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { tryCatch } from 'fp-ts/lib/TaskEither';

import { toPromise } from './fp_utils';

describe('toPromise', () => {
it('rejects with left if TaskEither is left', async () => {
const task = tryCatch(() => Promise.reject(new Error('whoops')), String);

await expect(toPromise(task)).rejects.toEqual('Error: whoops');
});

it('resolves with right if TaskEither is right', async () => {
const task = tryCatch(() => Promise.resolve('success'), String);

await expect(toPromise(task)).resolves.toEqual('success');
});
});
18 changes: 18 additions & 0 deletions x-pack/plugins/lists/public/common/fp_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { pipe } from 'fp-ts/lib/pipeable';
import { TaskEither } from 'fp-ts/lib/TaskEither';
import { fold } from 'fp-ts/lib/Either';

export const toPromise = async <E, A>(taskEither: TaskEither<E, A>): Promise<A> =>
pipe(
await taskEither(),
fold(
(e) => Promise.reject(e),
(a) => Promise.resolve(a)
)
);
93 changes: 93 additions & 0 deletions x-pack/plugins/lists/public/common/hooks/use_async_task.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { act, renderHook } from '@testing-library/react-hooks';

import { useAsyncTask } from './use_async_task';

describe('useAsyncTask', () => {
let task: jest.Mock;

beforeEach(() => {
task = jest.fn().mockResolvedValue('resolved value');
});

it('does not invoke task if start was not called', () => {
renderHook(() => useAsyncTask(task));
expect(task).not.toHaveBeenCalled();
});

it('invokes the task when start is called', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});
await waitForNextUpdate();

expect(task).toHaveBeenCalled();
});

it('invokes the task with a signal and start args', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({
arg1: 'value1',
arg2: 'value2',
});
});
await waitForNextUpdate();

expect(task).toHaveBeenCalledWith(expect.any(AbortController), {
arg1: 'value1',
arg2: 'value2',
});
});

it('populates result with the resolved value of the task', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});
await waitForNextUpdate();

expect(result.current.result).toEqual('resolved value');
});

it('start rejects and error is populated if task rejects', async () => {
expect.assertions(3);
task.mockRejectedValue(new Error('whoops'));
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({}).catch((e) => expect(e).toEqual(new Error('whoops')));
});
await waitForNextUpdate();

expect(result.current.result).toBeUndefined();
expect(result.current.error).toEqual(new Error('whoops'));
});

it('populates the loading state while the task is pending', async () => {
let resolve: () => void;
task.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve)));

const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});

expect(result.current.loading).toBe(true);

act(() => resolve());
await waitForNextUpdate();

expect(result.current.loading).toBe(false);
});
});
52 changes: 52 additions & 0 deletions x-pack/plugins/lists/public/common/hooks/use_async_task.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { useCallback, useRef } from 'react';
import useAsyncFn from 'react-use/lib/useAsyncFn';

// Params can be generalized to a ...rest parameter extending unknown[] once https://github.com/microsoft/TypeScript/pull/39094 is available.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The one caveat with useAsyncTask right now. Otherwise, it Just Works™ and is type safe.

// for now, the task must still receive unknown as a second argument, and an argument must be passed to start()
export type UseAsyncTask = <Result, Params extends unknown>(
task: (...args: [AbortController, Params]) => Promise<Result>
) => AsyncTask<Result, Params>;

export interface AsyncTask<Result, Params extends unknown> {
start: (params: Params) => Promise<Result>;
abort: () => void;
loading: boolean;
error: Error | undefined;
result: Result | undefined;
}

/**
*
* @param task Async function receiving an AbortController and optional arguments
*
* @returns An {@link AsyncTask} containing the underlying task's state along with start/abort helpers
*/
export const useAsyncTask: UseAsyncTask = (task) => {
const ctrl = useRef(new AbortController());
const abort = useCallback((): void => {
ctrl.current.abort();
}, []);

// @ts-ignore typings are incorrect, see: https://github.com/streamich/react-use/pull/589
const [state, initiator] = useAsyncFn(task, [task]);

const start = useCallback(
(args) => {
ctrl.current = new AbortController();

return initiator(ctrl.current, args).then((result) =>
// convert resolved error to rejection: https://github.com/streamich/react-use/issues/981
result instanceof Error ? Promise.reject(result) : result
);
},
[initiator]
);

return { abort, error: state.error, loading: state.loading, result: state.value, start };
};
5 changes: 5 additions & 0 deletions x-pack/plugins/lists/public/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

// Exports to be shared with plugins
export { useApi } from './exceptions/hooks/use_api';
export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item';
export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list';
export { useExceptionList } from './exceptions/hooks/use_exception_list';
export { useFindLists } from './lists/hooks/use_find_lists';
export { useImportList } from './lists/hooks/use_import_list';
export { useDeleteList } from './lists/hooks/use_delete_list';
export { useExportList } from './lists/hooks/use_export_list';
export {
ExceptionList,
ExceptionIdentifiers,
Expand Down
Loading