Skip to content
Snippets Groups Projects
jobsService.ts 1.1 KiB
Newer Older
  • Learn to ignore specific revisions
  • Hugo NOUTS's avatar
    Hugo NOUTS committed
    import { Client } from 'cozy-client'
    import { JOBS_DOCTYPE } from 'doctypes'
    import KonnectorJobWatcher from 'cozy-harvest-lib/dist/models/konnector/KonnectorJobWatcher'
    import {
      ERROR_EVENT,
      LOGIN_SUCCESS_EVENT,
      SUCCESS_EVENT,
    } from 'cozy-harvest-lib/dist/models/KonnectorJob'
    
    // TODO import enums from harvestLib
    
    export enum JobState {
      Errored = 'errored',
      Running = 'running',
      Done = 'done',
    }
    
    export class JobService {
      constructor(private _client: Client) {
        this._client = _client
      }
    
      fetchJob = async jobId => {
        return await this._client.query(this._client.get(JOBS_DOCTYPE, jobId))
      }
    
      watch = async (job: any, callbackResponse: any) => {
        const konnectorJobWatcher = new KonnectorJobWatcher(this._client, job, {
          expectedSuccessDelay: 8000,
        })
        konnectorJobWatcher.watch()
    
        konnectorJobWatcher.on(ERROR_EVENT, () => {
          callbackResponse(JobState.Errored)
        })
    
        konnectorJobWatcher.on(LOGIN_SUCCESS_EVENT, () => {
          callbackResponse(JobState.Done)
        })
    
        konnectorJobWatcher.on(SUCCESS_EVENT, () => {
          callbackResponse(JobState.Done)
        })
      }
    }