Skip to content

Commit e03cf5f

Browse files
committed
feat(network): Create Repository and Integrate Caching Logic
1 parent a6a0c1f commit e03cf5f

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

network/build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ android {
3030
}
3131

3232
dependencies {
33+
implementation(project(":database"))
3334
implementation(libs.androidx.core.ktx)
3435
implementation(libs.androidx.appcompat)
3536
implementation(libs.com.google.android.material)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.anysoftkeyboard.janus.network
2+
3+
import com.anysoftkeyboard.janus.database.TranslationDao
4+
import com.anysoftkeyboard.janus.database.Translation
5+
6+
class TranslationRepository(private val wikipediaApi: WikipediaApi, private val translationDao: TranslationDao) {
7+
8+
suspend fun getTranslation(sourceWord: String, sourceLang: String, targetLang: String): Translation? {
9+
// First, try to get the translation from the database
10+
val cachedTranslation = translationDao.findTranslation(sourceWord, sourceLang, targetLang)
11+
if (cachedTranslation != null) {
12+
return cachedTranslation
13+
}
14+
15+
// If not found in the database, fetch from the network
16+
return try {
17+
val searchResponse = wikipediaApi.search(sourceWord)
18+
val searchResult = searchResponse.query.search.firstOrNull()
19+
20+
if (searchResult != null) {
21+
val newTranslation = Translation(
22+
sourceWord = sourceWord,
23+
sourceLangCode = sourceLang,
24+
sourceArticleUrl = "https://en.wikipedia.org/wiki/${searchResult.title}",
25+
sourceShortDescription = searchResult.snippet,
26+
sourceSummary = null, // Wikipedia search API does not provide full summary
27+
translatedWord = searchResult.title, // For now, assume translated word is the article title
28+
targetLangCode = targetLang,
29+
targetArticleUrl = "https://en.wikipedia.org/wiki/${searchResult.title}",
30+
targetShortDescription = searchResult.snippet,
31+
targetSummary = null
32+
)
33+
translationDao.insertTranslation(newTranslation)
34+
newTranslation
35+
} else {
36+
null
37+
}
38+
} catch (e: Exception) {
39+
e.printStackTrace()
40+
null
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)