forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Security][Lists] Add API functions and react hooks for value list AP…
…Is (elastic#69603) * Add pure API functions and react hooks for value list APIs This also adds a generic hook, useAsyncTask, that wraps an async function to provide basic utilities: * loading state * error state * abort/cancel function * Fix type errors in hook tests These were not caught locally as I was accidentally running typescript without the full project. * Document current limitations of useAsyncTask * Defines a new validation function that returns an Either instead of a tuple This allows callers to further leverage fp-ts functions as needed. * Remove duplicated copyright comment * WIP: Perform request/response validations in the FP style * leverages new validateEither fn which returns an Either * constructs a pipeline that: * validates the payload * performs the API call * validates the response and short-circuits if any of those produce a Left value. It then converts the Either into a promise that either rejects with the Left or resolves with the Right. * Adds helper function to convert a TaskEither back to a Promise This cleans up our validation pipeline considerably. * Adds request/response validations to findLists * refactors private API functions to accept the encoded request schema (i.e. snake cased) * refactors validateEither to use `schema.validate` instead of `schema.decode` since we don't actually want the decoded value, we just want to verify that it'll be able to be decoded on the backend. * Refactor our API types * Add request/response validation to import/export functions * Fix type errors * Continue to export decoded types without a qualifier * pull types used by hooks from their new location * Fix errors with usage of act() * Attempting to reduce plugin bundle size By pulling from the module directly instead of an index, we can hopefully narrow down our dependencies until tree-shaking does this for us. * useAsyncFn's initiator does not return a promise Rather than returning a promise and requiring the caller to handle a rejection, we instead return nothing and require the user to watch the hook's state. * success can be handled with a useEffect on state.result * errors can be handled with a useEffect on state.error * Fix failing test Assertion count wasn't updated following interface changes; we've now got two inline expectations so this isn't needed. Co-authored-by: Elastic Machine <[email protected]>
- Loading branch information
Showing
25 changed files
with
1,040 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
93
x-pack/plugins/lists/public/common/hooks/use_async_task.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
expect(result.current.error).toBeUndefined(); | ||
}); | ||
|
||
it('populates error if task rejects', async () => { | ||
task.mockRejectedValue(new Error('whoops')); | ||
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task)); | ||
|
||
act(() => { | ||
result.current.start({}); | ||
}); | ||
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); | ||
}); | ||
}); |
48 changes: 48 additions & 0 deletions
48
x-pack/plugins/lists/public/common/hooks/use_async_task.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
/* | ||
* 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. | ||
// 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) => void; | ||
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(); | ||
initiator(ctrl.current, args); | ||
}, | ||
[initiator] | ||
); | ||
|
||
return { abort, error: state.error, loading: state.loading, result: state.value, start }; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.