import { assertExists } from '@ulangi/assert' ; import { SQLiteDatabase } from '@ulangi/sqlite-adapter' ; import { Action , ActionType , createAction } from '@ulangi/ulangi-action' ; import { GetDictionaryEntryRequest } from '@ulangi/ulangi-common/interfaces' ; import { GetDictionaryEntryResponseResolver } from '@ulangi/ulangi-common/resolvers' ; import { SessionModel } from '@ulangi/ulangi-local-database' ; import axios , { AxiosResponse } from 'axios' ; import { Task } from 'redux-saga' ; import { call , cancel , fork , put , take } from 'redux-saga/effects' ; import { PromiseType } from 'utility-types' ; import { errorConverter } from '../converters/ErrorConverter' ; import { SagaEnv } from '../interfaces/SagaEnv' ; import { createRequest } from '../utils/createRequest' ; import { ProtectedSaga } from './ProtectedSaga' ; export class DictionarySaga extends ProtectedSaga { private getEntryTask ? : Task ; private getDictionaryEntryResponseResolver = new GetDictionaryEntryResponseResolver ( ) ; private sharedDb : SQLiteDatabase ; private sessionModel : SessionModel ; public constructor ( sharedDb , sessionModel ) { super ( ) ; this . sharedDb = sharedDb ; this . sessionModel = sessionModel ; } public * run ( env ) { yield fork ( [ this , this . allowGetAndClearEntry ] , env . API_URL ) ; } public * allowGetAndClearEntry ( apiUrl ) { this . getEntryTask = yield fork ( [ this , this . allowGetEntry ] , apiUrl ) ; yield fork ( [ this , this . allowClearEntry ] , apiUrl ) ; } private * allowClearEntry ( apiUrl ) { while ( true ) { yield take ( ActionType . DICTIONARY__CLEAR_ENTRY ) ; if ( typeof this . getEntryTask !== 'undefined' ) { yield cancel ( this . getEntryTask ) ; } this . getEntryTask = yield fork ( [ this , this . allowGetEntry ] , apiUrl ) ; } } private * allowGetEntry ( apiUrl ) { while ( true ) { const action = yield take ( ActionType . DICTIONARY__GET_ENTRY ) ; const { searchTerm , searchTermLanguageCode , translatedToLanguageCode , } = action . payload ; try { yield put ( createAction ( ActionType . DICTIONARY__GETTING_ENTRY , null ) ) ; const result = yield call ( [ this . sessionModel , 'getAccessToken' ] , this . sharedDb ) ; const accessToken = assertExists ( result ) ; const response = yield call ( [ axios , 'request' ] , createRequest < GetDictionaryEntryRequest > ( 'get' , apiUrl , '/get-dictionary-entry' , { searchTerm , searchTermLanguageCode , translatedToLanguageCode , } , null , { accessToken } ) ) ; const { dictionaryEntry , traditionalEntry , masculineEntry , } = this . getDictionaryEntryResponseResolver . resolve ( response . data , true ) ; yield put ( createAction ( ActionType . DICTIONARY__GET_ENTRY_SUCCEEDED , { dictionaryEntry , traditionalEntry , masculineEntry , } ) ) ; } catch ( error ) { yield put ( createAction ( ActionType . DICTIONARY__GET_ENTRY_FAILED , { searchTerm , errorCode : errorConverter . getErrorCode ( error ) , error , } ) ) ; } } } }