Skip to content
Snippets Groups Projects
connectionService.ts 1.82 KiB
Newer Older
  • Learn to ignore specific revisions
  • Hugo NOUTS's avatar
    Hugo NOUTS committed
    import { Client } from 'cozy-client'
    import { Account, Konnector, Trigger } from 'doctypes'
    import { AccountService } from './accountService'
    import { TriggerService } from './triggersService'
    import KonnectorService from './konnectorService'
    
    export class ConnectionService {
      constructor(
        private _client: Client,
        private _konnectorId: string,
        private _login: string,
        private _password: string
      ) {
        this._client = _client
        this._konnectorId = _konnectorId
        this._login = _login
        this._password = _password
      }
    
      connectNewUser = async () => {
        // Retrieve konnector
        const konnectorService = new KonnectorService(
          this._client,
          this._konnectorId
        )
        const konnector: Konnector = await konnectorService.fetchKonnector()
        if (!konnector || !konnector.slug) {
          throw new Error(`Could not find konnector for ${this._konnectorId}`)
        }
        // Creation of the account linked to the konnector retrieved
        const accountService = new AccountService(
          this._client,
          this._login,
          this._password,
          konnector
        )
        const account: Account = await accountService.createAccount()
        if (!account || !account._id) {
          throw new Error(`Error during account creation`)
        }
        // creation of the trigger for the konnector retrieve and the created account
        const triggersServices = new TriggerService(
          this._client,
          account,
          konnector
        )
        const trigger: Trigger = await triggersServices.createTrigger()
        if (!trigger) {
          throw new Error(`Error during trigger creation`)
        }
    
    Yoan VALLET's avatar
    Yoan VALLET committed
        return {
          account: account,
          trigger: trigger,
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
        }
    
    Yoan VALLET's avatar
    Yoan VALLET committed
        //Launch the creation trigger
        // const job = await triggersServices.launchTrigger()
        // if (!job) {
        //   throw new Error(`Error during trigger launching`)
        // }
        // return job
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
      }
    }