action-kit
v1.1.2
Published
The Action Helper Library provides a framework for defining and handling actions in a Node.js environment. It enables you to encapsulate actions as functions and easily manage their invocation and error handling.
Downloads
6
Readme
Action Helper Library
The Action Helper Library provides a framework for defining and handling actions in a Node.js environment. It enables you to encapsulate actions as functions and easily manage their invocation and error handling.
Installation
To install the Action Helper Library, you can use npm:
npm install action-kit
Usage
Importing and Setting Up
import { ActionHelper } from "action-kit";
import { getClientAction } from "./path/actions/getClientAction.js";
import { withErrorsAction } from "./path/actions/withErrorsAction.js";
const actionHelper = new ActionHelper();
actionHelper.registerAction(getClientAction);
actionHelper.registerAction(withErrorsAction);
export function handler(event, context) {
return actionHelper.handle(event, context);
}
Defining Actions
withErrorsAction
import { Action, ActionError, ActionResponse } from "action-kit";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const handler = async (event, context, addError) => {
await sleep(2000);
addError(
new ActionError({ message: "clientnotfound" }, 404, "User not found")
);
};
const withErrorsAction = new Action({
name: "withErrors", // The name of the action
handler,
options: {
logs: {
onInput: true,
onOutput: true,
onError: true,
},
},
});
export default withErrorsAction;
getClientAction
import { Action, ActionError, ActionResponse } from "action-kit";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const handler = async (event, context, addError, getService) => {
await sleep(2000);
const generateRandomNumber = getService('generateRandomNumber');
console.log('Random number:', generateRandomNumber());
return new ActionResponse({ message: "OK" });
};
const getClientAction = new Action({
name: "getClient", // The name of the action
handler,
options: {
logs: {
onInput: true,
onOutput: true,
onError: true,
},
timeStamp: true,
},
});
getClientAction.addService({
name: 'generateRandomNumber',
execute: () => Math.random()
})
export default getClientAction;
Invoking the Handler
import { handler } from "./index.js";
const event = { body: { action: "getClient" } };
// const event = { body: { action: "withErrors" } };
// const event = { body: { action: "notFound" } };
const run = async () => {
const result = await handler(event, {});
console.log(result);
};
run();