From 5c9bdfb64e36149818ebff0576386859ef8898d0 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Thu, 11 Mar 2021 12:03:13 +0100 Subject: [PATCH] plugin-api: add back withApis Co-authored-by: Juan Lulkin Signed-off-by: Patrik Oldsberg --- packages/plugin-api/src/apis/system/index.ts | 2 +- .../plugin-api/src/apis/system/useApi.tsx | 35 ++++++++++++++++++- packages/plugin-api/src/index.test.ts | 1 + 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/plugin-api/src/apis/system/index.ts b/packages/plugin-api/src/apis/system/index.ts index 5adf0054d4..8b8dfff80b 100644 --- a/packages/plugin-api/src/apis/system/index.ts +++ b/packages/plugin-api/src/apis/system/index.ts @@ -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'; diff --git a/packages/plugin-api/src/apis/system/useApi.tsx b/packages/plugin-api/src/apis/system/useApi.tsx index b55fb36c17..a0a40085cd 100644 --- a/packages/plugin-api/src/apis/system/useApi.tsx +++ b/packages/plugin-api/src/apis/system/useApi.tsx @@ -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(apiRef: ApiRef): T { } return api; } + +export function withApis(apis: TypesToApiRefs) { + return function withApisWrapper

( + WrappedComponent: React.ComponentType

, + ) { + const Hoc = (props: PropsWithChildren>) => { + 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 ; + }; + const displayName = + WrappedComponent.displayName || WrappedComponent.name || 'Component'; + + Hoc.displayName = `withApis(${displayName})`; + + return Hoc; + }; +} diff --git a/packages/plugin-api/src/index.test.ts b/packages/plugin-api/src/index.test.ts index 7d642c81ff..7d716c7f91 100644 --- a/packages/plugin-api/src/index.test.ts +++ b/packages/plugin-api/src/index.test.ts @@ -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),