import { assertExists } from '@ulangi/assert' ; import { SQLiteDatabase , Transaction } from '@ulangi/sqlite-adapter' ; import { ActionType , createAction } from '@ulangi/ulangi-action' ; import { DownloadUserRequest } from '@ulangi/ulangi-common/interfaces' ; import { DownloadUserResponseResolver } from '@ulangi/ulangi-common/resolvers' ; import { SessionModel , UserModel } from '@ulangi/ulangi-local-database' ; import axios , { AxiosResponse } from 'axios' ; import { call , put } from 'redux-saga/effects' ; import { PromiseType } from 'utility-types' ; import { errorConverter } from '../converters/ErrorConverter' ; import { createRequest } from '../utils/createRequest' ; export class DownloadUserSaga { private downloadUserResponseResolver = new DownloadUserResponseResolver ( ) ; private userDb : SQLiteDatabase ; private sharedDb : SQLiteDatabase ; private sessionModel : SessionModel ; private userModel : UserModel ; public constructor ( userDb , sharedDb , sessionModel , userModel ) { this . userDb = userDb ; this . sharedDb = sharedDb ; this . sessionModel = sessionModel ; this . userModel = userModel ; } public * downloadUser ( apiUrl ) { let success ; try { yield put ( createAction ( ActionType . USER__DOWNLOADING_USER , null ) ) ; const accessToken = yield call ( [ this . sessionModel , 'getAccessToken' ] , this . sharedDb ) ; const response = yield call ( [ axios , 'request' ] , createRequest < DownloadUserRequest > ( 'get' , apiUrl , '/download-user' , null , null , { accessToken : assertExists ( accessToken ) } ) ) ; const { user } = this . downloadUserResponseResolver . resolve ( response . data , true ) ; yield call ( [ this . userDb , 'transaction' ] , ( tx ) : void => { this . userModel . updateUser ( tx , user , 'remote' ) ; } ) ; yield put ( createAction ( ActionType . USER__DOWNLOAD_USER_SUCCEEDED , null ) ) ; success = true ; } catch ( error ) { yield put ( createAction ( ActionType . USER__DOWNLOAD_USER_FAILED , { errorCode : errorConverter . getErrorCode ( error ) , error , } ) ) ; success = false ; } return { success , noMore : true } ; } }