@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
118 lines (92 loc) • 2.74 kB
text/typescript
import { createLogger } from "../logger";
export enum ActionResult {
Success = "success",
Error = "error",
Cancel = "cancel",
}
const { log_error, log_debug, log_info } = createLogger({
subsystem: "ActionExecutor",
category: "General",
});
class ActionExecutor {
private registeredActions: Record<string, any> = {};
// TODO: Remove context
handleAction = async (
action: ActionType,
entry: ZappEntry = null
): Promise<ActionResult> => {
const handler = this.registeredActions[action.type];
if (!handler) {
log_error(
`handleAction: no handler found for action type: ${action.type}`,
{ action, entry }
);
return;
}
log_debug(
`handleAction: ${action.type}${
entry ? `, entry id ${entry.id}, title: ${entry.title}` : ""
}`,
{ action, entry }
);
try {
return handler(action, entry);
} catch (error) {
log_error(
`handleAction: error handling action type: ${action.type}, message: ${error.message}`,
{ action, entry, error }
);
throw error;
}
};
handleActions = async (
actionTypes: ActionType[],
entry: ZappEntry = null
): Promise<ActionResult> => {
for (const action of actionTypes) {
// TODO: Handle action result error
const result = await this.handleAction(action, entry);
if (result === ActionResult.Cancel) {
log_info(`handleActions: action: ${action.type} canceled`);
return result;
}
}
return ActionResult.Success;
};
handleEntryActions = async (entry: ZappEntry): Promise<ActionResult> => {
const tapActions = entry.extensions?.tap_actions?.actions;
if (!tapActions) {
return;
}
if (!Array.isArray(tapActions)) {
log_error(
`handleEntryActions: tapActions is not an array for id: ${entry.id} title: ${entry.title}`,
{ entry }
);
return;
}
if (tapActions.length === 0) {
return;
}
await this.handleActions(tapActions, entry);
};
unregisterAction = (actionType: string) => {
delete this.registeredActions[actionType];
};
registerAction = (
type: string,
handler: (action: ActionType, entry?: ZappEntry) => Promise<ActionResult>
) => {
if (this.registeredActions[type]) {
log_error(`registerAction: action type: ${type} already registered`);
return () => {};
}
this.registeredActions[type] = handler;
log_debug(`registerAction: action type: ${type} registered`);
return () => {
this.unregisterAction(type);
log_debug(`registerAction: action type: ${type} un-registered`);
};
};
}
export const actionExecutor = new ActionExecutor();