-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubjectsAPI.kt
More file actions
73 lines (58 loc) · 1.91 KB
/
SubjectsAPI.kt
File metadata and controls
73 lines (58 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.yara.raco.api
import com.yara.raco.model.subject.Subject
import com.yara.raco.utils.Json
import com.yara.raco.utils.OkHttpRequest
import com.yara.raco.utils.Result
import com.yara.raco.utils.ResultCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
class SubjectsAPI private constructor() {
suspend fun getSubjects(accessToken: String, language: String = "ca"): Result<List<Subject>> =
try {
val response = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = SUBJECT_URL,
accessToken = accessToken,
language = language
)
}
val statusCode = response.code
val body = withContext(Dispatchers.IO) {
response.body.string()
}
withContext(Dispatchers.IO) {
response.close()
}
if (statusCode == 200) {
val aux = Json.decodeFromString<SubjectResponse>(body).results
Result.Success(aux)
}
else {
Result.Error(ResultCode.ERROR_API_BAD_RESPONSE)
}
}
catch (e: Exception) {
e.printStackTrace()
Result.Error(ResultCode.ERROR_API_BAD_REQUEST)
}
@Serializable
data class SubjectResponse (
val count: Int,
val results: List<Subject>
)
companion object {
private const val SUBJECT_URL = "https://api.fib.upc.edu/v2/jo/assignatures/?format=json"
private var INSTANCE: SubjectsAPI? = null
fun getInstance(): SubjectsAPI {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = SubjectsAPI()
INSTANCE = instance
}
return instance
}
}
}
}