Task Functions
Use this adapter to schedule and manage tasks.
Importing the adapter
import { taskAdapter } from 'epicenter-libs';
The taskAdapter namespace exports functions that make calls to the Task API.
For descriptions of the objects used by the Task adapter functions, read Task Entities.
Create
Create task
Call the create() function to schedule a new task.
A task's payload describes what happens when the task fires: either an HTTP request or a group status change. The trigger describes when that happens: on a cron schedule, at a specific date, or after an offset.
Permissions
Requires a role of FACILITATOR or higher.
Function description
- Constructs a
POSTrequest to the/taskendpoint. - Normalizes the
payload, defaultingobjectTypeto'http'unless'groupStatus'is provided. - Assigns the task to the given
scope. - Optionally includes a retry policy, fail-safe termination deadline, and TTL.
- Returns a
TaskReadOutViewobject representing the newly created task, including itstaskKey.
export async function create<
B extends object = TaskPayloadBody,
H extends object = TaskPayloadHeaders,
>(
scope: { userKey?: string } & GenericScope,
name: string,
payload: TaskPayloadCreateInput<B, H>,
trigger: TaskTriggerCreateInView,
optionals: {
retryPolicy?: keyof typeof RETRY_POLICY;
failSafeTermination?: string;
ttlSeconds?: number;
} & RoutingOptions = {},
): Promise<TaskReadOutView<B, H>>
Parameters
scope: { userKey?: string } & GenericScope- Defines the scope of the task. Can consist ofGenericScopeplus auserKeyfor user-specific scope.scopeBoundary- Defines the type of scope. SeeSCOPE_BOUNDARYfor all types.scopeKey- A unique identifier tied to the scope. For example, if yourscopeBoundaryisGROUP, yourscopeKeywill be yourgroupKey; forEPISODE,episodeKey, etc.userKey?- (Optional) Key associated with the user.
name: string- Name of the task.payload: TaskPayloadCreateInput<B, H>- An HTTP request or group-status change to execute when the task is triggered.- For an HTTP payload (
HttpTaskPayloadCreateInput):method- HTTP method to use ('GET','POST','PUT', or'DELETE').url- Relative URL the request will be sent to; the task runner builds the full URL as{host}{targetPath}/{account}/{project}{url}.target?- (Optional) Where the task fires:'APPLICATION'(the project app, the default) or'PROXY'(the project's proxy server).body- The JSON body of the HTTP request.headers?- (Optional) Headers to send along with the HTTP request. Must be non-empty when provided — omit rather than pass an empty object.timeoutSeconds?- (Optional) Request timeout in seconds (1–30).objectType?- (Optional) Defaults to'http'if omitted.
- For a group-status payload (
GroupStatusTaskPayloadCreateInView):objectType: 'groupStatus'- Identifies the payload as a group-status change.groupKey- Key of the group whose status will be changed.status-StatusCreateInViewobject withcodeandmessage.
- For an HTTP payload (
trigger: TaskTriggerCreateInView- Object that determines when to run the task.- For a cron trigger (
CronTaskTriggerCreateInView):objectType: 'cron',value- a cron expression (e.g.'0 7 * * * ?'). - For a date trigger (
DateTaskTriggerCreateInView):objectType: 'date',value- an ISO-8601 date-time string. - For an offset trigger (
OffsetTaskTriggerCreateInView):objectType: 'offset', with optionalminutes,hours, anddaysuntil the task fires.
- For a cron trigger (
optionals- (Optional) Additional task creation options.retryPolicy?: keyof typeof RETRY_POLICY- (Optional) Specifies what to do should the task fail.failSafeTermination?: string- (Optional) The date when Epicenter will stop running the Task (if it's scheduled as a repeated event). The server defaults and caps this at one year from creation.ttlSeconds?: number- (Optional) The amount of time Epicenter will wait for the task's operation to complete before marking it as failed.RoutingOptions- Additional routing options for request handling.
Return value
A promise resolving to a TaskReadOutView object representing the newly created task, including its taskKey.
Usage example
import { taskAdapter, SCOPE_BOUNDARY } from 'epicenter-libs';
const scope = {
scopeBoundary: SCOPE_BOUNDARY.GROUP,
scopeKey: session.groupKey,
};
const name = 'task-1-send-emails';
const payload = {
method: 'POST',
url: '/send-out-emails',
target: 'PROXY', // fire at the project's proxy server; omit to fire at the app
body: {},
};
const trigger = {
value: '0 7 15 * * ?', // triggers on day 15 7am of each month
objectType: 'cron',
};
await taskAdapter.create(scope, name, payload, trigger);
Retrieve
Get task
The get() function retrieves a task by its task key.
Permissions
Requires a role of FACILITATOR or higher.
Function description
- Constructs a
GETrequest to the/task/{TASK_KEY}endpoint. - Returns a
TaskReadOutViewobject containing the task's details.
export async function get<
B extends object = TaskPayloadBody,
H extends object = TaskPayloadHeaders,
>(taskKey: string, optionals: RoutingOptions = {}): Promise<TaskReadOutView<B, H>>
Parameters
taskKey: string- Unique key associated with a task.optionals(Type:RoutingOptions = {}) - (Optional) Additional routing options for request handling.
Return value
A promise resolving to a TaskReadOutView object containing the task's details.
Usage example
import { taskAdapter } from 'epicenter-libs';
const taskKey = '0000017dd3bf540e5ada5b1e058f08f20461';
const task = await taskAdapter.get(taskKey);
Get task history
The getHistory() function retrieves the history (100 most recent times it was triggered) of a task by its task key.
Permissions
Requires a role of FACILITATOR or higher.
Function description
- Constructs a
GETrequest to the/task/history/{TASK_KEY}endpoint. - Supports pagination through
firstandmax. - Returns a paginated list of
TaskHistoryReadOutViewobjects.
export async function getHistory(
taskKey: string,
optionals: TaskPageOptions & RoutingOptions = {},
): Promise<Page<TaskHistoryReadOutView>>
Parameters
taskKey: string- Unique key associated with a task.optionals(Type:TaskPageOptions& RoutingOptions = {}) - Pagination and network options.first?: number- (Optional) Zero-based index of the first history record. Defaults to0.max?: number- (Optional) Maximum history records to return. Defaults to100and cannot exceed100.RoutingOptions- Additional routing options for request handling.
Return value
A promise resolving to a Page<TaskHistoryReadOutView>, containing a paginated list of the task's history records.
Usage example
import { taskAdapter } from 'epicenter-libs';
const taskKey = '0000017dd3bf540e5ada5b1e058f08f20461';
const history = await taskAdapter.getHistory(taskKey);
Get tasks by scope
The getTaskIn() function gets the most recent 100 tasks related to the selected scope.
Only retrieves tasks that were created in the specified scope. If a task was created with episode scope, it will not be retrievable through group scoping.
Permissions
Requires a role of FACILITATOR or higher.
Function description
- Constructs a
GETrequest to:/task/in/{SCOPE_BOUNDARY}/{SCOPE_KEY}, or/task/in/{SCOPE_BOUNDARY}/{SCOPE_KEY}/{USER_KEY}whenscope.userKeyis provided.
- Supports sorting and pagination through
sort,first, andmax. - Returns a paginated list of
TaskReadOutViewobjects.
export async function getTaskIn<
B extends object = TaskPayloadBody,
H extends object = TaskPayloadHeaders,
>(
scope: { userKey?: string } & GenericScope,
optionals: TaskScopePageOptions & RoutingOptions = {},
): Promise<Page<TaskReadOutView<B, H>>>
Parameters
scope: { userKey?: string } & GenericScope- Defines the scope associated with the tasks.scopeBoundary- Defines the type of scope. SeeSCOPE_BOUNDARYfor all types.scopeKey- A unique identifier tied to the scope.userKey?- (Optional) When provided, retrieves tasks in the scope that were made by the specified user.
optionals(Type:TaskScopePageOptions& RoutingOptions = {}) - Pagination, sorting, and network options.sort?: string[]- (Optional) Task fields to sort by.first?: number- (Optional) Zero-based index of the first task. Defaults to0.max?: number- (Optional) Maximum tasks to return. Defaults to100and cannot exceed100.RoutingOptions- Additional routing options for request handling.
Return value
A promise resolving to a Page<TaskReadOutView<B, M>>, containing a paginated list of matching tasks.
Usage example
import { taskAdapter, SCOPE_BOUNDARY } from 'epicenter-libs';
const scope = {
scopeBoundary: SCOPE_BOUNDARY.GROUP,
scopeKey: '0000017dd3bf540e5ada5b1e058f08f20461',
};
const tasks = await taskAdapter.getTaskIn(scope);
Filtered query
Use the query() function to search for tasks matching specific filter and sort criteria.
Permissions
Requires a role of ANONYMOUS or higher.
No authentication is required to call this function; however, results use facilitator-level row visibility.
Function description
- Constructs a
GETrequest to the/task/searchendpoint. - Supports filtering, sorting, and pagination through
GenericSearchOptions. - Returns a paginated list of
TaskReadOutViewobjects.
export async function query<
B extends object = TaskPayloadBody,
H extends object = TaskPayloadHeaders,
>(
searchOptions: GenericSearchOptions,
optionals: RoutingOptions = {},
): Promise<Page<TaskReadOutView<B, H>>>
Parameters
Filterable/sortable fields include task.taskKey, task.name, task.status, task.scopeBoundary, task.scopeKey, task.userKey, task.groupName, task.episodeName, task.nextExecution, task.failSafeExecution, and task.created.
searchOptions: GenericSearchOptions- Search options for the query.filter?- Filters for searching.sort?- Sorting criteria.first?- The starting index of the page returned.max?- The number of entries per page.
optionals(Type:RoutingOptions = {}) - (Optional) Additional routing options for request handling.
Return value
A promise resolving to a Page<TaskReadOutView<B, M>>, containing a paginated list of matching tasks.
Usage example
import { taskAdapter } from 'epicenter-libs';
const page = await taskAdapter.query({
filter: [
'task.scopeKey=0000017dd3bf540e5ada5b1e058f08f20461', // tasks scoped to this group
'task.status=INITIALIZED', // that have not yet fired
],
sort: ['-task.created'], // newest first
max: 10, // page should only include the first 10 items
});
Delete
Delete task
The destroy() function changes the task's status to cancelled. This prevents a scheduled task from running. For repeating tasks, it cancels all subsequent task runs.
The task data remains in task history for the rest of the task lifespan.
Permissions
Requires a role of FACILITATOR or higher.
Function description
- Constructs a
DELETErequest to the/task/{TASK_KEY}endpoint. - Sets the task's status to
cancelled. - Returns a
voidpromise upon success.
export async function destroy(
taskKey: string,
optionals: RoutingOptions = {},
): Promise<void>
Parameters
taskKey: string- Unique key associated with a task.optionals(Type:RoutingOptions = {}) - (Optional) Additional routing options for request handling.
Return value
A promise that resolves to void when successful.
Usage example
import { taskAdapter } from 'epicenter-libs';
const taskKey = '0000017dd3bf540e5ada5b1e058f08f20461';
await taskAdapter.destroy(taskKey);