From 19a603018c87065191f99a55cdcdfc8193dc493d Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Wed, 14 Jun 2023 22:30:26 +0330 Subject: [PATCH] feat(util): renderState --- core/util/src/_logger.ts | 3 +++ core/util/src/index.ts | 1 + core/util/src/render-state.ts | 46 +++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 core/util/src/_logger.ts create mode 100644 core/util/src/render-state.ts diff --git a/core/util/src/_logger.ts b/core/util/src/_logger.ts new file mode 100644 index 000000000..5ee3e8dca --- /dev/null +++ b/core/util/src/_logger.ts @@ -0,0 +1,3 @@ +import {createLogger} from '@alwatr/logger'; + +export const logger = createLogger('alwatr/util'); diff --git a/core/util/src/index.ts b/core/util/src/index.ts index 9fd559339..66832ce2e 100644 --- a/core/util/src/index.ts +++ b/core/util/src/index.ts @@ -5,3 +5,4 @@ export * from './client-id.js'; export * from './polyfill.js'; export * from './flat-str.js'; export * from './string.js'; +export * from './render-state.js'; diff --git a/core/util/src/render-state.ts b/core/util/src/render-state.ts new file mode 100644 index 000000000..914f56787 --- /dev/null +++ b/core/util/src/render-state.ts @@ -0,0 +1,46 @@ +import {logger} from './_logger.js'; + +export const renderState = ( + state: T, + renderRecord: Record R)>, + thisArg: unknown = null, +): R | void => { + logger.logMethodArgs?.('renderState', {state, renderRecord}); + + let render = renderRecord[state]; + + if (typeof render === 'string') { + render = renderRecord[render as T]; + } + + if (render === undefined) { + if (renderRecord._default === undefined) { + logger.error('renderState', 'invalid_render_state'); + return; + } + // else + if (typeof renderRecord._default === 'string') { + if (renderRecord[renderRecord._default] === undefined) { + logger.error('renderState', 'invalid_default_render'); + return; + } + // else + return renderState(renderRecord._default, renderRecord, thisArg); + } + // else + render = renderRecord._default; + } + + if (typeof render !== 'function') { + logger.error('renderState', 'invalid_render_state'); + return; + } + + try { + return render.call(thisArg); + } + catch (err) { + logger.error('renderState', 'render_error', err); + return; + } +};