Edits history of script submission #22234 for ' Run Task (apify)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { ApifyClient, Dictionary, TaskCallOptions } from 'apify-client@^2.19.0';
    
    type ApifyApiKey = {
      api_key: string;
    };
    
    type Apify = {
      token: string;
    };
    
    type MemoryInMb =
      | '128'
      | '256'
      | '512'
      | '1024'
      | '2048'
      | '4096'
      | '8192'
      | '16384'
      | '32768';
    
    export type DynSelect_taskId = string;
    export async function taskId(api_key?: ApifyApiKey, oauth_token?: Apify) {
      if (!api_key?.api_key && !oauth_token?.token) {
        return [{ value: '', label: 'Missing Apify API key or OAuth token' }];
      }
    
      try {
        const client = createClient(api_key, oauth_token);
    
        const data = await client.tasks().list();
        const items = data?.items ?? [];
    
        return items.map((task: any) => ({
          value: task.id,
          label: task.title || task.name || task.id,
        }));
      } catch (error: any) {
        return [
          { value: '', label: `Failed to load tasks: ${error.message || error}` },
        ];
      }
    }
    
    const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => {
      const token = oauth_token?.token ?? api_key?.api_key;
      if (!token) {
        throw new Error('Missing Apify API key or OAuth token');
      }
    
      return new ApifyClient({
        token: token,
        requestInterceptors: [
          (request) => {
            if (!request.headers) {
              request.headers = {};
            }
            request.headers['x-apify-integration-platform'] = 'windmill';
            return request;
          },
        ],
      });
    };
    
    async function pollRunStatus(
      client: ApifyClient,
      runId: string,
      options: { throwIfNotSucceeded: boolean; } = { throwIfNotSucceeded: false }
    ): Promise<any> {
      let status = '';
      let runData: any;
      while (true) {
        runData = await client.run(runId).get();
        status = runData.status;
        if (['SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED-OUT'].includes(status)) break;
        await new Promise((res) => setTimeout(res, 1000));
      }
    
      if (options.throwIfNotSucceeded && status !== 'SUCCEEDED') {
        throw new Error(`Actor run did not succeed: ${status}`);
      }
    
      return runData;
    }
    
    export async function main(
      actorTaskId: DynSelect_taskId,
      customBody: object = {},
      timeout?: number | null,
      memoryInMb: MemoryInMb = '1024',
      build?: string,
      waitForFinish: boolean = true,
      api_key?: ApifyApiKey,
      oauth_token?: Apify,
    ) {
      if (!actorTaskId) {
        return { error: 'Task ID is required' };
      }
    
      const client = createClient(api_key, oauth_token);
    
      try {
        const runOptions: TaskCallOptions = {
          waitSecs: 0, // let custom logic handle the polling
        };
    
        if (timeout != null) runOptions.timeout = timeout;
        if (memoryInMb != null) runOptions.memory = Number(memoryInMb);
        if (build) runOptions.build = build;
    
        // Start the task run
        const apiResult = await client
          .task(actorTaskId)
          .call(customBody as Dictionary, runOptions);
    
        if (!apiResult?.id) {
          return { error: 'Run ID not found after running the task' };
        }
    
        if (!waitForFinish) {
          return { ...apiResult };
        }
    
        const runId = apiResult.id;
        const lastRunData = await pollRunStatus(client, runId);
        return { ...lastRunData };
      } catch (error: any) {
        return {
          error: `Failed to run task. Reason: ${error.message}`,
        };
      }
    }
    

    Submitted by jakub.drobnik222 162 days ago