import { PollTimeout } from "../error.js";
import { constructParams } from "../util.js";
function workflow(w) {
return {
...w,
created: new Date(w.created),
started: w.started ? new Date(w.started) : null,
finished: w.finished ? new Date(w.finished) : null,
};
}
/** Metafold workflows endpoint. */
export class Workflows {
client;
constructor(client) {
this.client = client;
}
/**
* List workflows.
*
* @param {Object} [params] - Optional list parameters.
* @param {string} [params.sort] - Sort string. For details on syntax see the Metafold API docs.
* Supported sorting fields are: "id", "created", "started", or "finished".
* @param {string} [params.q] - Query string. For details on syntax see the Metafold API docs.
* Supported search fields are: "id" and "state".
* @returns List of workflow resources.
*/
async list({ sort, q } = {}) {
const params = constructParams({ sort, q });
const r = await this.client.get(`/projects/${this.client.projectID}/workflows`, { params });
return r.data.map(workflow);
}
/**
* Get a workflow.
*
* @param {string} id - ID of workflow to get.
* @returns Workflow resource.
*/
async get(id) {
const r = await this.client.get(`/projects/${this.client.projectID}/workflows/${id}`);
return workflow(r.data);
}
/**
* Dispatch a new workflow and wait for the result.
*
* @param {string} definition - Workflow definition encoded as YAML.
* @param {Object} [params] - Workflow parameters.
* @param {Object} [assets] - Workflow assets.
* @param {number} [timeout=12000] - Time in seconds to wait for a result.
* @returns Completed workflow resource.
*/
async run(definition, params, assets, timeout = 1000 * 60 * 2) {
const data = constructParams({ definition, assets, parameters: params });
let r = await this.client.post(`/projects/${this.client.projectID}/workflows`, data, {
headers: { "Content-Type": "application/json" },
});
const url = r.data.link;
try {
r = await this.client.poll(url, timeout, 2);
}
catch (e) {
if (e instanceof PollTimeout) {
throw new Error(`Workflow failed to complete within ${timeout} ms`, { cause: e });
}
else {
throw e;
}
}
return workflow(r.data);
}
/**
* Cancel a running workflow.
*
* @param {string} id - ID of workflow to canel.
* @returns Workflow resource.
*/
async cancel(id) {
const r = await this.client.post(`/projects/${this.client.projectID}/workflows/${id}/cancel`);
return workflow(r.data);
}
/**
* Delete a workflow.
*
* @param {string} id - ID of workflow to delete.
*/
async delete(id) {
await this.client.delete(`/projects/${this.client.projectID}/workflows/${id}`);
}
}