UNPKG

@onereach/channel-transformer

Version:

Convert data model between different channels (Slack, Microsoft Teams, Generic...)

123 lines (107 loc) 3.15 kB
import { IGenericWrapper } from '../../generic/types/wrapper'; import { ISlackBlockKitData } from '../types/index'; import { transformText } from './items/text'; import { getMethods } from './methods'; import { getErrorObject } from '../../../helpers/get-error-object'; function mapBlocks(blocks: Array<any>, type: String): Array<any> { const res = blocks.reduce( (acc, block) => { let converted = getMethods(block.type)(block, type); if ( converted.type !== "section" && converted.type !== "context" && converted.type !== "actions" && converted.type !== "input" ) { const isSubmitSurface = (slackType) => ['modal', 'home'].includes(slackType); const getElementWrapper = (elementType) => { if ([ 'static_select', 'external_select', 'users_select', 'conversations_select', 'channels_select', 'overflow', 'multi_static_select', 'multi_users_select', 'multi_conversations_select', 'multi_channels_select', 'multi_checkbox', 'radio', 'datepicker', 'timepicker' ].includes(elementType)) { return isSubmitSurface(type) ? 'input' : 'actions'; } else if (elementType === 'plain_text') { return 'section'; } else { return null; } }; const wrapper = getElementWrapper(converted.type); if (wrapper) { if (wrapper === 'section') { converted = { "type": "section", "text": converted }; } else if (wrapper === 'actions') { converted = { "type": wrapper, "elements": [ converted ] }; } else { converted = { "type": wrapper, "element": converted }; } } } // console.log('converted -> ', converted); return acc.concat(converted); }, []); return res.length > 0 ? res : [{}]; } export function transformGenericToSlack({ children, props }: IGenericWrapper): ISlackBlockKitData { const type = props?.slack?.type || 'message'; if (type === 'message') { return { blocks: mapBlocks(children, type), }; } if (type === 'attachments') { const attachments = []; for (let i = 0; i < children.length; i++) { const blocks = children[i]; attachments.push({ blocks: mapBlocks(blocks, type), }); } return { attachments }; } if (type === 'home') { return { type: "home", blocks: mapBlocks(children, type), }; } if (type === 'modal') { return { type: "modal", blocks: mapBlocks(children, type), title: transformText(props.slack.title), submit: transformText(props.slack.submit), close: transformText(props.slack.close), }; } return getErrorObject({ type: type, message: 'transformGenericToSlack method' })(); }