plugin-api: add back withApis
Co-authored-by: Juan Lulkin <jmaiz@spotify.com> Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { useApi, useApiHolder } from './useApi';
|
||||
export { useApi, useApiHolder, withApis } from './useApi';
|
||||
export { createApiRef } from './ApiRef';
|
||||
export * from './types';
|
||||
export * from './helpers';
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { ApiRef, ApiHolder } from './types';
|
||||
import React, { PropsWithChildren } from 'react';
|
||||
import { ApiRef, ApiHolder, TypesToApiRefs } from './types';
|
||||
import { useVersionedContext } from '../../lib/versionedValues';
|
||||
|
||||
export function useApiHolder(): ApiHolder {
|
||||
@@ -36,3 +37,35 @@ export function useApi<T>(apiRef: ApiRef<T>): T {
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
export function withApis<T>(apis: TypesToApiRefs<T>) {
|
||||
return function withApisWrapper<P extends T>(
|
||||
WrappedComponent: React.ComponentType<P>,
|
||||
) {
|
||||
const Hoc = (props: PropsWithChildren<Omit<P, keyof T>>) => {
|
||||
const apiHolder = useApiHolder();
|
||||
|
||||
const impls = {} as T;
|
||||
|
||||
for (const key in apis) {
|
||||
if (apis.hasOwnProperty(key)) {
|
||||
const ref = apis[key];
|
||||
|
||||
const api = apiHolder.get(ref);
|
||||
if (!api) {
|
||||
throw new Error(`No implementation available for ${ref}`);
|
||||
}
|
||||
impls[key] = api;
|
||||
}
|
||||
}
|
||||
|
||||
return <WrappedComponent {...(props as P)} {...impls} />;
|
||||
};
|
||||
const displayName =
|
||||
WrappedComponent.displayName || WrappedComponent.name || 'Component';
|
||||
|
||||
Hoc.displayName = `withApis(${displayName})`;
|
||||
|
||||
return Hoc;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ describe('index', () => {
|
||||
useApiHolder: expect.any(Function),
|
||||
useApp: expect.any(Function),
|
||||
useRouteRef: expect.any(Function),
|
||||
withApis: expect.any(Function),
|
||||
|
||||
createApiRef: expect.any(Function),
|
||||
createExternalRouteRef: expect.any(Function),
|
||||
|
||||
Reference in New Issue
Block a user