Fixed method to get information from MongoDb

v5
Jéluchu 9 months ago
parent 96b47813f7
commit d41154274d

@ -23,7 +23,7 @@ RUN gradle buildFatJar --no-daemon
FROM amazoncorretto:21 AS runtime FROM amazoncorretto:21 AS runtime
EXPOSE 8080/tcp EXPOSE 8080/tcp
RUN mkdir /app RUN mkdir /app
COPY --from=build /home/gradle/src/build/libs/*.jar /app/app.jar COPY --from=build /home/gradle/src/build/libs/aruppi-api-all.jar /app/app.jar
COPY entrypoint.sh /app/entrypoint.sh COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /app/entrypoint.sh RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"] ENTRYPOINT ["/entrypoint.sh"]

@ -2,14 +2,14 @@
# Check if MONGO_CONNECTION_STRING is defined # Check if MONGO_CONNECTION_STRING is defined
if [ -z "$MONGO_CONNECTION_STRING" ]; then if [ -z "$MONGO_CONNECTION_STRING" ]; then
echo "ERROR: The environment variable for the database, MONGO_CONNECTION_STRING is not defined." >&2 echo -e "ERROR: The environment variable MONGO_CONNECTION_STRING is not defined.\n\tYou must provide a valid Connection String"
exit 1 exit 1
fi fi
# Verificar si MONGO_DATABASE_NAME está definido # Verificar si MONGO_DATABASE_NAME está definido
if [ -z "$MONGO_DATABASE_NAME" ]; then if [ -z "$MONGO_DATABASE_NAME" ]; then
echo "WARNING: The environment variable for the database, MONGO_DATABASE_NAME, is not defined. It is using mongodb as the default value." >&2 echo -e "WARNING: The environment variable for the database, MONGO_DATABASE_NAME, is not defined.\n\tUsing aruppi as default value."
MONGO_DATABASE_NAME="mongodb" MONGO_DATABASE_NAME="aruppi"
fi fi
@ -25,10 +25,12 @@ ktor:
db: db:
mongo: mongo:
connectionStrings: "${MONGO_CONNECTION_STRING}" connectionStrings: ${MONGO_CONNECTION_STRING}
database: database:
name: "${MONGO_DATABASE_NAME:-mongodb}" name: ${MONGO_DATABASE_NAME:-mongodb}
EOF EOF
cd /app/
# Run the application with the specified configuration # Run the application with the specified configuration
exec java -Dconfig.file=/app/application.yaml -jar /app/app.jar exec java -Dconfig.file=/app/application.yaml -jar /app/app.jar

@ -0,0 +1,115 @@
package com.jeluchu.core.extensions
import org.bson.Document
import java.text.SimpleDateFormat
import java.util.*
fun Document.getStringSafe(key: String, defaultValue: String = ""): String {
return try {
when (val value = this[key]) {
is String -> value
is Number, is Boolean -> value.toString()
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getIntSafe(key: String, defaultValue: Int = 0): Int {
return try {
when (val value = this[key]) {
is Int -> value
is Number -> value.toInt()
is String -> value.toIntOrNull() ?: defaultValue
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getDoubleSafe(key: String, defaultValue: Double = 0.0): Double {
return try {
when (val value = this[key]) {
is Double -> value
is Number -> value.toDouble()
is String -> value.toDoubleOrNull() ?: defaultValue
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getFloatSafe(key: String, defaultValue: Float = 0.0f): Float {
return try {
when (val value = this[key]) {
is Float -> value
is Number -> value.toFloat()
is String -> value.toFloatOrNull() ?: defaultValue
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getLongSafe(key: String, defaultValue: Long = 0L): Long {
return try {
val value = this.get(key)
when (value) {
is Long -> value
is Number -> value.toLong()
is String -> value.toLongOrNull() ?: defaultValue
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getBooleanSafe(key: String, defaultValue: Boolean = false): Boolean {
return try {
when (val value = this[key]) {
is Boolean -> value
is String -> value.toBoolean()
is Number -> value.toInt() != 0
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getDateSafe(key: String, defaultValue: Date = Date(0)): Date {
return try {
when (val value = this[key]) {
is Date -> value
is String -> SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(value) ?: defaultValue
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
inline fun <reified T> Document.getListSafe(key: String, defaultValue: List<T> = emptyList()): List<T> {
return try {
when (val value = this[key]) {
is List<*> -> value.filterIsInstance<T>()
else -> defaultValue
}
} catch (e: Exception) {
defaultValue
}
}
fun Document.getDocumentSafe(key: String): Document? {
return try {
val value = this[key]
if (value is Document) value else null
} catch (e: Exception) {
null
}
}

@ -1,149 +1,151 @@
package com.jeluchu.features.anime.mappers package com.jeluchu.features.anime.mappers
import com.example.models.* import com.example.models.*
import com.jeluchu.core.extensions.*
import kotlinx.serialization.json.Json
import org.bson.Document import org.bson.Document
fun documentToMoreInfoEntity(doc: Document): MoreInfoEntity { fun documentToMoreInfoEntity(doc: Document): MoreInfoEntity {
return MoreInfoEntity( return MoreInfoEntity(
id = doc.getLong("id") ?: 0, id = doc.getLongSafe("id"),
malId = doc.getInteger("malId", 0) ?: 0, malId = doc.getIntSafe("malId"),
title = doc.getString("title") ?: "", title = doc.getStringSafe("title"),
poster = doc.getString("poster") ?: "", poster = doc.getStringSafe("poster"),
cover = doc.getString("cover") ?: "", cover = doc.getStringSafe("cover"),
genres = doc.getList("genres", String::class.java) ?: emptyList(), genres = doc.getListSafe<String>("genres"),
synopsis = doc.getString("synopsis") ?: "", synopsis = doc.getStringSafe("synopsis"),
episodes = doc.getList("episodes", Document::class.java)?.map { documentToMergedEpisode(it) } ?: emptyList(), episodes = doc.getListSafe<Document>("episodes").map { documentToMergedEpisode(it) } ?: emptyList(),
episodesCount = doc.getInteger("episodesCount", 0) ?: 0, episodesCount = doc.getIntSafe("episodesCount", 0) ?: 0,
score = doc.getString("score") ?: "", score = doc.getStringSafe("score") ?: "",
staff = doc.getList("staff", Document::class.java)?.map { documentToStaff(it) } ?: emptyList(), staff = doc.getListSafe<Document>("staff").map { documentToStaff(it) } ?: emptyList(),
characters = doc.getList("characters", Document::class.java)?.map { documentToCharacter(it) } ?: emptyList(), characters = doc.getListSafe<Document>("characters").map { documentToCharacter(it) } ?: emptyList(),
status = doc.getString("status") ?: "", status = doc.getStringSafe("status") ?: "",
type = doc.getString("type") ?: "", type = doc.getStringSafe("type") ?: "",
url = doc.getString("url") ?: "", url = doc.getStringSafe("url") ?: "",
promo = doc.get("promo", Document::class.java)?.let { documentToVideoPromo(it) } ?: VideoPromo(), promo = doc.getDocumentSafe("promo")?.let { documentToVideoPromo(it) } ?: VideoPromo(),
source = doc.getString("source") ?: "", source = doc.getStringSafe("source") ?: "",
duration = doc.getString("duration") ?: "", duration = doc.getStringSafe("duration") ?: "",
rank = doc.getInteger("rank", 0) ?: 0, rank = doc.getIntSafe("rank", 0) ?: 0,
titles = doc.getList("titles", Document::class.java)?.map { documentToAlternativeTitles(it) } ?: emptyList(), titles = doc.getListSafe<Document>("titles").map { documentToAlternativeTitles(it) } ?: emptyList(),
airing = doc.getBoolean("airing", false) ?: false, airing = doc.getBooleanSafe("airing") ?: false,
aired = doc.get("aired", Document::class.java)?.let { documentToAiringTime(it) } ?: AiringTime(), aired = doc.getDocumentSafe("aired")?.let { documentToAiringTime(it) } ?: AiringTime(),
broadcast = doc.get("broadcast", Document::class.java)?.let { documentToAnimeBroadcast(it) } ?: AnimeBroadcast(), broadcast = doc.getDocumentSafe("broadcast")?.let { documentToAnimeBroadcast(it) } ?: AnimeBroadcast(),
season = doc.getString("season") ?: "", season = doc.getStringSafe("season") ?: "",
year = doc.getInteger("year", 0), year = doc.getIntSafe("year", 0),
external = doc.getList("external", Document::class.java)?.map { documentToExternalLinks(it) } ?: emptyList(), external = doc.getListSafe<Document>("external").map { documentToExternalLinks(it) } ?: emptyList(),
streaming = doc.getList("streaming", Document::class.java)?.map { documentToExternalLinks(it) } ?: emptyList(), streaming = doc.getListSafe<Document>("streaming").map { documentToExternalLinks(it) } ?: emptyList(),
studios = doc.getList("studios", Document::class.java)?.map { documentToCompanies(it) } ?: emptyList(), studios = doc.getListSafe<Document>("studios").map { documentToCompanies(it) } ?: emptyList(),
licensors = doc.getList("licensors", Document::class.java)?.map { documentToCompanies(it) } ?: emptyList(), licensors = doc.getListSafe<Document>("licensors").map { documentToCompanies(it) } ?: emptyList(),
producers = doc.getList("producers", Document::class.java)?.map { documentToCompanies(it) } ?: emptyList(), producers = doc.getListSafe<Document>("producers").map { documentToCompanies(it) } ?: emptyList(),
theme = doc.get("theme", Document::class.java)?.let { documentToThemes(it) } ?: Themes(), theme = doc.getDocumentSafe("theme")?.let { documentToThemes(it) } ?: Themes(),
relations = doc.getList("relations", Document::class.java)?.map { documentToRelated(it) } ?: emptyList(), relations = doc.getListSafe<Document>("relations").map { documentToRelated(it) } ?: emptyList(),
stats = doc.get("stats", Document::class.java)?.let { documentToStatistics(it) } ?: Statistics(), stats = doc.getDocumentSafe("stats")?.let { documentToStatistics(it) } ?: Statistics(),
gallery = doc.getList("gallery", Document::class.java)?.map { documentToImageMediaEntity(it) } ?: emptyList(), gallery = doc.getListSafe<Document>("gallery").map { documentToImageMediaEntity(it) } ?: emptyList(),
episodeSource = doc.getString("episodeSource") ?: "" episodeSource = doc.getStringSafe("episodeSource") ?: ""
) )
} }
fun documentToActor(doc: Document): Actor { fun documentToActor(doc: Document): Actor {
return Actor( return Actor(
person = doc.get("person", Document::class.java)?.let { documentToIndividual(it) } ?: Individual(), person = doc.getDocumentSafe("person")?.let { documentToIndividual(it) } ?: Individual(),
language = doc.getString("language") ?: "" language = doc.getStringSafe("language") ?: ""
) )
} }
fun documentToAiringTime(doc: Document): AiringTime { fun documentToAiringTime(doc: Document): AiringTime {
return AiringTime( return AiringTime(
from = doc.getString("from") ?: "", from = doc.getStringSafe("from") ?: "",
to = doc.getString("to") ?: "" to = doc.getStringSafe("to") ?: ""
) )
} }
fun documentToAlternativeTitles(doc: Document): AlternativeTitles { fun documentToAlternativeTitles(doc: Document): AlternativeTitles {
return AlternativeTitles( return AlternativeTitles(
title = doc.getString("title") ?: "", title = doc.getStringSafe("title") ?: "",
type = doc.getString("type") ?: "" type = doc.getStringSafe("type") ?: ""
) )
} }
fun documentToAnimeBroadcast(doc: Document): AnimeBroadcast { fun documentToAnimeBroadcast(doc: Document): AnimeBroadcast {
return AnimeBroadcast( return AnimeBroadcast(
day = doc.getString("day") ?: "", day = doc.getStringSafe("day") ?: "",
time = doc.getString("time") ?: "", time = doc.getStringSafe("time") ?: "",
timezone = doc.getString("timezone") ?: "" timezone = doc.getStringSafe("timezone") ?: ""
) )
} }
fun documentToAnimeSource(doc: Document): AnimeSource { fun documentToAnimeSource(doc: Document): AnimeSource {
return AnimeSource( return AnimeSource(
id = doc.getString("id") ?: "", id = doc.getStringSafe("id") ?: "",
source = doc.getString("source") ?: "" source = doc.getStringSafe("source") ?: ""
) )
} }
fun documentToCharacter(doc: Document): Character { fun documentToCharacter(doc: Document): Character {
return Character( return Character(
character = doc.get("character", Document::class.java)?.let { documentToIndividual(it) } ?: Individual(), character = doc.getDocumentSafe("character")?.let { documentToIndividual(it) } ?: Individual(),
role = doc.getString("role") ?: "", role = doc.getStringSafe("role") ?: "",
voiceActor = doc.getList("voiceActor", Document::class.java)?.map { documentToActor(it) } ?: emptyList() voiceActor = doc.getListSafe<Document>("voiceActor").map { documentToActor(it) } ?: emptyList()
) )
} }
fun documentToCompanies(doc: Document): Companies { fun documentToCompanies(doc: Document): Companies {
return Companies( return Companies(
malId = doc.getInteger("malId", 0), malId = doc.getIntSafe("malId", 0),
name = doc.getString("name") ?: "", name = doc.getStringSafe("name") ?: "",
type = doc.getString("type") ?: "", type = doc.getStringSafe("type") ?: "",
url = doc.getString("url") ?: "" url = doc.getStringSafe("url") ?: ""
) )
} }
fun documentToExternalLinks(doc: Document): ExternalLinks { fun documentToExternalLinks(doc: Document): ExternalLinks {
return ExternalLinks( return ExternalLinks(
url = doc.getString("url") ?: "", url = doc.getStringSafe("url") ?: "",
name = doc.getString("name") ?: "" name = doc.getStringSafe("name") ?: ""
) )
} }
fun documentToImageMediaEntity(doc: Document): ImageMediaEntity { fun documentToImageMediaEntity(doc: Document): ImageMediaEntity {
return ImageMediaEntity( return ImageMediaEntity(
media = doc.getString("media") ?: "", media = doc.getStringSafe("media") ?: "",
thumbnail = doc.getString("thumbnail") ?: "", thumbnail = doc.getStringSafe("thumbnail") ?: "",
width = doc.getInteger("width", 0), width = doc.getIntSafe("width", 0),
height = doc.getInteger("height", 0), height = doc.getIntSafe("height", 0),
url = doc.getString("url") ?: "" url = doc.getStringSafe("url") ?: ""
) )
} }
fun documentToImages(doc: Document): Images { fun documentToImages(doc: Document): Images {
return Images( return Images(
generic = doc.getString("generic") ?: "", generic = doc.getStringSafe("generic") ?: "",
small = doc.getString("small") ?: "", small = doc.getStringSafe("small") ?: "",
medium = doc.getString("medium") ?: "", medium = doc.getStringSafe("medium") ?: "",
large = doc.getString("large") ?: "", large = doc.getStringSafe("large") ?: "",
maximum = doc.getString("maximum") ?: "" maximum = doc.getStringSafe("maximum") ?: ""
) )
} }
fun documentToIndividual(doc: Document): Individual { fun documentToIndividual(doc: Document): Individual {
return Individual( return Individual(
malId = doc.getInteger("malId", 0), malId = doc.getIntSafe("malId", 0),
url = doc.getString("url") ?: "", url = doc.getStringSafe("url") ?: "",
name = doc.getString("name") ?: "", name = doc.getStringSafe("name") ?: "",
images = doc.getString("images") ?: "" images = doc.getStringSafe("images") ?: ""
) )
} }
fun documentToMergedEpisode(doc: Document): MergedEpisode { fun documentToMergedEpisode(doc: Document): MergedEpisode {
return MergedEpisode( return MergedEpisode(
number = doc.getInteger("number", 0), number = doc.getIntSafe("number", 0),
ids = doc.getList("ids", Document::class.java)?.map { documentToAnimeSource(it) }?.toMutableList() ?: mutableListOf(), ids = doc.getListSafe<Document>("ids").map { documentToAnimeSource(it) }.toMutableList() ?: mutableListOf(),
nextEpisodeDate = doc.getString("nextEpisodeDate") ?: "" nextEpisodeDate = doc.getStringSafe("nextEpisodeDate") ?: ""
) )
} }
fun documentToRelated(doc: Document): Related { fun documentToRelated(doc: Document): Related {
return Related( return Related(
entry = doc.getList("entry", Document::class.java)?.map { documentToCompanies(it) } ?: emptyList(), entry = doc.getListSafe<Document>("entry").map { documentToCompanies(it) } ?: emptyList(),
relation = doc.getString("relation") ?: "" relation = doc.getStringSafe("relation") ?: ""
) )
} }
@ -154,42 +156,50 @@ fun documentToScore(doc: Document): Score {
is Int -> value.toDouble() is Int -> value.toDouble()
else -> 0.0 else -> 0.0
}, },
score = doc.getInteger("score", 0), score = doc.getIntSafe("score", 0),
votes = doc.getInteger("votes", 0) votes = doc.getIntSafe("votes", 0)
) )
} }
fun documentToStaff(doc: Document): Staff { fun documentToStaff(doc: Document): Staff {
return Staff( return Staff(
person = doc.get("person", Document::class.java)?.let { documentToIndividual(it) } ?: Individual(), person = doc.get("person", Document::class.java)?.let { documentToIndividual(it) } ?: Individual(),
positions = doc.getList("positions", String::class.java) ?: emptyList() positions = doc.getListSafe<String>("positions") ?: emptyList()
) )
} }
fun documentToStatistics(doc: Document): Statistics { fun documentToStatistics(doc: Document): Statistics {
return Statistics( return Statistics(
completed = doc.getInteger("completed"), completed = doc.getIntSafe("completed") ?: 0,
dropped = doc.getInteger("dropped"), dropped = doc.getIntSafe("dropped") ?: 0,
onHold = doc.getInteger("onHold"), onHold = doc.getIntSafe("onHold") ?: 0,
planToWatch = doc.getInteger("planToWatch"), planToWatch = doc.getIntSafe("planToWatch") ?: 0,
scores = doc.getList("scores", Document::class.java)?.map { documentToScore(it) } ?: emptyList(), scores = doc.getListSafe<Document>("scores").map { documentToScore(it) } ?: emptyList(),
total = doc.getInteger("total"), total = doc.getIntSafe("total") ?: 0,
watching = doc.getInteger("watching") watching = doc.getIntSafe("watching") ?: 0
) )
} }
fun documentToThemes(doc: Document): Themes { fun documentToThemes(doc: Document): Themes {
return Themes( return Themes(
endings = doc.getList("endings", String::class.java) ?: emptyList(), endings = doc.getListSafe<String>("endings"),
openings = doc.getList("openings", String::class.java) ?: emptyList() openings = doc.getListSafe<String>("openings")
) )
} }
fun documentToVideoPromo(doc: Document): VideoPromo { fun documentToVideoPromo(doc: Document): VideoPromo {
return VideoPromo( return VideoPromo(
embedUrl = doc.getString("embedUrl") ?: "", embedUrl = doc.getStringSafe("embedUrl") ?: "",
url = doc.getString("url") ?: "", url = doc.getStringSafe("url") ?: "",
youtubeId = doc.getString("youtubeId") ?: "", youtubeId = doc.getStringSafe("youtubeId") ?: "",
images = doc.get("images", Document::class.java)?.let { documentToImages(it) } ?: Images() images = doc.get("images", Document::class.java)?.let { documentToImages(it) } ?: Images()
) )
} }
fun List<Document>.toMoreInfoEntity(): List<MoreInfoEntity> {
val json = Json { ignoreUnknownKeys = true }
val jsonStrings = map { it.toJson() }
return jsonStrings.map { json.decodeFromString<MoreInfoEntity>(it) }
}

@ -3,6 +3,7 @@ package com.jeluchu.features.anime.services
import com.jeluchu.core.messages.ErrorMessages import com.jeluchu.core.messages.ErrorMessages
import com.jeluchu.core.models.ErrorResponse import com.jeluchu.core.models.ErrorResponse
import com.jeluchu.features.anime.mappers.documentToMoreInfoEntity import com.jeluchu.features.anime.mappers.documentToMoreInfoEntity
import com.jeluchu.features.anime.mappers.toMoreInfoEntity
import com.mongodb.client.MongoDatabase import com.mongodb.client.MongoDatabase
import com.mongodb.client.model.Filters import com.mongodb.client.model.Filters
import io.ktor.http.* import io.ktor.http.*

Loading…
Cancel
Save