diff --git a/CHANGELOG.md b/CHANGELOG.md index e589ceb449..31aa7c5f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,8 @@ * `TelegramBotAPI`: * Currently `UpdateDeserializationStrategy` is publicly available +* `TelegramBotAPI-extensions-utils`: + * Extension `asTelegramUpdate` was added ### 0.27.2 diff --git a/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/JsonFormat.kt b/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/JsonFormat.kt new file mode 100644 index 0000000000..63977802c2 --- /dev/null +++ b/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/JsonFormat.kt @@ -0,0 +1,11 @@ +package com.github.insanusmokrassar.TelegramBotAPI.extensions.utils + +import kotlinx.serialization.json.Json + +@Suppress("EXPERIMENTAL_API_USAGE") +internal val nonstrictJsonFormat = Json { + isLenient = true + ignoreUnknownKeys = true + serializeSpecialFloatingPointValues = true + useArrayPolymorphism = true +} diff --git a/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/updates/UpdateDeserialization.kt b/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/updates/UpdateDeserialization.kt new file mode 100644 index 0000000000..fa650fdd1e --- /dev/null +++ b/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/updates/UpdateDeserialization.kt @@ -0,0 +1,31 @@ +package com.github.insanusmokrassar.TelegramBotAPI.extensions.utils.updates + +import com.github.insanusmokrassar.TelegramBotAPI.extensions.utils.nonstrictJsonFormat +import com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.UpdateDeserializationStrategy +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement + +/** + * @return Deserialize [source] as [com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.Update] + */ +fun Json.asTelegramUpdate(source: String) = parse(UpdateDeserializationStrategy, source) +/** + * @return Deserialize [source] as [com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.Update] + */ +fun Json.asTelegramUpdate(source: JsonElement) = fromJson(UpdateDeserializationStrategy, source) + +/** + * @return Deserialize [this] as [com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.Update]. In fact, + * it is must be JSON + * + * @see Json.asTelegramUpdate + */ +fun String.asTelegramUpdate() = nonstrictJsonFormat.asTelegramUpdate(this) +/** + * @return Deserialize [this] as [com.github.insanusmokrassar.TelegramBotAPI.types.update.abstracts.Update] + * + * @see Json.asTelegramUpdate + */ +fun JsonElement.asTelegramUpdate() = nonstrictJsonFormat.asTelegramUpdate(this) + +