simple-async-tasks
easily create and use async-tasks within a pit-of-success
install
npm install simple-async-tasks
use
define your async task
define the domain object of the async task you want to be able to run
import { DomainEntity } from 'domain-objects';
import { AsyncTask, AsyncTaskStatus } from 'simple-async-tasks';
export interface AsyncTaskEmitToRemote extends AsyncTask {
uuid?: string;
updatedAt?: string;
status: AsyncTaskStatus;
endpoint: string;
payload: string | Buffer;
}
export class AsyncTaskEmitToRemote
extends DomainEntity<AsyncTaskEmitToRemote>
implements AsyncTaskEmitToRemote
{
public static unique = ['endpoint', 'payload'];
}
define your dao
define the database-access-object we can use to persist this async-task
usually, you should be using a library to code-generate or instantiate the dao for you
for example
import { createCacheDao } from 'simple-cache-dao';
import { createCache } from 'simple-in-memory-cache';
const daoTaskEmitToRemote = createCacheDao({ cache: createCache() })
define how to queue
define how to queue your task for execution
import { createQueue, QueueOrder } from 'simple-in-memory-queue';
export const asyncTaskEmitToRemoteQueue = createQueue<AsyncTaskEmitToRemote>({
order: QueueOrder.FIRST_IN_FIRST_OUT,
});
export const queueTaskEmitToRemote = withAsyncTaskExecutionLifecycleQueue({
dao: daoTaskEmitToRemote,
queue: asyncTaskEmitToRemoteQueue,
getNew: ({ endpoint, payload }) =>
new AsyncTaskEmitToRemote({
status: AsyncTaskStatus.QUEUED,
endpoint,
payload,
}),
});
define how to execute
define how to execute your async task
export const executeTaskEmitToRemote = withAsyncTaskExecutionLifecycleExecute(
async ({ task }: { task: HasMetadata<AsyncTaskEmitToRemote> }) => {
await daoTaskEmitToRemote.upsert({ task: { ...task, status: AsyncTaskStatus.FULFILLED }})
},
{
dao: daoTaskEmitToRemote,
},
);
⚠️ note: you must change the status of the task away from attempted by the time the execute function resolves to some non-attempted , otherwise it will be considered a failure
define the execution trigger
define the trigger that will consume from your queue and invoke the execute function
note
- this will vary based on which queue implementation you use
- for example,