Skip to content

Commit

Permalink
refactor(backend): reduce redundancy in DataUseTerms.fromParameters()
Browse files Browse the repository at this point in the history
  • Loading branch information
chaoran-chen committed Dec 29, 2024
1 parent 23a1c8c commit be8174a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 25 deletions.
43 changes: 19 additions & 24 deletions backend/src/main/kotlin/org/loculus/backend/api/DataUseTerms.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,35 +83,30 @@ sealed interface DataUseTerms {
}

companion object {
fun fromParameters(type: DataUseTermsType, restrictedUntilString: String?): DataUseTerms = when (type) {
DataUseTermsType.OPEN -> Open
DataUseTermsType.RESTRICTED -> Restricted(parseRestrictedUntil(restrictedUntilString))
}
fun fromParameters(type: DataUseTermsType, restrictedUntil: String?): DataUseTerms =
if (type == DataUseTermsType.OPEN) {
Open
} else {
fromParameters(type, restrictedUntil?.let { parseDate(it) })
}

fun fromParameters(type: DataUseTermsType, restrictedUntilString: LocalDate?): DataUseTerms = when (type) {
fun fromParameters(type: DataUseTermsType, restrictedUntil: LocalDate?): DataUseTerms = when (type) {
DataUseTermsType.OPEN -> Open
DataUseTermsType.RESTRICTED ->
if (restrictedUntilString == null) {
throw BadRequestException(
"The date 'restrictedUntil' must be set if 'dataUseTermsType' is RESTRICTED.",
)
} else {
Restricted(restrictedUntilString)
}
}

private fun parseRestrictedUntil(restrictedUntilString: String?): LocalDate {
if (restrictedUntilString == null) {
throw BadRequestException("The date 'restrictedUntil' must be set if 'dataUseTermsType' is RESTRICTED.")
}
return try {
LocalDate.parse(restrictedUntilString)
} catch (e: Exception) {
throw BadRequestException(
"The date 'restrictedUntil' must be a valid date in the format YYYY-MM-DD: $restrictedUntilString.",
DataUseTermsType.RESTRICTED -> {
restrictedUntil ?: throw BadRequestException(
"The date 'restrictedUntil' must be set if 'dataUseTermsType' is RESTRICTED.",
)
Restricted(restrictedUntil)
}
}

private fun parseDate(restrictedUntilString: String): LocalDate = try {
LocalDate.parse(restrictedUntilString)
} catch (e: Exception) {
throw BadRequestException(
"The date 'restrictedUntil' must be a valid date in the format YYYY-MM-DD: $restrictedUntilString.",
)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class DataUseTermsDatabaseService(
changeDate = it[DataUseTermsTable.changeDateColumn].toString(),
dataUseTerms = DataUseTerms.fromParameters(
type = DataUseTermsType.fromString(it[DataUseTermsTable.dataUseTermsTypeColumn]),
restrictedUntilString = it[DataUseTermsTable.restrictedUntilColumn],
restrictedUntil = it[DataUseTermsTable.restrictedUntilColumn],
),
userName = it[DataUseTermsTable.userNameColumn],
)
Expand Down

0 comments on commit be8174a

Please sign in to comment.