|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from linkedapi.mappers.base import ( |
| 6 | + BaseMapper, |
| 7 | + MappedResponse, |
| 8 | + as_action_dict, |
| 9 | + collect_action_errors, |
| 10 | +) |
| 11 | +from linkedapi.types import WorkflowCompletion, WorkflowDefinition, serialize_model |
| 12 | +from linkedapi.types.message import SendMessageParams |
| 13 | + |
| 14 | + |
| 15 | +class SendMessageMapper(BaseMapper[SendMessageParams, None]): |
| 16 | + def map_request(self, params: SendMessageParams | None = None) -> WorkflowDefinition: |
| 17 | + serialized = serialize_model(params) |
| 18 | + manage_conversation = serialized.pop("manageConversation", None) |
| 19 | + definition: dict[str, Any] = {"actionType": "st.sendMessage", **serialized} |
| 20 | + # The child st.manageConversation acts on the conversation this message was sent into, so it |
| 21 | + # carries only `operation` — no threadId. Core rejects a threadId on a child manageConversation. |
| 22 | + # Guard on `operation` so an empty passthrough (e.g. Make sending {"operation": ""}) is ignored. |
| 23 | + if manage_conversation and manage_conversation.get("operation"): |
| 24 | + definition["then"] = { |
| 25 | + "actionType": "st.manageConversation", |
| 26 | + "operation": manage_conversation["operation"], |
| 27 | + } |
| 28 | + return definition |
| 29 | + |
| 30 | + def map_response(self, completion: WorkflowCompletion) -> MappedResponse[None]: |
| 31 | + if isinstance(completion, list): |
| 32 | + errors = collect_action_errors( |
| 33 | + [as_action_dict(action).get("error") for action in completion] |
| 34 | + ) |
| 35 | + return MappedResponse(data=None, errors=errors) |
| 36 | + |
| 37 | + action = as_action_dict(completion) |
| 38 | + raw_errors: list[Any] = [action.get("error")] |
| 39 | + |
| 40 | + single_data = action.get("data") |
| 41 | + if single_data is not None: |
| 42 | + then_actions = as_action_dict(single_data).get("then") |
| 43 | + if then_actions: |
| 44 | + child_actions = then_actions if isinstance(then_actions, list) else [then_actions] |
| 45 | + raw_errors.extend(as_action_dict(child).get("error") for child in child_actions) |
| 46 | + |
| 47 | + return MappedResponse(data=None, errors=collect_action_errors(raw_errors)) |
0 commit comments