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:
Patrik Oldsberg
2021-03-11 12:03:13 +01:00
parent 63f7d4d6cd
commit 5c9bdfb64e
3 changed files with 36 additions and 2 deletions
+1 -1
View File
@@ -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';
+34 -1
View File
@@ -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;
};
}
+1
View File
@@ -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),