import { assertExists , assertTrue } from '@ulangi/assert' ; import { SQLiteDatabase } from '@ulangi/sqlite-adapter' ; import { ActionType , createAction } from '@ulangi/ulangi-action' ; import { UploadUserRequest } from '@ulangi/ulangi-common/interfaces' ; import { UploadUserResponseResolver } from '@ulangi/ulangi-common/resolvers' ; import { DirtyUserModel , SessionModel } 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 UploadUserSaga { private uploadUserResponseResolver = new UploadUserResponseResolver ( ) ; private userDb : SQLiteDatabase ; private sharedDb : SQLiteDatabase ; private sessionModel : SessionModel ; private dirtyUserModel : DirtyUserModel ; public constructor ( userDb , sharedDb , sessionModel , dirtyUserModel ) { this . userDb = userDb ; this . sharedDb = sharedDb ; this . sessionModel = sessionModel ; this . dirtyUserModel = dirtyUserModel ; } public * uploadUser ( apiUrl ) { let success , noMore ; try { const userId = yield call ( [ this . sessionModel , 'getUserId' ] , this . sharedDb ) ; const accessToken = yield call ( [ this . sessionModel , 'getAccessToken' ] , this . sharedDb ) ; const result = yield call ( [ this . dirtyUserModel , 'getDirtyUserForSyncing' ] , this . userDb , assertExists ( userId ) , true ) ; const { user , markUserAsSynced } = result ; yield put ( createAction ( ActionType . USER__UPLOADING_USER , { user , } ) ) ; noMore = user === null ; if ( user !== null ) { const response = yield call ( [ axios , 'request' ] , createRequest < UploadUserRequest > ( 'post' , apiUrl , '/upload-user' , null , { user } , { accessToken : assertExists ( accessToken ) } ) ) ; const uploadResult = this . uploadUserResponseResolver . resolve ( response . data , true ) ; success = assertTrue ( uploadResult . success ) ; yield call ( [ this . userDb , 'transaction' ] , markUserAsSynced ) ; yield put ( createAction ( ActionType . USER__UPLOAD_USER_SUCCEEDED , { noMore , } ) ) ; } else { success = true ; yield put ( createAction ( ActionType . USER__UPLOAD_USER_SUCCEEDED , { noMore } ) ) ; } } catch ( error ) { yield put ( createAction ( ActionType . USER__UPLOAD_USER_FAILED , { errorCode : errorConverter . getErrorCode ( error ) , error , } ) ) ; success = false ; } return { success , noMore } ; } }