diff --git a/article-api/src/main/scala/no/ndla/articleapi/controller/ArticleControllerV2.scala b/article-api/src/main/scala/no/ndla/articleapi/controller/ArticleControllerV2.scala index fb8202da37..923eefca79 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/controller/ArticleControllerV2.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/controller/ArticleControllerV2.scala @@ -92,7 +92,7 @@ trait ArticleControllerV2 { private case class SummaryWithHeader( @jsonbody - body: SearchResultV2, + body: SearchResultV2DTO, @header("search-context") searchContext: Option[String] ) @@ -106,8 +106,8 @@ trait ArticleControllerV2 { * A Try with scroll result, or the return of the orFunction (Usually a try with a search result). */ private def scrollSearchOr(scrollId: Option[String], language: String)( - orFunction: => Try[(SearchResultV2, DynamicHeaders)] - ): Try[(SearchResultV2, DynamicHeaders)] = + orFunction: => Try[(SearchResultV2DTO, DynamicHeaders)] + ): Try[(SearchResultV2DTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => articleSearchService.scroll(scroll, language) match { @@ -129,7 +129,7 @@ trait ArticleControllerV2 { .in(pageSize) .in(pageNo) .in(language) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .errorOut(errorOutputsFor()) .serverLogicPure { case (query, pageSize, pageNo, language) => val queryOrEmpty = query.getOrElse("") @@ -165,7 +165,7 @@ trait ArticleControllerV2 { grepCodes: Seq[String], shouldScroll: Boolean, feideToken: Option[String] - ): Try[(SearchResultV2, DynamicHeaders)] = { + ): Try[(SearchResultV2DTO, DynamicHeaders)] = { val result = readService.search( query, sort, @@ -207,7 +207,7 @@ trait ArticleControllerV2 { .in(fallback) .in(scrollId) .in(grepCodes) - .out(jsonBody[SearchResultV2]) + .out(jsonBody[SearchResultV2DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor()) .serverLogicPure { @@ -260,7 +260,7 @@ trait ArticleControllerV2 { .in(pageSize) .in(pageNo) .errorOut(errorOutputsFor()) - .out(jsonBody[Seq[ArticleV2]]) + .out(jsonBody[Seq[ArticleV2DTO]]) .serverLogicPure { case (feideToken, ids, fallback, language, mbPageSize, mbPageNo) => val pageSize = mbPageSize.getOrElse(props.DefaultPageSize) match { @@ -288,9 +288,9 @@ trait ArticleControllerV2 { .summary("Find published articles.") .description("Search all articles.") .in(feideHeader) - .in(jsonBody[ArticleSearchParams]) + .in(jsonBody[ArticleSearchParamsDTO]) .errorOut(errorOutputsFor()) - .out(jsonBody[SearchResultV2]) + .out(jsonBody[SearchResultV2DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .serverLogicPure { case (feideToken, searchParams) => val language = searchParams.language.getOrElse(AllLanguages) @@ -331,7 +331,7 @@ trait ArticleControllerV2 { .in(language) .in(fallback) .errorOut(errorOutputsFor(410)) - .out(jsonBody[ArticleV2]) + .out(jsonBody[ArticleV2DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .serverLogicPure { params => val (articleId, revisionQuery, feideToken, language, fallback) = params @@ -361,7 +361,7 @@ trait ArticleControllerV2 { .in("external_id") .in(deprecatedNodeId) .errorOut(errorOutputsFor(404, 500)) - .out(jsonBody[ArticleIdV2]) + .out(jsonBody[ArticleIdV2DTO]) .serverLogicPure(externalId => { readService.getInternalIdByExternalId(externalId) match { case Some(id) => Right(id) @@ -377,7 +377,7 @@ trait ArticleControllerV2 { .in("external_ids") .in(deprecatedNodeId) .errorOut(errorOutputsFor(404, 500)) - .out(jsonBody[api.ArticleIds]) + .out(jsonBody[api.ArticleIdsDTO]) .serverLogicPure(externalId => { readService.getArticleIdsByExternalId(externalId) match { case Some(idObject) => Right(idObject) diff --git a/article-api/src/main/scala/no/ndla/articleapi/controller/InternController.scala b/article-api/src/main/scala/no/ndla/articleapi/controller/InternController.scala index 19862a9a46..1ca3222fca 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/controller/InternController.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/controller/InternController.scala @@ -120,7 +120,7 @@ trait InternController { .in(query[Int]("page-size").default(250)) .in(query[String]("language").default(Language.AllLanguages)) .in(query[Boolean]("fallback").default(false)) - .out(jsonBody[ArticleDump]) + .out(jsonBody[ArticleDumpDTO]) .serverLogicPure { case (pageNo, pageSize, language, fallback) => readService.getArticlesByPage(pageNo, pageSize, language, fallback).asRight } @@ -129,7 +129,7 @@ trait InternController { .in("dump" / "article") .in(query[Int]("page").default(1)) .in(query[Int]("page-size").default(250)) - .out(jsonBody[ArticleDomainDump]) + .out(jsonBody[ArticleDomainDumpDTO]) .serverLogicPure { case (pageNo, pageSize) => readService.getArticleDomainDump(pageNo, pageSize).asRight } @@ -182,7 +182,7 @@ trait InternController { .in("article" / path[Long]("id")) .in(query[Option[Int]]("revision")) .errorOut(errorOutputsFor(401, 403, 404)) - .out(jsonBody[ArticleIdV2]) + .out(jsonBody[ArticleIdV2DTO]) .requirePermission(ARTICLE_API_WRITE) .serverLogicPure { _ => params => val (id, revision) = params @@ -193,7 +193,7 @@ trait InternController { .in("article" / path[Long]("id") / "unpublish") .in(query[Option[Int]]("revision")) .errorOut(errorOutputsFor(401, 403, 404)) - .out(jsonBody[ArticleIdV2]) + .out(jsonBody[ArticleIdV2DTO]) .requirePermission(ARTICLE_API_WRITE) .serverLogicPure { _ => params => val (id, revision) = params @@ -202,11 +202,11 @@ trait InternController { def partialPublishArticle: ServerEndpoint[Any, Eff] = endpoint.patch .in("partial-publish" / path[Long]("article_id")) - .in(jsonBody[PartialPublishArticle]) + .in(jsonBody[PartialPublishArticleDTO]) .in(query[String]("language").default(Language.AllLanguages)) .in(query[Boolean]("fallback").default(false)) .errorOut(errorOutputsFor(401, 403, 404)) - .out(jsonBody[ArticleV2]) + .out(jsonBody[ArticleV2DTO]) .requirePermission(ARTICLE_API_WRITE) .serverLogicPure { _ => params => val (articleId, partialUpdateBody, language, fallback) = params diff --git a/article-api/src/main/scala/no/ndla/articleapi/integration/FrontpageApiClient.scala b/article-api/src/main/scala/no/ndla/articleapi/integration/FrontpageApiClient.scala index 48839f0b4e..4d2b9fa6f5 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/integration/FrontpageApiClient.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/integration/FrontpageApiClient.scala @@ -10,7 +10,7 @@ package no.ndla.articleapi.integration import com.typesafe.scalalogging.StrictLogging import no.ndla.articleapi.Props import no.ndla.articleapi.service.ConverterService -import no.ndla.common.model.api.FrontPage +import no.ndla.common.model.api.FrontPageDTO import no.ndla.network.NdlaClient import sttp.client3.quick.* @@ -24,9 +24,9 @@ trait FrontpageApiClient { private val frontpageApiBaseUrl = s"$FrontpageApiBaseUrl/frontpage-api/v1/frontpage" - def getFrontpage: Try[FrontPage] = { + def getFrontpage: Try[FrontPageDTO] = { val req = quickRequest.get(uri"$frontpageApiBaseUrl") - ndlaClient.fetch[FrontPage](req) + ndlaClient.fetch[FrontPageDTO](req) } } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2DTO.scala similarity index 71% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2DTO.scala index dd39dbe74c..aadc5c99c0 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleContentV2DTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("The content of the article in the specified language") -case class ArticleContentV2( +case class ArticleContentV2DTO( @description("The html content") content: String, @description("ISO 639-1 code that represents the language used in the content") language: String ) -object ArticleContentV2 { - implicit val encoder: Encoder[ArticleContentV2] = deriveEncoder - implicit val decoder: Decoder[ArticleContentV2] = deriveDecoder +object ArticleContentV2DTO { + implicit val encoder: Encoder[ArticleContentV2DTO] = deriveEncoder + implicit val decoder: Decoder[ArticleContentV2DTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDump.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDumpDTO.scala similarity index 94% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDump.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDumpDTO.scala index 479702b594..0bc7bec81a 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDump.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleDomainDumpDTO.scala @@ -11,7 +11,7 @@ import no.ndla.common.model.domain.article.Article import sttp.tapir.Schema.annotations.description @description("Information about articles") -case class ArticleDomainDump( +case class ArticleDomainDumpDTO( @description("The total number of articles in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2DTO.scala similarity index 72% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2DTO.scala index 347effd03c..8002db0424 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdV2DTO.scala @@ -11,4 +11,4 @@ package no.ndla.articleapi.model.api import sttp.tapir.Schema.annotations.description @description("Id for a single Article") -case class ArticleIdV2(@description("The unique id of the article") id: Long) +case class ArticleIdV2DTO(@description("The unique id of the article") id: Long) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIds.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdsDTO.scala similarity index 63% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIds.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdsDTO.scala index 10ad2a7885..507f5b1594 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIds.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIdsDTO.scala @@ -7,4 +7,4 @@ package no.ndla.articleapi.model.api -case class ArticleIds(articleId: Long, externalIds: List[String]) +case class ArticleIdsDTO(articleId: Long, externalIds: List[String]) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroduction.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroductionDTO.scala similarity index 74% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroduction.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroductionDTO.scala index 5a2a38ebc6..633724db1b 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroduction.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleIntroductionDTO.scala @@ -13,7 +13,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of the article introduction") -case class ArticleIntroduction( +case class ArticleIntroductionDTO( @description("The introduction content") introduction: String, @description("The html-version introduction content") htmlIntroduction: String, @description( @@ -21,7 +21,7 @@ case class ArticleIntroduction( ) language: String ) -object ArticleIntroduction { - implicit val encoder: Encoder[ArticleIntroduction] = deriveEncoder - implicit val decoder: Decoder[ArticleIntroduction] = deriveDecoder +object ArticleIntroductionDTO { + implicit val encoder: Encoder[ArticleIntroductionDTO] = deriveEncoder + implicit val decoder: Decoder[ArticleIntroductionDTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescription.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescriptionDTO.scala similarity index 64% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescription.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescriptionDTO.scala index f7a0ae6aa6..b3d86bc1f6 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescription.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaDescriptionDTO.scala @@ -13,14 +13,14 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta description of the article") -case class ArticleMetaDescription( +case class ArticleMetaDescriptionDTO( @description("The meta description") metaDescription: String, @description( "The ISO 639-1 language code describing which article translation this meta description belongs to" ) language: String ) -object ArticleMetaDescription { - implicit val encoder: Encoder.AsObject[ArticleMetaDescription] = deriveEncoder[ArticleMetaDescription] - implicit val decoder: Decoder[ArticleMetaDescription] = deriveDecoder[ArticleMetaDescription] +object ArticleMetaDescriptionDTO { + implicit val encoder: Encoder.AsObject[ArticleMetaDescriptionDTO] = deriveEncoder[ArticleMetaDescriptionDTO] + implicit val decoder: Decoder[ArticleMetaDescriptionDTO] = deriveDecoder[ArticleMetaDescriptionDTO] } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImage.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImageDTO.scala similarity index 74% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImage.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImageDTO.scala index 94ceb7f133..11af2af4fb 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImage.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleMetaImageDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta description of the article") -case class ArticleMetaImage( +case class ArticleMetaImageDTO( @description("The meta image url") url: String, @description("The alt text for the meta image") alt: String, @description( @@ -20,7 +20,7 @@ case class ArticleMetaImage( ) language: String ) -object ArticleMetaImage { - implicit val encoder: Encoder[ArticleMetaImage] = deriveEncoder - implicit val decoder: Decoder[ArticleMetaImage] = deriveDecoder +object ArticleMetaImageDTO { + implicit val encoder: Encoder[ArticleMetaImageDTO] = deriveEncoder + implicit val decoder: Decoder[ArticleMetaImageDTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParams.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParamsDTO.scala similarity index 97% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParams.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParamsDTO.scala index 3feb287c43..a441a822c4 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParams.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSearchParamsDTO.scala @@ -12,7 +12,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class ArticleSearchParams( +case class ArticleSearchParamsDTO( @description("The search query") query: Option[String], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], @description("Return only articles with provided license.") license: Option[String], diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2.scala deleted file mode 100644 index 53145cf224..0000000000 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Part of NDLA article-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.articleapi.model.api - -import no.ndla.common.model.NDLADate -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Short summary of information about the article") -case class ArticleSummaryV2( - @description("The unique id of the article") id: Long, - @description("The title of the article") title: ArticleTitle, - @description("A visual element article") visualElement: Option[VisualElement], - @description("An introduction for the article") introduction: Option[ArticleIntroduction], - @description("A metaDescription for the article") metaDescription: Option[ArticleMetaDescription], - @description("A meta image for the article") metaImage: Option[ArticleMetaImage], - @description("The full url to where the complete information about the article can be found") url: String, - @description("Describes the license of the article") license: String, - @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: String, - @description("The time when the article was last updated") lastUpdated: NDLADate, - @description("A list of available languages for this article") supportedLanguages: Seq[String], - @description("A list of codes from GREP API attached to this article") grepCodes: Seq[String], - @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: String, -) -// format: on diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2DTO.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2DTO.scala new file mode 100644 index 0000000000..c6f5874050 --- /dev/null +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleSummaryV2DTO.scala @@ -0,0 +1,42 @@ +/* + * Part of NDLA article-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.articleapi.model.api + +import no.ndla.common.model.NDLADate +import sttp.tapir.Schema.annotations.description + +@description("Short summary of information about the article") +case class ArticleSummaryV2DTO( + @description("The unique id of the article") + id: Long, + @description("The title of the article") + title: ArticleTitleDTO, + @description("A visual element article") + visualElement: Option[VisualElementDTO], + @description("An introduction for the article") + introduction: Option[ArticleIntroductionDTO], + @description("A metaDescription for the article") + metaDescription: Option[ArticleMetaDescriptionDTO], + @description("A meta image for the article") + metaImage: Option[ArticleMetaImageDTO], + @description("The full url to where the complete information about the article can be found") + url: String, + @description("Describes the license of the article") + license: String, + @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") + articleType: String, + @description("The time when the article was last updated") + lastUpdated: NDLADate, + @description("A list of available languages for this article") + supportedLanguages: Seq[String], + @description("A list of codes from GREP API attached to this article") + grepCodes: Seq[String], + @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") + availability: String +) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTag.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTagDTO.scala similarity index 68% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTag.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTagDTO.scala index 293cf67d0d..e324de3e13 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTag.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTagDTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of the tags of the article") -case class ArticleTag( +case class ArticleTagDTO( @description("The searchable tag.") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) -object ArticleTag { - implicit val encoder: Encoder.AsObject[ArticleTag] = deriveEncoder[ArticleTag] - implicit val decoder: Decoder[ArticleTag] = deriveDecoder[ArticleTag] +object ArticleTagDTO { + implicit val encoder: Encoder.AsObject[ArticleTagDTO] = deriveEncoder[ArticleTagDTO] + implicit val decoder: Decoder[ArticleTagDTO] = deriveDecoder[ArticleTagDTO] } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitle.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitleDTO.scala similarity index 75% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitle.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitleDTO.scala index 22df4ce711..92c69371c7 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitle.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleTitleDTO.scala @@ -13,13 +13,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of a title") -case class ArticleTitle( +case class ArticleTitleDTO( @description("The freetext title of the article") title: String, @description("The freetext html-version title of the article") htmlTitle: String, @description("ISO 639-1 code that represents the language used in title") language: String ) -object ArticleTitle { - implicit val encoder: Encoder[ArticleTitle] = deriveEncoder - implicit val decoder: Decoder[ArticleTitle] = deriveDecoder +object ArticleTitleDTO { + implicit val encoder: Encoder[ArticleTitleDTO] = deriveEncoder + implicit val decoder: Decoder[ArticleTitleDTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2.scala deleted file mode 100644 index d2abdde4f9..0000000000 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Part of NDLA article-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.articleapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.implicits.* -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.{Copyright, RelatedContent, RelatedContentLink} -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Information about the article") -case class ArticleV2( - @description("The unique id of the article") id: Long, - @description("Link to article on old platform") oldNdlaUrl: Option[String], - @description("The revision number for the article") revision: Int, - @description("Available titles for the article") title: ArticleTitle, - @description("The content of the article in available languages") content: ArticleContentV2, - @description("Describes the copyright information for the article") copyright: Copyright, - @description("Searchable tags for the article") tags: ArticleTag, - @description("Required libraries in order to render the article") requiredLibraries: Seq[RequiredLibrary], - @description("A visual element article") visualElement: Option[VisualElement], - @description("A meta image for the article") metaImage: Option[ArticleMetaImage], - @description("An introduction for the article") introduction: Option[ArticleIntroduction], - @description("Meta description for the article") metaDescription: ArticleMetaDescription, - @description("When the article was created") created: NDLADate, - @description("When the article was last updated") updated: NDLADate, - @description("By whom the article was last updated") updatedBy: String, - @description("When the article was last published") published: NDLADate, - @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: String, - @description("The languages this article supports") supportedLanguages: Seq[String], - @description("A list of codes from GREP API connected to the article") grepCodes: Seq[String], - @description("A list of conceptIds connected to the article") conceptIds: Seq[Long], - @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: String, - @description("A list of content related to the article") relatedContent: Seq[RelatedContent], - @description("The date for the next planned revision which indicates when the article might be outdated") revisionDate: Option[NDLADate], - @description("The path to the frontpage article") slug: Option[String], -) -// format: on - -object ArticleV2 { - implicit def eitherEnc: Encoder[Either[RelatedContentLink, Long]] = eitherEncoder[RelatedContentLink, Long] - implicit def eitherDec: Decoder[Either[RelatedContentLink, Long]] = eitherDecoder[RelatedContentLink, Long] - implicit val encoder: Encoder[ArticleV2] = deriveEncoder - implicit val decoder: Decoder[ArticleV2] = deriveDecoder -} diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2DTO.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2DTO.scala new file mode 100644 index 0000000000..d02bae193d --- /dev/null +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/ArticleV2DTO.scala @@ -0,0 +1,75 @@ +/* + * Part of NDLA article-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.articleapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.implicits.* +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.{CopyrightDTO, RelatedContent, RelatedContentLinkDTO} +import sttp.tapir.Schema.annotations.description + +@description("Information about the article") +case class ArticleV2DTO( + @description("The unique id of the article") + id: Long, + @description("Link to article on old platform") + oldNdlaUrl: Option[String], + @description("The revision number for the article") + revision: Int, + @description("Available titles for the article") + title: ArticleTitleDTO, + @description("The content of the article in available languages") + content: ArticleContentV2DTO, + @description("Describes the copyright information for the article") + copyright: CopyrightDTO, + @description("Searchable tags for the article") + tags: ArticleTagDTO, + @description("Required libraries in order to render the article") + requiredLibraries: Seq[RequiredLibraryDTO], + @description("A visual element article") + visualElement: Option[VisualElementDTO], + @description("A meta image for the article") + metaImage: Option[ArticleMetaImageDTO], + @description("An introduction for the article") + introduction: Option[ArticleIntroductionDTO], + @description("Meta description for the article") + metaDescription: ArticleMetaDescriptionDTO, + @description("When the article was created") + created: NDLADate, + @description("When the article was last updated") + updated: NDLADate, + @description("By whom the article was last updated") + updatedBy: String, + @description("When the article was last published") + published: NDLADate, + @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") + articleType: String, + @description("The languages this article supports") + supportedLanguages: Seq[String], + @description("A list of codes from GREP API connected to the article") + grepCodes: Seq[String], + @description("A list of conceptIds connected to the article") + conceptIds: Seq[Long], + @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") + availability: String, + @description("A list of content related to the article") + relatedContent: Seq[RelatedContent], + @description("The date for the next planned revision which indicates when the article might be outdated") + revisionDate: Option[NDLADate], + @description("The path to the frontpage article") + slug: Option[String] +) + +object ArticleV2DTO { + implicit def eitherEnc: Encoder[Either[RelatedContentLinkDTO, Long]] = eitherEncoder[RelatedContentLinkDTO, Long] + implicit def eitherDec: Decoder[Either[RelatedContentLinkDTO, Long]] = eitherDecoder[RelatedContentLinkDTO, Long] + implicit val encoder: Encoder[ArticleV2DTO] = deriveEncoder + implicit val decoder: Decoder[ArticleV2DTO] = deriveDecoder +} diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/NewArticleMetaImage.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/NewArticleMetaImage.scala deleted file mode 100644 index bca11080bd..0000000000 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/NewArticleMetaImage.scala +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Part of NDLA article-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.articleapi.model.api -import sttp.tapir.Schema.annotations.description - -case class NewArticleMetaImage( - @description("The image-api id of the meta image") id: String, - @description("The alt text of the meta image") alt: String -) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticle.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticle.scala deleted file mode 100644 index 938d7bdf30..0000000000 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticle.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Part of NDLA article-api - * Copyright (C) 2020 NDLA - * - * See LICENSE - * - */ - -package no.ndla.articleapi.model.api - -import io.circe.generic.semiauto.* -import io.circe.{Decoder, Encoder} -import no.ndla.common.implicits.{eitherDecoder, eitherEncoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.{RelatedContent, RelatedContentLink, UpdateOrDelete} -import no.ndla.common.model.domain.Availability -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Partial data about article to publish independently") -case class PartialPublishArticle( - @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: Option[Availability], - @description("A list of codes from GREP API connected to the article") grepCodes: Option[Seq[String]], - @description("The name of the license") license: Option[String], - @description("A list of meta description objects") metaDescription: Option[Seq[ArticleMetaDescription]], - @description("A list of content related to the article") relatedContent: Option[Seq[RelatedContent]], - @description("A list of tag objects") tags: Option[Seq[ArticleTag]], - @description("A revision date to specify expected earliest revision date of the article") revisionDate: UpdateOrDelete[NDLADate], - @description("A date to specify published date of the article") published: Option[NDLADate], -) - -object PartialPublishArticle { - implicit val relatedContentLinkEnc: Encoder.AsObject[RelatedContentLink] = deriveEncoder[RelatedContentLink] - implicit val relatedContentLinkDec: Decoder[RelatedContentLink] = deriveDecoder[RelatedContentLink] - implicit def eitherEnc: Encoder[Either[RelatedContentLink, Long]] = eitherEncoder[RelatedContentLink, Long] - implicit def eitherDec: Decoder[Either[RelatedContentLink, Long]] = eitherDecoder[RelatedContentLink, Long] - implicit val encoder: Encoder.AsObject[PartialPublishArticle] = UpdateOrDelete.filterMarkers(deriveEncoder[PartialPublishArticle]) - implicit val decoder: Decoder[PartialPublishArticle] = deriveDecoder[PartialPublishArticle] -} diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticleDTO.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticleDTO.scala new file mode 100644 index 0000000000..68e0b451a2 --- /dev/null +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/PartialPublishArticleDTO.scala @@ -0,0 +1,39 @@ +/* + * Part of NDLA article-api + * Copyright (C) 2020 NDLA + * + * See LICENSE + * + */ + +package no.ndla.articleapi.model.api + +import io.circe.generic.semiauto.* +import io.circe.{Decoder, Encoder} +import no.ndla.common.implicits.{eitherDecoder, eitherEncoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.{RelatedContent, RelatedContentLinkDTO, UpdateOrDelete} +import no.ndla.common.model.domain.Availability +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Partial data about article to publish independently") +case class PartialPublishArticleDTO( + @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: Option[Availability], + @description("A list of codes from GREP API connected to the article") grepCodes: Option[Seq[String]], + @description("The name of the license") license: Option[String], + @description("A list of meta description objects") metaDescription: Option[Seq[ArticleMetaDescriptionDTO]], + @description("A list of content related to the article") relatedContent: Option[Seq[RelatedContent]], + @description("A list of tag objects") tags: Option[Seq[ArticleTagDTO]], + @description("A revision date to specify expected earliest revision date of the article") revisionDate: UpdateOrDelete[NDLADate], + @description("A date to specify published date of the article") published: Option[NDLADate], +) + +object PartialPublishArticleDTO { + implicit val relatedContentLinkEnc: Encoder.AsObject[RelatedContentLinkDTO] = deriveEncoder[RelatedContentLinkDTO] + implicit val relatedContentLinkDec: Decoder[RelatedContentLinkDTO] = deriveDecoder[RelatedContentLinkDTO] + implicit def eitherEnc: Encoder[Either[RelatedContentLinkDTO, Long]] = eitherEncoder[RelatedContentLinkDTO, Long] + implicit def eitherDec: Decoder[Either[RelatedContentLinkDTO, Long]] = eitherDecoder[RelatedContentLinkDTO, Long] + implicit val encoder: Encoder.AsObject[PartialPublishArticleDTO] = UpdateOrDelete.filterMarkers(deriveEncoder[PartialPublishArticleDTO]) + implicit val decoder: Decoder[PartialPublishArticleDTO] = deriveDecoder[PartialPublishArticleDTO] +} diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibrary.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibraryDTO.scala similarity index 74% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibrary.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibraryDTO.scala index 86a9d25d3f..d1fe6fd1aa 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibrary.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/RequiredLibraryDTO.scala @@ -13,13 +13,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a library required to render the article") -case class RequiredLibrary( +case class RequiredLibraryDTO( @description("The type of the library. E.g. CSS or JavaScript") mediaType: String, @description("The name of the library") name: String, @description("The full url to where the library can be downloaded") url: String ) -object RequiredLibrary { - implicit val encoder: Encoder[RequiredLibrary] = deriveEncoder - implicit val decoder: Decoder[RequiredLibrary] = deriveDecoder +object RequiredLibraryDTO { + implicit val encoder: Encoder[RequiredLibraryDTO] = deriveEncoder + implicit val decoder: Decoder[RequiredLibraryDTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/SearchResult.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/SearchResult.scala index f8e0ad4774..d4dea7e9bf 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/SearchResult.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/SearchResult.scala @@ -11,16 +11,16 @@ package no.ndla.articleapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class SearchResultV2( +case class SearchResultV2DTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ArticleSummaryV2] + @description("The search results") results: Seq[ArticleSummaryV2DTO] ) @description("Information about tags-search-results") -case class TagsSearchResult( +case class TagsSearchResultDTO( @description("The total number of tags matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @@ -29,10 +29,10 @@ case class TagsSearchResult( ) @description("Information about articles") -case class ArticleDump( +case class ArticleDumpDTO( @description("The total number of articles in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ArticleV2] + @description("The search results") results: Seq[ArticleV2DTO] ) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/TSTypes.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/TSTypes.scala index dbdcfe2427..80b262869d 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/TSTypes.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/TSTypes.scala @@ -2,12 +2,12 @@ package no.ndla.articleapi.model.api import com.scalatsi.TypescriptType.TSNull import com.scalatsi.* -import no.ndla.common.model.api.RelatedContentLink +import no.ndla.common.model.api.RelatedContentLinkDTO object TSTypes { implicit val nullAlias: TSNamedType[Null] = TSType.alias[Null]("NullAlias", TSNull) // https://github.com/scala-tsi/scala-tsi/issues/172 // Type-aliases referencing generics does not work without this in scala-tsi. See: https://github.com/scala-tsi/scala-tsi/issues/184 - implicit val relatedContent: TSIType[RelatedContentLink] = TSType.fromCaseClass[RelatedContentLink] + implicit val relatedContent: TSIType[RelatedContentLinkDTO] = TSType.fromCaseClass[RelatedContentLinkDTO] } diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/ValidationError.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/ValidationError.scala deleted file mode 100644 index acd1aa52b5..0000000000 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/ValidationError.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Part of NDLA article-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - * - */ - -package no.ndla.articleapi.model.api - -import no.ndla.common.errors.ValidationMessage -import sttp.tapir.Schema.annotations.description - -import java.time.LocalDateTime - -@description("Information about validation errors") -case class ValidationError( - @description("Code stating the type of error") code: String, - @description("Description of the error") description: String, - @description("List of validation messages") messages: Seq[ValidationMessage], - @description("When the error occurred") occuredAt: LocalDateTime = LocalDateTime.now() -) diff --git a/article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElement.scala b/article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElementDTO.scala similarity index 76% rename from article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElement.scala rename to article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElementDTO.scala index aa0eec8074..7b7b9f576d 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElement.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/model/api/VisualElementDTO.scala @@ -13,7 +13,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of a visual element") -case class VisualElement( +case class VisualElementDTO( @description( "Html containing the visual element. May contain any legal html element, including the embed-tag" ) visualElement: String, @@ -22,7 +22,7 @@ case class VisualElement( ) language: String ) -object VisualElement { - implicit val encoder: Encoder[VisualElement] = deriveEncoder - implicit val decoder: Decoder[VisualElement] = deriveDecoder +object VisualElementDTO { + implicit val encoder: Encoder[VisualElementDTO] = deriveEncoder + implicit val decoder: Decoder[VisualElementDTO] = deriveDecoder } diff --git a/article-api/src/main/scala/no/ndla/articleapi/service/ConverterService.scala b/article-api/src/main/scala/no/ndla/articleapi/service/ConverterService.scala index 1a2d7ccd03..306d3024db 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/service/ConverterService.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/service/ConverterService.scala @@ -11,7 +11,7 @@ package no.ndla.articleapi.service import com.sksamuel.elastic4s.requests.searches.SearchHit import com.typesafe.scalalogging.StrictLogging import no.ndla.articleapi.Props -import no.ndla.articleapi.model.api.{ArticleSummaryV2, ImportException, NotFoundException, PartialPublishArticle} +import no.ndla.articleapi.model.api.{ArticleSummaryV2DTO, ImportException, NotFoundException, PartialPublishArticleDTO} import no.ndla.articleapi.model.domain.* import no.ndla.articleapi.model.search.SearchableArticle import no.ndla.articleapi.model.api @@ -19,7 +19,7 @@ import no.ndla.articleapi.repository.ArticleRepository import no.ndla.common import no.ndla.common.{CirceUtil, Clock, model} import no.ndla.common.model.{RelatedContentLink, api as commonApi} -import no.ndla.common.model.api.{Delete, License, Missing, UpdateWith} +import no.ndla.common.model.api.{Delete, LicenseDTO, Missing, UpdateWith} import no.ndla.common.model.domain.{ ArticleContent, ArticleMetaImage, @@ -90,7 +90,7 @@ trait ConverterService { * @return * Article summary extracted from hitString in specified language. */ - def hitAsArticleSummaryV2(hitString: String, language: String): ArticleSummaryV2 = { + def hitAsArticleSummaryV2(hitString: String, language: String): ArticleSummaryV2DTO = { val searchableArticle = CirceUtil.unsafeParseAs[SearchableArticle](hitString) val titles = searchableArticle.title.languageValues.map(lv => Title(lv.value, lv.language)) @@ -107,7 +107,7 @@ trait ConverterService { val title = findByLanguageOrBestEffort(titles, language) .map(toApiArticleTitle) - .getOrElse(api.ArticleTitle("", "", UnknownLanguage.toString)) + .getOrElse(api.ArticleTitleDTO("", "", UnknownLanguage.toString)) val visualElement = findByLanguageOrBestEffort(visualElements, language).map(toApiVisualElement) val introduction = findByLanguageOrBestEffort(introductions, language).map(toApiArticleIntroduction) val metaDescription = findByLanguageOrBestEffort(metaDescriptions, language).map(toApiArticleMetaDescription) @@ -115,7 +115,7 @@ trait ConverterService { val lastUpdated = searchableArticle.lastUpdated val availability = searchableArticle.availability - ArticleSummaryV2( + ArticleSummaryV2DTO( searchableArticle.id, title, visualElement, @@ -157,7 +157,7 @@ trait ConverterService { newMetaDescriptions ++ metaDescToKeep } - def updateArticleFields(existingArticle: Article, partialArticle: PartialPublishArticle): Article = { + def updateArticleFields(existingArticle: Article, partialArticle: PartialPublishArticleDTO): Article = { val newAvailability = partialArticle.availability.getOrElse(existingArticle.availability) val newGrepCodes = partialArticle.grepCodes.getOrElse(existingArticle.grepCodes) val newLicense = partialArticle.license.getOrElse(existingArticle.copyright.license) @@ -204,7 +204,7 @@ trait ConverterService { } } - def toDomainCopyright(copyright: model.api.Copyright): Copyright = { + def toDomainCopyright(copyright: model.api.CopyrightDTO): Copyright = { Copyright( copyright.license.license, copyright.origin, @@ -238,30 +238,30 @@ trait ConverterService { article: Article, language: String, fallback: Boolean - ): Try[api.ArticleV2] = { + ): Try[api.ArticleV2DTO] = { val supportedLanguages = getSupportedArticleLanguages(article) val isLanguageNeutral = supportedLanguages.contains(UnknownLanguage.toString) && supportedLanguages.length == 1 if (supportedLanguages.contains(language) || language == AllLanguages || isLanguageNeutral || fallback) { val meta = findByLanguageOrBestEffort(article.metaDescription, language) .map(toApiArticleMetaDescription) - .getOrElse(api.ArticleMetaDescription("", UnknownLanguage.toString)) + .getOrElse(api.ArticleMetaDescriptionDTO("", UnknownLanguage.toString)) val tags = findByLanguageOrBestEffort(article.tags, language) .map(toApiArticleTag) - .getOrElse(api.ArticleTag(Seq(), UnknownLanguage.toString)) + .getOrElse(api.ArticleTagDTO(Seq(), UnknownLanguage.toString)) val title = findByLanguageOrBestEffort(article.title, language) .map(toApiArticleTitle) - .getOrElse(api.ArticleTitle("", "", UnknownLanguage.toString)) + .getOrElse(api.ArticleTitleDTO("", "", UnknownLanguage.toString)) val introduction = findByLanguageOrBestEffort(article.introduction, language).map(toApiArticleIntroduction) val visualElement = findByLanguageOrBestEffort(article.visualElement, language).map(toApiVisualElement) val articleContent = findByLanguageOrBestEffort(article.content, language) .map(toApiArticleContentV2) - .getOrElse(api.ArticleContentV2("", UnknownLanguage.toString)) + .getOrElse(api.ArticleContentV2DTO("", UnknownLanguage.toString)) val metaImage = findByLanguageOrBestEffort(article.metaImage, language).map(toApiArticleMetaImage) val copyright = toApiCopyright(article.copyright) Success( - api.ArticleV2( + api.ArticleV2DTO( article.id.get, article.id.flatMap(getMainNidUrlToOldNdla), article.revision.get, @@ -298,12 +298,12 @@ trait ConverterService { } } - def toApiArticleTitle(title: Title): api.ArticleTitle = { - api.ArticleTitle(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) + def toApiArticleTitle(title: Title): api.ArticleTitleDTO = { + api.ArticleTitleDTO(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) } - private def toApiArticleContentV2(content: ArticleContent): api.ArticleContentV2 = { - api.ArticleContentV2( + private def toApiArticleContentV2(content: ArticleContent): api.ArticleContentV2DTO = { + api.ArticleContentV2DTO( content.content, content.language ) @@ -311,14 +311,14 @@ trait ConverterService { private def toApiRelatedContent(relatedContent: RelatedContent): common.model.api.RelatedContent = { relatedContent match { - case Left(x) => Left(common.model.api.RelatedContentLink(url = x.url, title = x.title)) + case Left(x) => Left(common.model.api.RelatedContentLinkDTO(url = x.url, title = x.title)) case Right(x) => Right(x) } } - private def toApiCopyright(copyright: Copyright): commonApi.Copyright = { - commonApi.Copyright( + private def toApiCopyright(copyright: Copyright): commonApi.CopyrightDTO = { + commonApi.CopyrightDTO( toApiLicense(copyright.license), copyright.origin, copyright.creators.map(_.toApi), @@ -330,39 +330,39 @@ trait ConverterService { ) } - def toApiLicense(shortLicense: String): License = { + def toApiLicense(shortLicense: String): LicenseDTO = { getLicense(shortLicense) match { - case Some(l) => model.api.License(l.license.toString, Option(l.description), l.url) - case None => model.api.License("unknown", None, None) + case Some(l) => model.api.LicenseDTO(l.license.toString, Option(l.description), l.url) + case None => model.api.LicenseDTO("unknown", None, None) } } - private def toApiArticleTag(tag: Tag): api.ArticleTag = { - api.ArticleTag(tag.tags, tag.language) + private def toApiArticleTag(tag: Tag): api.ArticleTagDTO = { + api.ArticleTagDTO(tag.tags, tag.language) } - private def toApiRequiredLibrary(required: RequiredLibrary): api.RequiredLibrary = { - api.RequiredLibrary(required.mediaType, required.name, required.url) + private def toApiRequiredLibrary(required: RequiredLibrary): api.RequiredLibraryDTO = { + api.RequiredLibraryDTO(required.mediaType, required.name, required.url) } - private def toApiVisualElement(visual: VisualElement): api.VisualElement = { - api.VisualElement(visual.resource, visual.language) + private def toApiVisualElement(visual: VisualElement): api.VisualElementDTO = { + api.VisualElementDTO(visual.resource, visual.language) } - def toApiArticleIntroduction(intro: Introduction): api.ArticleIntroduction = { - api.ArticleIntroduction( + def toApiArticleIntroduction(intro: Introduction): api.ArticleIntroductionDTO = { + api.ArticleIntroductionDTO( Jsoup.parseBodyFragment(intro.introduction).body().text(), intro.introduction, intro.language ) } - private def toApiArticleMetaDescription(metaDescription: Description): api.ArticleMetaDescription = { - api.ArticleMetaDescription(metaDescription.content, metaDescription.language) + private def toApiArticleMetaDescription(metaDescription: Description): api.ArticleMetaDescriptionDTO = { + api.ArticleMetaDescriptionDTO(metaDescription.content, metaDescription.language) } - private def toApiArticleMetaImage(metaImage: ArticleMetaImage): api.ArticleMetaImage = { - api.ArticleMetaImage( + private def toApiArticleMetaImage(metaImage: ArticleMetaImage): api.ArticleMetaImageDTO = { + api.ArticleMetaImageDTO( s"${externalApiUrls("raw-image")}/${metaImage.imageId}", metaImage.altText, metaImage.language @@ -371,7 +371,7 @@ trait ConverterService { private def createLinkToOldNdla(nodeId: String): String = s"//red.ndla.no/node/$nodeId" - def toApiArticleIds(ids: ArticleIds): api.ArticleIds = api.ArticleIds(ids.articleId, ids.externalId) + def toApiArticleIds(ids: ArticleIds): api.ArticleIdsDTO = api.ArticleIdsDTO(ids.articleId, ids.externalId) def toApiArticleTags( tags: Seq[String], @@ -379,8 +379,8 @@ trait ConverterService { pageSize: Int, offset: Int, language: String - ): api.TagsSearchResult = { - api.TagsSearchResult(tagsCount, offset, pageSize, language, tags) + ): api.TagsSearchResultDTO = { + api.TagsSearchResultDTO(tagsCount, offset, pageSize, language, tags) } } diff --git a/article-api/src/main/scala/no/ndla/articleapi/service/ReadService.scala b/article-api/src/main/scala/no/ndla/articleapi/service/ReadService.scala index cd7f4f525a..7372fe5747 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/service/ReadService.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/service/ReadService.scala @@ -15,7 +15,7 @@ import no.ndla.articleapi.Props import no.ndla.articleapi.caching.MemoizeHelpers import no.ndla.articleapi.integration.FrontpageApiClient import no.ndla.articleapi.model.api -import no.ndla.articleapi.model.api.{ArticleSummaryV2, ErrorHandling, NotFoundException} +import no.ndla.articleapi.model.api.{ArticleSummaryV2DTO, ErrorHandling, NotFoundException} import no.ndla.articleapi.model.domain.* import no.ndla.articleapi.model.search.SearchResult import no.ndla.articleapi.repository.ArticleRepository @@ -23,7 +23,7 @@ import no.ndla.articleapi.service.search.{ArticleSearchService, SearchConverterS import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.errors.{AccessDeniedException, ValidationException} import no.ndla.common.implicits.* -import no.ndla.common.model.api.Menu +import no.ndla.common.model.api.MenuDTO import no.ndla.common.model.domain.article.Article import no.ndla.common.model.domain.{ArticleType, Availability} import no.ndla.language.Language @@ -43,8 +43,8 @@ trait ReadService { val readService: ReadService class ReadService extends StrictLogging { - def getInternalIdByExternalId(externalId: String): Option[api.ArticleIdV2] = - articleRepository.getIdFromExternalId(externalId).map(api.ArticleIdV2.apply) + def getInternalIdByExternalId(externalId: String): Option[api.ArticleIdV2DTO] = + articleRepository.getIdFromExternalId(externalId).map(api.ArticleIdV2DTO.apply) def withIdV2( id: Long, @@ -52,7 +52,7 @@ trait ReadService { fallback: Boolean, revision: Option[Int], feideAccessToken: Option[String] - ): Try[Cachable[api.ArticleV2]] = { + ): Try[Cachable[api.ArticleV2DTO]] = { val article = revision match { case Some(rev) => articleRepository.withIdAndRevision(id, rev) case None => articleRepository.withId(id) @@ -89,13 +89,13 @@ trait ReadService { slug: String, language: String, fallback: Boolean - ): Try[Cachable[api.ArticleV2]] = getDomainArticleBySlug(slug).flatMap { + ): Try[Cachable[api.ArticleV2DTO]] = getDomainArticleBySlug(slug).flatMap { case article if article.availability == Availability.everyone => - val res: Try[Cachable[api.ArticleV2]] = + val res: Try[Cachable[api.ArticleV2DTO]] = Cachable.yes(converterService.toApiArticleV2(article, language, fallback)) res case article => - val res: Try[Cachable[api.ArticleV2]] = + val res: Try[Cachable[api.ArticleV2DTO]] = Cachable.no(converterService.toApiArticleV2(article, language, fallback)) res } @@ -108,7 +108,7 @@ trait ReadService { article.copy(content = articleWithUrls, visualElement = visualElementWithUrls) } - def getAllTags(input: String, pageSize: Int, offset: Int, language: String): api.TagsSearchResult = { + def getAllTags(input: String, pageSize: Int, offset: Int, language: String): api.TagsSearchResultDTO = { val (tags, tagsCount) = articleRepository.getTags(input, pageSize, (offset - 1) * pageSize, language) converterService.toApiArticleTags(tags, tagsCount, pageSize, offset, language) } @@ -118,21 +118,21 @@ trait ReadService { pageSize: Int, lang: String, fallback: Boolean - ): api.ArticleDump = { + ): api.ArticleDumpDTO = { val (safePageNo, safePageSize) = (max(pageNo, 1), max(pageSize, 0)) val results = articleRepository .getArticlesByPage(safePageSize, (safePageNo - 1) * safePageSize) .flatMap(article => converterService.toApiArticleV2(article, lang, fallback).toOption) - api.ArticleDump(articleRepository.articleCount, pageNo, pageSize, lang, results) + api.ArticleDumpDTO(articleRepository.articleCount, pageNo, pageSize, lang, results) } - def getArticleDomainDump(pageNo: Int, pageSize: Int): api.ArticleDomainDump = { + def getArticleDomainDump(pageNo: Int, pageSize: Int): api.ArticleDomainDumpDTO = { val (safePageNo, safePageSize) = (max(pageNo, 1), max(pageSize, 0)) val results = articleRepository.getArticlesByPage(safePageSize, (safePageNo - 1) * safePageSize).map(addUrlsOnEmbedResources) - api.ArticleDomainDump(articleRepository.articleCount, pageNo, pageSize, results) + api.ArticleDomainDumpDTO(articleRepository.articleCount, pageNo, pageSize, results) } private[service] def addUrlOnResource(content: String): String = { @@ -178,7 +178,7 @@ trait ReadService { } } - def getArticleIdsByExternalId(externalId: String): Option[api.ArticleIds] = + def getArticleIdsByExternalId(externalId: String): Option[api.ArticleIdsDTO] = articleRepository.getArticleIdsFromExternalId(externalId).map(converterService.toApiArticleIds) def search( @@ -194,7 +194,7 @@ trait ReadService { grepCodes: Seq[String], shouldScroll: Boolean, feideAccessToken: Option[String] - ): Try[Cachable[SearchResult[ArticleSummaryV2]]] = { + ): Try[Cachable[SearchResult[ArticleSummaryV2DTO]]] = { val availabilities = feideApiClient.getFeideExtendedUser(feideAccessToken) match { case Success(user) => user.availabilities case Failure(_: AccessDeniedException) => @@ -267,7 +267,7 @@ trait ReadService { page: Int, pageSize: Int, feideAccessToken: Option[String] - ): Try[Seq[api.ArticleV2]] = { + ): Try[Seq[api.ArticleV2DTO]] = { if (articleIds.isEmpty) Failure(ValidationException("ids", "Query parameter 'ids' is missing")) else { val offset = (page - 1) * pageSize @@ -280,19 +280,19 @@ trait ReadService { } @tailrec - private def findArticleMenu(article: api.ArticleV2, menus: List[Menu]): Try[Menu] = { + private def findArticleMenu(article: api.ArticleV2DTO, menus: List[MenuDTO]): Try[MenuDTO] = { if (menus.isEmpty) Failure(NotFoundException(s"Could not find menu for article with id ${article.id}")) else menus.find(_.articleId == article.id) match { case Some(value) => Success(value) case None => - val submenus = menus.flatMap(m => m.menu.map { case x: Menu => x }) + val submenus = menus.flatMap(m => m.menu.map { case x: MenuDTO => x }) findArticleMenu(article, submenus) } } - private def getArticlesForRSSFeed(menu: Menu): Try[Cachable[List[api.ArticleV2]]] = { - val articleIds = menu.menu.map { case x: Menu => x.articleId } + private def getArticlesForRSSFeed(menu: MenuDTO): Try[Cachable[List[api.ArticleV2DTO]]] = { + val articleIds = menu.menu.map { case x: MenuDTO => x.articleId } val articles = articleIds.traverse(id => withIdV2(id, Language.DefaultLanguage, fallback = true, revision = None, feideAccessToken = None) @@ -300,7 +300,7 @@ trait ReadService { articles.map(Cachable.merge) } - private def toArticleItem(article: api.ArticleV2): String = { + private def toArticleItem(article: api.ArticleV2DTO): String = { s""" | ${article.title.title} | ${article.metaDescription.metaDescription} @@ -315,7 +315,7 @@ trait ReadService { .getOrElse(s"${props.ndlaFrontendUrl}/article/$id") private val allBlankLinesRegex = """(?m)^\s*$[\r\n]*""".r - private def toRSSXML(parentArticle: api.ArticleV2, articles: List[api.ArticleV2]): String = { + private def toRSSXML(parentArticle: api.ArticleV2DTO, articles: List[api.ArticleV2DTO]): String = { val rss = s""" | | diff --git a/article-api/src/main/scala/no/ndla/articleapi/service/WriteService.scala b/article-api/src/main/scala/no/ndla/articleapi/service/WriteService.scala index a249dfe889..481a67ff7e 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/service/WriteService.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/service/WriteService.scala @@ -11,7 +11,7 @@ package no.ndla.articleapi.service import com.typesafe.scalalogging.StrictLogging import no.ndla.articleapi.integration.SearchApiClient import no.ndla.articleapi.model.api -import no.ndla.articleapi.model.api.{NotFoundException, PartialPublishArticle} +import no.ndla.articleapi.model.api.{NotFoundException, PartialPublishArticleDTO} import no.ndla.articleapi.repository.ArticleRepository import no.ndla.articleapi.service.search.ArticleIndexService import no.ndla.articleapi.validation.ContentValidator @@ -70,10 +70,10 @@ trait WriteService { def partialUpdate( articleId: Long, - partialArticle: PartialPublishArticle, + partialArticle: PartialPublishArticleDTO, language: String, fallback: Boolean - ): Try[api.ArticleV2] = { + ): Try[api.ArticleV2DTO] = { articleRepository.withId(articleId).toArticle match { case None => Failure(NotFoundException(s"Could not find article with id '$articleId' to partial publish")) case Some(existingArticle) => @@ -89,7 +89,7 @@ trait WriteService { } } - def unpublishArticle(id: Long, revision: Option[Int]): Try[api.ArticleIdV2] = { + def unpublishArticle(id: Long, revision: Option[Int]): Try[api.ArticleIdV2DTO] = { val updated = revision match { case Some(rev) => articleRepository.unpublish(id, rev) case None => articleRepository.unpublishMaxRevision(id) @@ -98,10 +98,10 @@ trait WriteService { updated .flatMap(articleIndexService.deleteDocument) .map(searchApiClient.deleteArticle) - .map(api.ArticleIdV2.apply) + .map(api.ArticleIdV2DTO.apply) } - def deleteArticle(id: Long, revision: Option[Int]): Try[api.ArticleIdV2] = { + def deleteArticle(id: Long, revision: Option[Int]): Try[api.ArticleIdV2DTO] = { val deleted = revision match { case Some(rev) => articleRepository.delete(id, rev) case None => articleRepository.deleteMaxRevision(id) @@ -110,7 +110,7 @@ trait WriteService { deleted .flatMap(articleIndexService.deleteDocument) .map(searchApiClient.deleteArticle) - .map(api.ArticleIdV2.apply) + .map(api.ArticleIdV2DTO.apply) } } diff --git a/article-api/src/main/scala/no/ndla/articleapi/service/search/ArticleSearchService.scala b/article-api/src/main/scala/no/ndla/articleapi/service/search/ArticleSearchService.scala index b6de9bc8e8..bba2c4ff76 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/service/search/ArticleSearchService.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/service/search/ArticleSearchService.scala @@ -13,7 +13,7 @@ import com.sksamuel.elastic4s.requests.searches.queries.compound.BoolQuery import com.typesafe.scalalogging.StrictLogging import no.ndla.articleapi.Props import no.ndla.articleapi.model.api -import no.ndla.articleapi.model.api.{ArticleSummaryV2, ErrorHandling} +import no.ndla.articleapi.model.api.{ArticleSummaryV2DTO, ErrorHandling} import no.ndla.articleapi.model.domain.* import no.ndla.articleapi.model.search.SearchResult import no.ndla.articleapi.service.ConverterService @@ -34,16 +34,16 @@ trait ArticleSearchService { import props.* - class ArticleSearchService extends StrictLogging with SearchService[api.ArticleSummaryV2] { + class ArticleSearchService extends StrictLogging with SearchService[api.ArticleSummaryV2DTO] { private val noCopyright = boolQuery().not(termQuery("license", License.Copyrighted.toString)) override val searchIndex: String = ArticleSearchIndex - override def hitToApiModel(hit: String, language: String): api.ArticleSummaryV2 = { + override def hitToApiModel(hit: String, language: String): api.ArticleSummaryV2DTO = { converterService.hitAsArticleSummaryV2(hit, language) } - def matchingQuery(settings: SearchSettings): Try[SearchResult[ArticleSummaryV2]] = { + def matchingQuery(settings: SearchSettings): Try[SearchResult[ArticleSummaryV2DTO]] = { val fullQuery = settings.query.emptySomeToNone match { case Some(query) => val language = if (settings.fallback) "*" else settings.language @@ -70,7 +70,7 @@ trait ArticleSearchService { executeSearch(fullQuery, settings) } - def executeSearch(queryBuilder: BoolQuery, settings: SearchSettings): Try[SearchResult[ArticleSummaryV2]] = { + def executeSearch(queryBuilder: BoolQuery, settings: SearchSettings): Try[SearchResult[ArticleSummaryV2DTO]] = { val articleTypesFilter = if (settings.articleTypes.nonEmpty) Some(constantScoreQuery(termsQuery("articleType", settings.articleTypes))) @@ -138,7 +138,7 @@ trait ArticleSearchService { e4sClient.execute(searchWithScroll) match { case Success(response) => Success( - SearchResult[ArticleSummaryV2]( + SearchResult[ArticleSummaryV2DTO]( response.result.totalHits, Some(settings.page), numResults, diff --git a/article-api/src/main/scala/no/ndla/articleapi/service/search/SearchConverterService.scala b/article-api/src/main/scala/no/ndla/articleapi/service/search/SearchConverterService.scala index 6a6eea2ddb..5967331fdd 100644 --- a/article-api/src/main/scala/no/ndla/articleapi/service/search/SearchConverterService.scala +++ b/article-api/src/main/scala/no/ndla/articleapi/service/search/SearchConverterService.scala @@ -9,7 +9,7 @@ package no.ndla.articleapi.service.search import com.typesafe.scalalogging.StrictLogging -import no.ndla.articleapi.model.api.{ArticleSummaryV2, SearchResultV2} +import no.ndla.articleapi.model.api.{ArticleSummaryV2DTO, SearchResultV2DTO} import no.ndla.articleapi.model.search.* import no.ndla.articleapi.service.ConverterService import no.ndla.common.model.domain.article.Article @@ -59,8 +59,8 @@ trait SearchConverterService { ) } - def asApiSearchResultV2(searchResult: SearchResult[ArticleSummaryV2]): SearchResultV2 = - SearchResultV2( + def asApiSearchResultV2(searchResult: SearchResult[ArticleSummaryV2DTO]): SearchResultV2DTO = + SearchResultV2DTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, diff --git a/article-api/src/test/scala/no/ndla/articleapi/TestData.scala b/article-api/src/test/scala/no/ndla/articleapi/TestData.scala index aea6da220a..c7e09fd4e4 100644 --- a/article-api/src/test/scala/no/ndla/articleapi/TestData.scala +++ b/article-api/src/test/scala/no/ndla/articleapi/TestData.scala @@ -49,28 +49,28 @@ trait TestData { val (articleId, externalId) = (1L, "751234") - val sampleArticleV2: api.ArticleV2 = api.ArticleV2( + val sampleArticleV2: api.ArticleV2DTO = api.ArticleV2DTO( id = 1, oldNdlaUrl = None, revision = 1, - title = api.ArticleTitle("title", "title", "nb"), - content = api.ArticleContentV2("this is content", "nb"), - copyright = model.api.Copyright( - model.api.License("licence", None, None), + title = api.ArticleTitleDTO("title", "title", "nb"), + content = api.ArticleContentV2DTO("this is content", "nb"), + copyright = model.api.CopyrightDTO( + model.api.LicenseDTO("licence", None, None), Some("origin"), - Seq(model.api.Author("developer", "Per")), + Seq(model.api.AuthorDTO("developer", "Per")), List(), List(), None, None, false ), - tags = api.ArticleTag(Seq("tag"), "nb"), - requiredLibraries = Seq(api.RequiredLibrary("JS", "JavaScript", "url")), + tags = api.ArticleTagDTO(Seq("tag"), "nb"), + requiredLibraries = Seq(api.RequiredLibraryDTO("JS", "JavaScript", "url")), visualElement = None, metaImage = None, introduction = None, - metaDescription = api.ArticleMetaDescription("metaDesc", "nb"), + metaDescription = api.ArticleMetaDescriptionDTO("metaDesc", "nb"), created = NDLADate.of(2017, 1, 1, 12, 15, 32), updated = NDLADate.of(2017, 4, 1, 12, 15, 32), updatedBy = "me", @@ -85,14 +85,14 @@ trait TestData { slug = None ) - val apiArticleV2: api.ArticleV2 = api.ArticleV2( + val apiArticleV2: api.ArticleV2DTO = api.ArticleV2DTO( articleId, Some(s"//red.ndla.no/node/$externalId"), 2, - api.ArticleTitle("title", "title", "nb"), - api.ArticleContentV2("content", "nb"), - model.api.Copyright( - model.api.License( + api.ArticleTitleDTO("title", "title", "nb"), + api.ArticleContentV2DTO("content", "nb"), + model.api.CopyrightDTO( + model.api.LicenseDTO( "CC-BY-4.0", Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -105,12 +105,12 @@ trait TestData { None, false ), - api.ArticleTag(Seq("tag"), "nb"), + api.ArticleTagDTO(Seq("tag"), "nb"), Seq(), None, - Some(api.ArticleMetaImage(s"http://api-gateway.ndla-local/image-api/raw/id/11", "alt", "nb")), + Some(api.ArticleMetaImageDTO(s"http://api-gateway.ndla-local/image-api/raw/id/11", "alt", "nb")), None, - api.ArticleMetaDescription("meta description", "nb"), + api.ArticleMetaDescriptionDTO("meta description", "nb"), today, today, "ndalId54321", @@ -242,12 +242,12 @@ trait TestData { slug = None ) - val apiArticleWithHtmlFaultV2: api.ArticleV2 = api.ArticleV2( + val apiArticleWithHtmlFaultV2: api.ArticleV2DTO = api.ArticleV2DTO( 1, None, 1, - api.ArticleTitle("test", "test", "en"), - api.ArticleContentV2( + api.ArticleTitleDTO("test", "test", "en"), + api.ArticleContentV2DTO( """
  • Det er ikke lov Ã¥ gjøre dette.

    Tekst utenfor.
  • Dette er helt ok
|
  • Det er ikke lov Ã¥ gjøre dette.

  • Dette er helt ok
|
  1. Det er ikke lov å gjøre dette.

  2. Dette er helt ok
@@ -255,13 +255,14 @@ trait TestData { """.stripMargin, "en" ), - model.api.Copyright(model.api.License("publicdomain", None, None), None, Seq(), Seq(), Seq(), None, None, false), - api.ArticleTag(Seq.empty, "en"), + model.api + .CopyrightDTO(model.api.LicenseDTO("publicdomain", None, None), None, Seq(), Seq(), Seq(), None, None, false), + api.ArticleTagDTO(Seq.empty, "en"), Seq.empty, None, None, None, - api.ArticleMetaDescription("so meta", "en"), + api.ArticleMetaDescriptionDTO("so meta", "en"), NDLADate.now().minusDays(4), NDLADate.now().minusDays(2), "ndalId54321", @@ -311,7 +312,7 @@ trait TestData { ) } - val sampleApiTagsSearchResult: api.TagsSearchResult = api.TagsSearchResult(10, 1, 1, "nb", Seq("a", "b")) + val sampleApiTagsSearchResult: api.TagsSearchResultDTO = api.TagsSearchResultDTO(10, 1, 1, "nb", Seq("a", "b")) val testSettings: SearchSettings = SearchSettings( query = None, diff --git a/article-api/src/test/scala/no/ndla/articleapi/controller/ArticleControllerV2Test.scala b/article-api/src/test/scala/no/ndla/articleapi/controller/ArticleControllerV2Test.scala index a86bf56c78..9c5c66a90d 100644 --- a/article-api/src/test/scala/no/ndla/articleapi/controller/ArticleControllerV2Test.scala +++ b/article-api/src/test/scala/no/ndla/articleapi/controller/ArticleControllerV2Test.scala @@ -127,12 +127,12 @@ class ArticleControllerV2Test extends UnitSuite with TestEnvironment with TapirC test("That scrollId is in header, and not in body") { val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = SearchResult[api.ArticleSummaryV2]( + val searchResponse = SearchResult[api.ArticleSummaryV2DTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummaryV2], + Seq.empty[api.ArticleSummaryV2DTO], Some(scrollId) ) when(readService.search(any, any, any, any, any, any, any, any, any, any, any, any)) @@ -154,12 +154,12 @@ class ArticleControllerV2Test extends UnitSuite with TestEnvironment with TapirC when(searchConverterService.asApiSearchResultV2(any)).thenCallRealMethod() val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = SearchResult[api.ArticleSummaryV2]( + val searchResponse = SearchResult[api.ArticleSummaryV2DTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummaryV2], + Seq.empty[api.ArticleSummaryV2DTO], Some(scrollId) ) @@ -180,12 +180,12 @@ class ArticleControllerV2Test extends UnitSuite with TestEnvironment with TapirC reset(articleSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = SearchResult[api.ArticleSummaryV2]( + val searchResponse = SearchResult[api.ArticleSummaryV2DTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummaryV2], + Seq.empty[api.ArticleSummaryV2DTO], Some(scrollId) ) @@ -220,7 +220,7 @@ class ArticleControllerV2Test extends UnitSuite with TestEnvironment with TapirC test("That initial search-context doesn't scroll") { reset(articleSearchService, readService) - val result = SearchResult[api.ArticleSummaryV2]( + val result = SearchResult[api.ArticleSummaryV2DTO]( totalCount = 0, page = None, pageSize = 10, diff --git a/article-api/src/test/scala/no/ndla/articleapi/service/ConverterServiceTest.scala b/article-api/src/test/scala/no/ndla/articleapi/service/ConverterServiceTest.scala index 079a219b04..2d98545977 100644 --- a/article-api/src/test/scala/no/ndla/articleapi/service/ConverterServiceTest.scala +++ b/article-api/src/test/scala/no/ndla/articleapi/service/ConverterServiceTest.scala @@ -13,7 +13,7 @@ import no.ndla.articleapi.model.api.ImportException import no.ndla.articleapi.{TestEnvironment, UnitSuite} import no.ndla.common.model import no.ndla.common.model.{NDLADate, RelatedContentLink, api as commonApi} -import no.ndla.common.model.api.{License, UpdateWith} +import no.ndla.common.model.api.{LicenseDTO, UpdateWith} import no.ndla.common.model.domain.{Author, Availability, Description, Introduction, RequiredLibrary, Tag, Title} import no.ndla.common.model.domain.article.Copyright import org.mockito.Mockito.when @@ -31,12 +31,12 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val sampleAlt = "Fotografi" test("toApiLicense defaults to unknown if the license was not found") { - service.toApiLicense("invalid") should equal(License("unknown", None, None)) + service.toApiLicense("invalid") should equal(LicenseDTO("unknown", None, None)) } test("toApiLicense converts a short license string to a license object with description and url") { service.toApiLicense("CC-BY-4.0") should equal( - model.api.License( + model.api.LicenseDTO( "CC-BY-4.0", Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -47,14 +47,18 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("toApiArticleTitle returns both title and htmlTitle") { val title = Title("Title with ukrainian word", "en") service.toApiArticleTitle(title) should equal( - api.ArticleTitle("Title with ukrainian word", "Title with ukrainian word", "en") + api.ArticleTitleDTO( + "Title with ukrainian word", + "Title with ukrainian word", + "en" + ) ) } test("toApiArticleIntroduction returns both introduction and htmlIntroduction") { val introduction = Introduction("Introduction with emphasis", "en") service.toApiArticleIntroduction(introduction) should equal( - api.ArticleIntroduction("Introduction with emphasis", "Introduction with emphasis", "en") + api.ArticleIntroductionDTO("Introduction with emphasis", "Introduction with emphasis", "en") ) } @@ -195,19 +199,19 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val revisionDate = NDLADate.now() val partialArticle = - api.PartialPublishArticle( + api.PartialPublishArticleDTO( availability = Some(Availability.teacher), grepCodes = Some(Seq("New", "grep", "codes")), license = Some("newLicense"), - metaDescription = Some(Seq(api.ArticleMetaDescription("nyDesc", "nb"))), + metaDescription = Some(Seq(api.ArticleMetaDescriptionDTO("nyDesc", "nb"))), relatedContent = Some( Seq( - Left(commonApi.RelatedContentLink("New Title", "New Url")), - Left(commonApi.RelatedContentLink("Newer Title", "Newer Url")), + Left(commonApi.RelatedContentLinkDTO("New Title", "New Url")), + Left(commonApi.RelatedContentLinkDTO("Newer Title", "Newer Url")), Right(42L) ) ), - tags = Some(Seq(api.ArticleTag(Seq("nye", "Tags"), "nb"))), + tags = Some(Seq(api.ArticleTagDTO(Seq("nye", "Tags"), "nb"))), revisionDate = UpdateWith(revisionDate), published = Some(revisionDate) ) @@ -243,23 +247,23 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val revisionDate = NDLADate.now() val partialArticle = - api.PartialPublishArticle( + api.PartialPublishArticleDTO( availability = Some(Availability.teacher), grepCodes = Some(Seq("New", "grep", "codes")), license = Some("newLicense"), metaDescription = Some( Seq( - api.ArticleMetaDescription("nyDesc", "nb"), - api.ArticleMetaDescription("newDesc", "en"), - api.ArticleMetaDescription("neuDesc", "de") + api.ArticleMetaDescriptionDTO("nyDesc", "nb"), + api.ArticleMetaDescriptionDTO("newDesc", "en"), + api.ArticleMetaDescriptionDTO("neuDesc", "de") ) ), relatedContent = Some(Seq(Right(42L), Right(420L), Right(4200L))), tags = Some( Seq( - api.ArticleTag(Seq("nye", "Tags"), "nb"), - api.ArticleTag(Seq("new", "Tagss"), "en"), - api.ArticleTag(Seq("Guten", "Tag"), "de") + api.ArticleTagDTO(Seq("nye", "Tags"), "nb"), + api.ArticleTagDTO(Seq("new", "Tagss"), "en"), + api.ArticleTagDTO(Seq("Guten", "Tag"), "de") ) ), revisionDate = UpdateWith(revisionDate), diff --git a/article-api/src/test/scala/no/ndla/articleapi/service/ReadServiceTest.scala b/article-api/src/test/scala/no/ndla/articleapi/service/ReadServiceTest.scala index 368806ef80..977091e9b8 100644 --- a/article-api/src/test/scala/no/ndla/articleapi/service/ReadServiceTest.scala +++ b/article-api/src/test/scala/no/ndla/articleapi/service/ReadServiceTest.scala @@ -9,14 +9,14 @@ package no.ndla.articleapi.service import no.ndla.articleapi.model.api -import no.ndla.articleapi.model.api.ArticleSummaryV2 +import no.ndla.articleapi.model.api.ArticleSummaryV2DTO import no.ndla.articleapi.model.domain.* import no.ndla.articleapi.model.search.SearchResult import no.ndla.articleapi.{TestEnvironment, UnitSuite} import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.errors.{AccessDeniedException, ValidationException} import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.{FrontPage, Menu} +import no.ndla.common.model.api.{FrontPageDTO, MenuDTO} import no.ndla.common.model.domain.{ ArticleContent, ArticleMetaImage, @@ -76,7 +76,7 @@ class ReadServiceTest extends UnitSuite with TestEnvironment { when(articleRepository.withId(1)).thenReturn(Some(toArticleRow(article))) when(articleRepository.getExternalIdsFromId(any[Long])(any[DBSession])).thenReturn(List("54321")) - val expectedResult: Try[Cachable[api.ArticleV2]] = Cachable.yes( + val expectedResult: Try[Cachable[api.ArticleV2DTO]] = Cachable.yes( converterService.toApiArticleV2( article .copy(content = Seq(expectedArticleContent1), visualElement = Seq(VisualElement(visualElementAfter, "nb"))), @@ -133,7 +133,7 @@ class ReadServiceTest extends UnitSuite with TestEnvironment { } test("search should use size of id-list as page-size if defined") { - val searchMock = mock[SearchResult[ArticleSummaryV2]] + val searchMock = mock[SearchResult[ArticleSummaryV2DTO]] when(articleSearchService.matchingQuery(any[SearchSettings])).thenReturn(Success(searchMock)) when(feideApiClient.getFeideExtendedUser(any)).thenReturn(Failure(new AccessDeniedException("not allowed"))) @@ -323,9 +323,9 @@ class ReadServiceTest extends UnitSuite with TestEnvironment { published = date ) - val frontPage = FrontPage( + val frontPage = FrontPageDTO( 100, - List(Menu(1, List(Menu(2, List.empty, Some(true)), Menu(3, List.empty, Some(true))), Some(false))) + List(MenuDTO(1, List(MenuDTO(2, List.empty, Some(true)), MenuDTO(3, List.empty, Some(true))), Some(false))) ) val rowOne = Some(ArticleRow(1, 1, 1, Some("some-slug"), Some(parentArticle))) diff --git a/article-api/src/test/scala/no/ndla/articleapi/service/search/ArticleSearchServiceTest.scala b/article-api/src/test/scala/no/ndla/articleapi/service/search/ArticleSearchServiceTest.scala index 3e71dda24b..1ce142cf71 100644 --- a/article-api/src/test/scala/no/ndla/articleapi/service/search/ArticleSearchServiceTest.scala +++ b/article-api/src/test/scala/no/ndla/articleapi/service/search/ArticleSearchServiceTest.scala @@ -567,7 +567,7 @@ class ArticleSearchServiceTest search.totalCount should be(1) search.results.head.metaImage should be( Some( - api.ArticleMetaImage("http://api-gateway.ndla-local/image-api/raw/id/5555", "Alt text is here friend", "nb") + api.ArticleMetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/5555", "Alt text is here friend", "nb") ) ) } diff --git a/audio-api/src/main/scala/no/ndla/audioapi/controller/AudioController.scala b/audio-api/src/main/scala/no/ndla/audioapi/controller/AudioController.scala index c4e9f01c74..b3cbaa12a6 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/controller/AudioController.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/controller/AudioController.scala @@ -135,7 +135,7 @@ trait AudioController { .summary("Find audio files") .description("Shows all the audio files in the ndla.no database. You can search it too.") .in("search") - .in(jsonBody[SearchParams]) + .in(jsonBody[SearchParamsDTO]) .out(EndpointOutput.derived[SummaryWithHeader]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { searchParams => @@ -162,7 +162,7 @@ trait AudioController { .in(pathAudioId) .in(language) .errorOut(errorOutputsFor(400, 404)) - .out(jsonBody[AudioMetaInformation]) + .out(jsonBody[AudioMetaInformationDTO]) .serverLogicPure { case (id, language) => readService.withId(id, language) match { case Some(audio) => audio.asRight @@ -175,7 +175,7 @@ trait AudioController { .in(audioIds) .in(language) .errorOut(errorOutputsFor(400, 404)) - .out(jsonBody[List[AudioMetaInformation]]) + .out(jsonBody[List[AudioMetaInformationDTO]]) .summary("Fetch audio that matches ids parameter.") .description("Fetch audios that matches ids parameter.") .serverLogicPure { case (audioIds, language) => @@ -199,7 +199,7 @@ trait AudioController { .in(pathAudioId) .in("language") .in(pathLanguage) - .out(noContentOrBodyOutput[AudioMetaInformation]) + .out(noContentOrBodyOutput[AudioMetaInformationDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { _ => input => @@ -215,7 +215,7 @@ trait AudioController { .summary("Upload a new audio file with meta information") .description("Upload a new audio file with meta data") .in(multipartBody[MetaDataAndFileForm]) - .out(jsonBody[AudioMetaInformation]) + .out(jsonBody[AudioMetaInformationDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404, 413)) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { user => formData => @@ -234,7 +234,7 @@ trait AudioController { .in(pathAudioId) .in(multipartBody[MetaDataAndOptFileForm]) .errorOut(errorOutputsFor(400, 401, 403, 404, 413)) - .out(jsonBody[AudioMetaInformation]) + .out(jsonBody[AudioMetaInformationDTO]) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { user => input => { @@ -258,7 +258,7 @@ trait AudioController { .in(pageSize) .in(pageNo) .in(language) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { case (query, ps, pn, lang) => val pageSize = ps.getOrElse(DefaultPageSize) match { @@ -295,7 +295,7 @@ trait AudioController { private case class SummaryWithHeader( @jsonbody - body: AudioSummarySearchResult, + body: AudioSummarySearchResultDTO, @header("search-context") searchContext: Option[String] ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/controller/InternController.scala b/audio-api/src/main/scala/no/ndla/audioapi/controller/InternController.scala index 6e02d48039..627e1cf9b6 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/controller/InternController.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/controller/InternController.scala @@ -12,7 +12,7 @@ import cats.implicits.* import io.circe.generic.auto.* import no.ndla.audioapi.Props import no.ndla.audioapi.model.api -import no.ndla.audioapi.model.api.{AudioMetaDomainDump, ErrorHandling, NotFoundException} +import no.ndla.audioapi.model.api.{AudioMetaDomainDumpDTO, ErrorHandling, NotFoundException} import no.ndla.audioapi.model.domain.AudioMetaInformation import no.ndla.audioapi.repository.AudioRepository import no.ndla.audioapi.service.search.{AudioIndexService, SeriesIndexService, TagIndexService} @@ -42,7 +42,7 @@ trait InternController { .in("external") .in(path[String]("external_id")) .in(query[Option[String]]("language")) - .out(jsonBody[Option[api.AudioMetaInformation]]) + .out(jsonBody[Option[api.AudioMetaInformationDTO]]) .serverLogicPure { case (externalId, language) => readService.withExternalId(externalId, language).asRight }, @@ -103,7 +103,7 @@ trait InternController { .in("dump" / "audio") .in(query[Int]("page").default(1)) .in(query[Int]("page-size").default(250)) - .out(jsonBody[AudioMetaDomainDump]) + .out(jsonBody[AudioMetaDomainDumpDTO]) .errorOut(errorOutputsFor(400, 500)) .serverLogicPure { case (pageNo, pageSize) => readService.getMetaAudioDomainDump(pageNo, pageSize).asRight diff --git a/audio-api/src/main/scala/no/ndla/audioapi/controller/SeriesController.scala b/audio-api/src/main/scala/no/ndla/audioapi/controller/SeriesController.scala index 57cbe1d30a..c8ced99009 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/controller/SeriesController.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/controller/SeriesController.scala @@ -89,7 +89,7 @@ trait SeriesController { .summary("Find series") .description("Shows all the series. Also searchable.") .in("search") - .in(jsonBody[SeriesSearchParams]) + .in(jsonBody[SeriesSearchParamsDTO]) .out(EndpointOutput.derived[SummaryWithHeader]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { searchParams => @@ -112,7 +112,7 @@ trait SeriesController { .in(pathSeriesId) .in(language) .errorOut(errorOutputsFor(400, 404)) - .out(jsonBody[Series]) + .out(jsonBody[SeriesDTO]) .serverLogicPure { case (id, language) => readService.seriesWithId(id, language) } @@ -137,7 +137,7 @@ trait SeriesController { .in(pathSeriesId) .in("language") .in(pathLanguage) - .out(noContentOrBodyOutput[Series]) + .out(noContentOrBodyOutput[SeriesDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { _ => input => @@ -152,9 +152,9 @@ trait SeriesController { def postNewSeries: ServerEndpoint[Any, Eff] = endpoint.post .summary("Create a new series with meta information") .description("Create a new series with meta information") - .in(jsonBody[NewSeries]) + .in(jsonBody[NewSeriesDTO]) .errorOut(errorOutputsFor(400, 401, 403)) - .out(statusCode(StatusCode.Created).and(jsonBody[Series])) + .out(statusCode(StatusCode.Created).and(jsonBody[SeriesDTO])) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { _ => newSeries => writeService @@ -166,8 +166,8 @@ trait SeriesController { .summary("Upload audio for a different language or update metadata for an existing audio-file") .description("Update the metadata for an existing language, or upload metadata for a new language.") .in(pathSeriesId) - .in(jsonBody[NewSeries]) - .out(jsonBody[Series]) + .in(jsonBody[NewSeriesDTO]) + .out(jsonBody[SeriesDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(AUDIO_API_WRITE) .serverLogicPure { _ => input => @@ -177,7 +177,7 @@ trait SeriesController { private case class SummaryWithHeader( @jsonbody - body: SeriesSummarySearchResult, + body: SeriesSummarySearchResultDTO, @header("search-context") searchContext: Option[String] ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/controller/multipart/MultipartInput.scala b/audio-api/src/main/scala/no/ndla/audioapi/controller/multipart/MultipartInput.scala index fd451fee86..db690c0f08 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/controller/multipart/MultipartInput.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/controller/multipart/MultipartInput.scala @@ -7,16 +7,16 @@ package no.ndla.audioapi.controller.multipart -import no.ndla.audioapi.model.api.{NewAudioMetaInformation, UpdatedAudioMetaInformation} +import no.ndla.audioapi.model.api.{NewAudioMetaInformationDTO, UpdatedAudioMetaInformationDTO} import sttp.model.Part import java.io.File case class MetaDataAndFileForm( - metadata: Part[NewAudioMetaInformation], + metadata: Part[NewAudioMetaInformationDTO], file: Part[File] ) case class MetaDataAndOptFileForm( - metadata: Part[UpdatedAudioMetaInformation], + metadata: Part[UpdatedAudioMetaInformationDTO], file: Option[Part[File]] ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Audio.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioDTO.scala similarity index 95% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Audio.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioDTO.scala index 5b5ee36877..a1712185e9 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Audio.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioDTO.scala @@ -10,7 +10,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description @description("Url and size information about the audio") -case class Audio( +case class AudioDTO( @description("The path to where the audio is located") url: String, @description("The mime type of the audio file") mimeType: String, @description("The size of the audio file") fileSize: Long, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDump.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDumpDTO.scala similarity index 94% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDump.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDumpDTO.scala index dd7a9e21ca..20f57ff0fc 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDump.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaDomainDumpDTO.scala @@ -11,7 +11,7 @@ import no.ndla.audioapi.model.domain import sttp.tapir.Schema.annotations.description @description("Information about audio meta dump") -case class AudioMetaDomainDump( +case class AudioMetaDomainDumpDTO( @description("The total number of audios in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformation.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformation.scala deleted file mode 100644 index 2d163a82c7..0000000000 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformation.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Part of NDLA audio-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.audioapi.model.api - -import com.scalatsi._ -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.Copyright -import sttp.tapir.Schema.annotations.description - -import scala.annotation.unused - -// format: off -@description("Meta information about the audio object") -case class AudioMetaInformation( - @description("The unique id of this audio") id: Long, - @description("The revision number of this audio") revision: Int, - @description("The title of the audio file") title: Title, - @description("The audio file for this language") audioFile: Audio, - @description("Copyright information for the audio files") copyright: Copyright, - @description("Tags for this audio file") tags: Tag, - @description("The languages available for this audio") supportedLanguages: Seq[String], - @description("Type of audio. 'standard', or 'podcast'.") audioType: String, - @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[PodcastMeta], - @description("Meta information about series if the audio is a podcast and a part of a series.") series: Option[Series], - @description("Manuscript for the audio") manuscript: Option[Manuscript], - @description("The time of creation for the audio-file") created: NDLADate, - @description("The time of last update for the audio-file") updated: NDLADate -) -// format: on - -object AudioMetaInformation { - implicit val audioMetaInformationTSI: TSIType[AudioMetaInformation] = { - @unused - implicit val seriesReference: TSNamedType[Series] = TSType.external[Series]("ISeries") - TSType.fromCaseClass[AudioMetaInformation] - } -} diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformationDTO.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformationDTO.scala new file mode 100644 index 0000000000..156100a50e --- /dev/null +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioMetaInformationDTO.scala @@ -0,0 +1,54 @@ +/* + * Part of NDLA audio-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.audioapi.model.api + +import com.scalatsi._ +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.CopyrightDTO +import sttp.tapir.Schema.annotations.description + +import scala.annotation.unused + +@description("Meta information about the audio object") +case class AudioMetaInformationDTO( + @description("The unique id of this audio") + id: Long, + @description("The revision number of this audio") + revision: Int, + @description("The title of the audio file") + title: TitleDTO, + @description("The audio file for this language") + audioFile: AudioDTO, + @description("Copyright information for the audio files") + copyright: CopyrightDTO, + @description("Tags for this audio file") + tags: TagDTO, + @description("The languages available for this audio") + supportedLanguages: Seq[String], + @description("Type of audio. 'standard', or 'podcast'.") + audioType: String, + @description("Meta information about podcast, only applicable if audioType is 'podcast'.") + podcastMeta: Option[PodcastMetaDTO], + @description("Meta information about series if the audio is a podcast and a part of a series.") + series: Option[SeriesDTO], + @description("Manuscript for the audio") + manuscript: Option[ManuscriptDTO], + @description("The time of creation for the audio-file") + created: NDLADate, + @description("The time of last update for the audio-file") + updated: NDLADate +) + +object AudioMetaInformationDTO { + implicit val audioMetaInformationTSI: TSIType[AudioMetaInformationDTO] = { + @unused + implicit val seriesReference: TSNamedType[SeriesDTO] = TSType.external[SeriesDTO]("ISeriesDTO") + TSType.fromCaseClass[AudioMetaInformationDTO] + } +} diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummary.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummary.scala deleted file mode 100644 index d1f367c3b3..0000000000 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummary.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Part of NDLA audio-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.audioapi.model.api - -import com.scalatsi._ -import no.ndla.common.model.NDLADate -import sttp.tapir.Schema.annotations.description - -import scala.annotation.unused - -// format: off -@description("Short summary of information about the audio") -case class AudioSummary( - @description("The unique id of the audio") id: Long, - @description("The title of the audio") title: Title, - @description("The audioType. Possible values standard and podcast") audioType: String, - @description("The full url to where the complete information about the audio can be found") url: String, - @description("Describes the license of the audio") license: String, - @description("A list of available languages for this audio") supportedLanguages: Seq[String], - @description("A manuscript for the audio") manuscript: Option[Manuscript], - @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[PodcastMeta], - @description("Series that the audio is part of") series: Option[SeriesSummary], - @description("The time and date of last update") lastUpdated: NDLADate -) -// format: on - -object AudioSummary { - implicit val AudioSummaryTSI: TSIType[AudioSummary] = { - @unused - implicit val seriesSummaryReference: TSType[SeriesSummary] = TSType.external[SeriesSummary]("ISeriesSummary") - TSType.fromCaseClass[AudioSummary] - } -} diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummaryDTO.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummaryDTO.scala new file mode 100644 index 0000000000..26fb20d3a0 --- /dev/null +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/AudioSummaryDTO.scala @@ -0,0 +1,39 @@ +/* + * Part of NDLA audio-api + * Copyright (C) 2017 NDLA + * + * See LICENSE + */ + +package no.ndla.audioapi.model.api + +import com.scalatsi._ +import no.ndla.common.model.NDLADate +import sttp.tapir.Schema.annotations.description + +import scala.annotation.unused + +// format: off +@description("Short summary of information about the audio") +case class AudioSummaryDTO( + @description("The unique id of the audio") id: Long, + @description("The title of the audio") title: TitleDTO, + @description("The audioType. Possible values standard and podcast") audioType: String, + @description("The full url to where the complete information about the audio can be found") url: String, + @description("Describes the license of the audio") license: String, + @description("A list of available languages for this audio") supportedLanguages: Seq[String], + @description("A manuscript for the audio") manuscript: Option[ManuscriptDTO], + @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[PodcastMetaDTO], + @description("Series that the audio is part of") series: Option[SeriesSummaryDTO], + @description("The time and date of last update") lastUpdated: NDLADate +) +// format: on + +object AudioSummaryDTO { + implicit val AudioSummaryTSI: TSIType[AudioSummaryDTO] = { + @unused + implicit val seriesSummaryReference: TSType[SeriesSummaryDTO] = + TSType.external[SeriesSummaryDTO]("ISeriesSummaryDTO") + TSType.fromCaseClass[AudioSummaryDTO] + } +} diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhoto.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhotoDTO.scala similarity index 93% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhoto.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhotoDTO.scala index 6cfab45dbd..8668a8ad13 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhoto.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/CoverPhotoDTO.scala @@ -10,7 +10,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description @description("Meta information about podcast audio") -case class CoverPhoto( +case class CoverPhotoDTO( @description("Id for the coverPhoto in image-api") id: String, @description("Url to the coverPhoto") url: String, @description("Alttext for the coverPhoto") altText: String diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Description.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/DescriptionDTO.scala similarity index 92% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Description.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/DescriptionDTO.scala index 62bf5f44f1..34ddb44f35 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Description.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/DescriptionDTO.scala @@ -10,7 +10,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description -case class Description( +case class DescriptionDTO( @description("The description of the element") description: String, @description("ISO 639-1 code that represents the language used in the description") language: String ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Manuscript.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/ManuscriptDTO.scala similarity index 92% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Manuscript.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/ManuscriptDTO.scala index 29a6ef2941..9ed826de09 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Manuscript.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/ManuscriptDTO.scala @@ -9,7 +9,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description -case class Manuscript( +case class ManuscriptDTO( @description("The manuscript of the audio file") manuscript: String, @description("ISO 639-1 code that represents the language used in the manuscript") language: String ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformation.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformation.scala deleted file mode 100644 index 6735bc8087..0000000000 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformation.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Part of NDLA audio-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.audioapi.model.api - -import no.ndla.common.model.api.Copyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Meta information about the audio object") -case class NewAudioMetaInformation( - @description("The title of the audio file") title: String, - @description("ISO 639-1 code that represents the language used in this resource") language: String, - @description("Copyright information for the audio files") copyright: Copyright, - @description("Tags for this audio file") tags: Seq[String], - @description("Type of audio. 'standard', or 'podcast', defaults to 'standard'") audioType: Option[String], - @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[NewPodcastMeta], - @description("Id of series if the audio is a podcast and a part of a series.") seriesId: Option[Long], - @description("Manuscript for the audio") manuscript: Option[String] -) -// format: on diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformationDTO.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformationDTO.scala new file mode 100644 index 0000000000..aa36cf456d --- /dev/null +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewAudioMetaInformationDTO.scala @@ -0,0 +1,26 @@ +/* + * Part of NDLA audio-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.audioapi.model.api + +import no.ndla.common.model.api.CopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Meta information about the audio object") +case class NewAudioMetaInformationDTO( + @description("The title of the audio file") title: String, + @description("ISO 639-1 code that represents the language used in this resource") language: String, + @description("Copyright information for the audio files") copyright: CopyrightDTO, + @description("Tags for this audio file") tags: Seq[String], + @description("Type of audio. 'standard', or 'podcast', defaults to 'standard'") audioType: Option[String], + @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[NewPodcastMetaDTO], + @description("Id of series if the audio is a podcast and a part of a series.") seriesId: Option[Long], + @description("Manuscript for the audio") manuscript: Option[String] +) +// format: on diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMeta.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMetaDTO.scala similarity index 93% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMeta.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMetaDTO.scala index a8c72d7949..3499e73bed 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMeta.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewPodcastMetaDTO.scala @@ -11,7 +11,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Meta information about podcast audio") -case class NewPodcastMeta( +case class NewPodcastMetaDTO( @description("Introduction for the podcast") introduction: String, @description("Cover photo for the podcast") coverPhotoId: String, @description("Cover photo alttext for the podcast") coverPhotoAltText: String, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeries.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeriesDTO.scala similarity index 97% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeries.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeriesDTO.scala index d70e31f228..30c964cc90 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeries.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/NewSeriesDTO.scala @@ -11,7 +11,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description @description("Meta information about podcast series") -case class NewSeries( +case class NewSeriesDTO( @description("Header for the series") title: String, @description("Description for the series") description: String, @description("Cover photo for the series") coverPhotoId: String, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMeta.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMetaDTO.scala similarity index 93% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMeta.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMetaDTO.scala index cdd5a8e9b1..a0b94a4c7e 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMeta.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/PodcastMetaDTO.scala @@ -11,9 +11,9 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Meta information about podcast audio") -case class PodcastMeta( +case class PodcastMetaDTO( @description("Introduction for the podcast") introduction: String, - @description("Cover photo for the podcast") coverPhoto: CoverPhoto, + @description("Cover photo for the podcast") coverPhoto: CoverPhotoDTO, @description("ISO 639-1 code that represents the language used in the title") language: String ) // format: on diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParams.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParamsDTO.scala similarity index 98% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParams.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParamsDTO.scala index bc0708c8c2..6b5c752eff 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParams.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchParamsDTO.scala @@ -12,7 +12,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class SearchParams( +case class SearchParamsDTO( @description("Return only audio with titles, alt-texts or tags matching the specified query.") query: Option[String], @description("Return only audio with provided license.") license: Option[String], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchResult.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchResult.scala index 424aaabbcd..4e34a8d4ba 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchResult.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SearchResult.scala @@ -10,25 +10,25 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about audio summary search-results") -case class AudioSummarySearchResult( +case class AudioSummarySearchResultDTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[AudioSummary] + @description("The search results") results: Seq[AudioSummaryDTO] ) @description("Information about series summary search-results") -case class SeriesSummarySearchResult( +case class SeriesSummarySearchResultDTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[SeriesSummary] + @description("The search results") results: Seq[SeriesSummaryDTO] ) @description("Information about tags-search-results") -case class TagsSearchResult( +case class TagsSearchResultDTO( @description("The total number of tags matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Series.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesDTO.scala similarity index 70% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Series.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesDTO.scala index 0a859f208b..e5cea08fe5 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Series.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesDTO.scala @@ -14,22 +14,22 @@ import sttp.tapir.Schema.annotations.description import scala.annotation.unused @description("Meta information about the series") -case class Series( +case class SeriesDTO( @description("The unique id of this series") id: Long, @description("The revision number of this series") revision: Int, - @description("The title of the series") title: Title, - @description("The description of the series") description: Description, - @description("Cover photo for the series") coverPhoto: CoverPhoto, - @description("The metainfo of the episodes in the series") episodes: Option[Seq[AudioMetaInformation]], + @description("The title of the series") title: TitleDTO, + @description("The description of the series") description: DescriptionDTO, + @description("Cover photo for the series") coverPhoto: CoverPhotoDTO, + @description("The metainfo of the episodes in the series") episodes: Option[Seq[AudioMetaInformationDTO]], @description("A list of available languages for this series") supportedLanguages: Seq[String], @description("Specifies if this series generates rss-feed") hasRSS: Boolean ) -object Series { - implicit val seriesTSI: TSIType[Series] = { +object SeriesDTO { + implicit val seriesTSI: TSIType[SeriesDTO] = { @unused - implicit val audioMetaInformationReference: TSNamedType[AudioMetaInformation] = - TSType.external[AudioMetaInformation]("IAudioMetaInformation") - TSType.fromCaseClass[Series] + implicit val audioMetaInformationReference: TSNamedType[AudioMetaInformationDTO] = + TSType.external[AudioMetaInformationDTO]("IAudioMetaInformationDTO") + TSType.fromCaseClass[SeriesDTO] } } diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParams.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParamsDTO.scala similarity index 96% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParams.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParamsDTO.scala index 8d50e2dedb..662edc1fe1 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParams.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSearchParamsDTO.scala @@ -12,7 +12,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class SeriesSearchParams( +case class SeriesSearchParamsDTO( @description("Return only series with titles, alt-texts or tags matching the specified query.") query: Option[String], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], @description("The page number of the search hits to display.") page: Option[Int], diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummary.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummaryDTO.scala similarity index 66% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummary.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummaryDTO.scala index 3fd2d68ab6..3c3d35d25a 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummary.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/SeriesSummaryDTO.scala @@ -14,20 +14,20 @@ import sttp.tapir.Schema.annotations.description import scala.annotation.unused @description("Short summary of information about the series") -case class SeriesSummary( +case class SeriesSummaryDTO( @description("The unique id of the series") id: Long, - @description("The title of the series") title: Title, - @description("The description of the series") description: Description, + @description("The title of the series") title: TitleDTO, + @description("The description of the series") description: DescriptionDTO, @description("A list of available languages for this series") supportedLanguages: Seq[String], - @description("A list of episode summaries") episodes: Option[Seq[AudioSummary]], - @description("Cover photo for the series") coverPhoto: CoverPhoto + @description("A list of episode summaries") episodes: Option[Seq[AudioSummaryDTO]], + @description("Cover photo for the series") coverPhoto: CoverPhotoDTO ) -object SeriesSummary { - implicit val SeriesSummaryTSI: TSIType[SeriesSummary] = { +object SeriesSummaryDTO { + implicit val SeriesSummaryTSI: TSIType[SeriesSummaryDTO] = { @unused - implicit val audioSummaryReference: TSType[Option[Seq[AudioSummary]]] = - TSType.external[Option[Seq[AudioSummary]]]("IAudioSummary") - TSType.fromCaseClass[SeriesSummary] + implicit val audioSummaryReference: TSType[Option[Seq[AudioSummaryDTO]]] = + TSType.external[Option[Seq[AudioSummaryDTO]]]("IAudioSummary") + TSType.fromCaseClass[SeriesSummaryDTO] } } diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Tag.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/TagDTO.scala similarity index 95% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Tag.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/TagDTO.scala index ddf909ff02..f23aaf67ce 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Tag.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/TagDTO.scala @@ -10,7 +10,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description @description("Description of the tags of the audio") -case class Tag( +case class TagDTO( @description("The searchable tag.") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Title.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/TitleDTO.scala similarity index 94% rename from audio-api/src/main/scala/no/ndla/audioapi/model/api/Title.scala rename to audio-api/src/main/scala/no/ndla/audioapi/model/api/TitleDTO.scala index 825f3b9394..2afbe4e946 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/Title.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/TitleDTO.scala @@ -9,7 +9,7 @@ package no.ndla.audioapi.model.api import sttp.tapir.Schema.annotations.description -case class Title( +case class TitleDTO( @description("The title of the audio file") title: String, @description("ISO 639-1 code that represents the language used in the title") language: String ) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformation.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformation.scala deleted file mode 100644 index 613b1350eb..0000000000 --- a/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformation.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Part of NDLA audio-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.audioapi.model.api - -import no.ndla.common.model.api.Copyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Meta information about the audio object") -case class UpdatedAudioMetaInformation( - @description("The revision number of this audio") revision: Int, - @description("The title of the audio file") title: String, - @description("ISO 639-1 code that represents the language used in this resource") language: String, - @description("Copyright information for the audio files") copyright: Copyright, - @description("Tags for this audio file") tags: Seq[String], - @description("Type of audio. 'standard', or 'podcast', defaults to 'standard'") audioType: Option[String], - @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[NewPodcastMeta], - @description("Id of series if the audio is a podcast and a part of a series.") seriesId: Option[Long], - @description("Manuscript for the audio") manuscript: Option[String], -) -// format: on diff --git a/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformationDTO.scala b/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformationDTO.scala new file mode 100644 index 0000000000..dec4c82b49 --- /dev/null +++ b/audio-api/src/main/scala/no/ndla/audioapi/model/api/UpdatedAudioMetaInformationDTO.scala @@ -0,0 +1,26 @@ +/* + * Part of NDLA audio-api + * Copyright (C) 2017 NDLA + * + * See LICENSE + */ + +package no.ndla.audioapi.model.api + +import no.ndla.common.model.api.CopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Meta information about the audio object") +case class UpdatedAudioMetaInformationDTO( + @description("The revision number of this audio") revision: Int, + @description("The title of the audio file") title: String, + @description("ISO 639-1 code that represents the language used in this resource") language: String, + @description("Copyright information for the audio files") copyright: CopyrightDTO, + @description("Tags for this audio file") tags: Seq[String], + @description("Type of audio. 'standard', or 'podcast', defaults to 'standard'") audioType: Option[String], + @description("Meta information about podcast, only applicable if audioType is 'podcast'.") podcastMeta: Option[NewPodcastMetaDTO], + @description("Id of series if the audio is a podcast and a part of a series.") seriesId: Option[Long], + @description("Manuscript for the audio") manuscript: Option[String], +) +// format: on diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/ConverterService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/ConverterService.scala index 060a067b68..62f75c6d2b 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/ConverterService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/ConverterService.scala @@ -11,7 +11,7 @@ package no.ndla.audioapi.service import cats.implicits._ import com.typesafe.scalalogging.StrictLogging import no.ndla.audioapi.Props -import no.ndla.audioapi.model.api.{CouldNotFindLanguageException, Tag} +import no.ndla.audioapi.model.api.{CouldNotFindLanguageException, TagDTO} import no.ndla.audioapi.model.domain.{AudioMetaInformation, AudioType, PodcastMeta} import no.ndla.audioapi.model.{api, domain} import no.ndla.common.Clock @@ -31,7 +31,7 @@ trait ConverterService { class ConverterService extends StrictLogging { import props._ - def updateSeries(existingSeries: domain.Series, updatedSeries: api.NewSeries): domain.Series = { + def updateSeries(existingSeries: domain.Series, updatedSeries: api.NewSeriesDTO): domain.Series = { val newTitle = common.Title(updatedSeries.title, updatedSeries.language) val newDescription = domain.Description(updatedSeries.description, updatedSeries.language) val coverPhoto = domain.CoverPhoto( @@ -52,7 +52,7 @@ trait ConverterService { ) } - def toDomainSeries(newSeries: api.NewSeries): domain.SeriesWithoutId = { + def toDomainSeries(newSeries: api.NewSeriesDTO): domain.SeriesWithoutId = { val titles = Seq(common.Title(newSeries.title, newSeries.language)) val descriptions = Seq(domain.Description(newSeries.description, newSeries.language)) @@ -100,12 +100,12 @@ trait ConverterService { def toApiAudioMetaInformation( audioMeta: domain.AudioMetaInformation, language: Option[String] - ): Try[api.AudioMetaInformation] = { + ): Try[api.AudioMetaInformationDTO] = { val apiSeries = audioMeta.series.traverse(series => toApiSeries(series, language)) apiSeries.map(series => - api.AudioMetaInformation( + api.AudioMetaInformationDTO( id = audioMeta.id.get, revision = audioMeta.revision.get, title = maybeToApiTitle(findByLanguageOrBestEffort(audioMeta.titles, language)), @@ -123,42 +123,42 @@ trait ConverterService { ) } - private def toApiTitle(title: common.Title): api.Title = api.Title(title.title, title.language) - private def toApiDescription(desc: domain.Description): api.Description = - api.Description(desc.description, desc.language) + private def toApiTitle(title: common.Title): api.TitleDTO = api.TitleDTO(title.title, title.language) + private def toApiDescription(desc: domain.Description): api.DescriptionDTO = + api.DescriptionDTO(desc.description, desc.language) - private def maybeToApiTitle(maybeTitle: Option[common.Title]): api.Title = { + private def maybeToApiTitle(maybeTitle: Option[common.Title]): api.TitleDTO = { maybeTitle match { case Some(title) => toApiTitle(title) - case None => api.Title("", DefaultLanguage) + case None => api.TitleDTO("", DefaultLanguage) } } - private def toApiTags(maybeTag: Option[common.Tag]): Tag = { + private def toApiTags(maybeTag: Option[common.Tag]): TagDTO = { maybeTag match { - case Some(tag) => api.Tag(tag.tags, tag.language) - case None => api.Tag(Seq(), DefaultLanguage) + case Some(tag) => api.TagDTO(tag.tags, tag.language) + case None => api.TagDTO(Seq(), DefaultLanguage) } } - def toApiAudio(audio: Option[domain.Audio]): api.Audio = { + def toApiAudio(audio: Option[domain.Audio]): api.AudioDTO = { audio match { - case Some(x) => api.Audio(s"$Domain/$AudioFilesUrlSuffix/${x.filePath}", x.mimeType, x.fileSize, x.language) - case None => api.Audio("", "", 0, DefaultLanguage) + case Some(x) => api.AudioDTO(s"$Domain/$AudioFilesUrlSuffix/${x.filePath}", x.mimeType, x.fileSize, x.language) + case None => api.AudioDTO("", "", 0, DefaultLanguage) } } - def toApiLicence(licenseAbbrevation: String): commonApi.License = { + def toApiLicence(licenseAbbrevation: String): commonApi.LicenseDTO = { getLicense(licenseAbbrevation) match { - case Some(license) => commonApi.License(license.license.toString, Option(license.description), license.url) + case Some(license) => commonApi.LicenseDTO(license.license.toString, Option(license.description), license.url) case None => logger.warn("Could not retrieve license information for {}", licenseAbbrevation) - commonApi.License("unknown", None, None) + commonApi.LicenseDTO("unknown", None, None) } } - def toApiCopyright(copyright: Copyright): commonApi.Copyright = { - commonApi.Copyright( + def toApiCopyright(copyright: Copyright): commonApi.CopyrightDTO = { + commonApi.CopyrightDTO( toApiLicence(copyright.license), copyright.origin, copyright.creators.map(_.toApi), @@ -170,21 +170,21 @@ trait ConverterService { ) } - def toDomainTags(tags: api.Tag): Seq[common.Tag] = { + def toDomainTags(tags: api.TagDTO): Seq[common.Tag] = { if (tags.tags.nonEmpty) { Seq() } else { Seq(common.Tag(tags.tags, tags.language)) } } - def toApiPodcastMeta(meta: domain.PodcastMeta): api.PodcastMeta = { - api.PodcastMeta( + def toApiPodcastMeta(meta: domain.PodcastMeta): api.PodcastMetaDTO = { + api.PodcastMetaDTO( introduction = meta.introduction, coverPhoto = toApiCoverPhoto(meta.coverPhoto), language = meta.language ) } - def toApiManuscript(meta: domain.Manuscript): api.Manuscript = { - api.Manuscript( + def toApiManuscript(meta: domain.Manuscript): api.ManuscriptDTO = { + api.ManuscriptDTO( manuscript = meta.manuscript, language = meta.language ) @@ -192,15 +192,15 @@ trait ConverterService { def getPhotoUrl(meta: domain.CoverPhoto): String = s"$RawImageApiUrl/${meta.imageId}" - def toApiCoverPhoto(meta: domain.CoverPhoto): api.CoverPhoto = { - api.CoverPhoto( + def toApiCoverPhoto(meta: domain.CoverPhoto): api.CoverPhotoDTO = { + api.CoverPhotoDTO( id = meta.imageId, url = getPhotoUrl(meta), altText = meta.altText ) } - def toDomainPodcastMeta(meta: api.NewPodcastMeta, language: String): PodcastMeta = { + def toDomainPodcastMeta(meta: api.NewPodcastMetaDTO, language: String): PodcastMeta = { domain.PodcastMeta( introduction = meta.introduction, coverPhoto = domain.CoverPhoto(meta.coverPhotoId, meta.coverPhotoAltText), @@ -213,7 +213,7 @@ trait ConverterService { } def toDomainAudioMetaInformation( - audioMeta: api.NewAudioMetaInformation, + audioMeta: api.NewAudioMetaInformationDTO, audio: domain.Audio, maybeSeries: Option[domain.Series], tokenUser: TokenUser @@ -236,7 +236,7 @@ trait ConverterService { ) } - def toDomainCopyright(copyright: commonApi.Copyright): Copyright = { + def toDomainCopyright(copyright: commonApi.CopyrightDTO): Copyright = { Copyright( copyright.license.license, copyright.origin, @@ -264,13 +264,13 @@ trait ConverterService { } } - def toApiSeries(series: domain.Series, language: Option[String]): Try[api.Series] = { + def toApiSeries(series: domain.Series, language: Option[String]): Try[api.SeriesDTO] = { for { title <- findAndConvertDomainToApiField(series.title, language).map(toApiTitle) description <- findAndConvertDomainToApiField(series.description, language).map(toApiDescription) coverPhoto = toApiCoverPhoto(series.coverPhoto) episodes <- series.episodes.traverse(eps => eps.traverse(toApiAudioMetaInformation(_, language))) - } yield api.Series( + } yield api.SeriesDTO( id = series.id, revision = series.revision, title = title, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/ReadService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/ReadService.scala index d9682baf90..06e8299c90 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/ReadService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/ReadService.scala @@ -23,7 +23,7 @@ trait ReadService { class ReadService { - def seriesWithId(seriesId: Long, language: Option[String]): Try[api.Series] = { + def seriesWithId(seriesId: Long, language: Option[String]): Try[api.SeriesDTO] = { seriesRepository.withId(seriesId) match { case Failure(ex) => Failure(ex) case Success(None) => @@ -36,7 +36,7 @@ trait ReadService { } } - def getAllTags(input: String, pageSize: Int, page: Int, language: String): Try[api.TagsSearchResult] = { + def getAllTags(input: String, pageSize: Int, page: Int, language: String): Try[api.TagsSearchResultDTO] = { val result = tagSearchService.matchingQuery( query = input, searchLanguage = language, @@ -47,15 +47,15 @@ trait ReadService { result.map(searchConverterService.tagSearchResultAsApiResult) } - def withId(id: Long, language: Option[String]): Option[api.AudioMetaInformation] = + def withId(id: Long, language: Option[String]): Option[api.AudioMetaInformationDTO] = audioRepository.withId(id).flatMap(audio => converterService.toApiAudioMetaInformation(audio, language).toOption) - def withExternalId(externalId: String, language: Option[String]): Option[api.AudioMetaInformation] = + def withExternalId(externalId: String, language: Option[String]): Option[api.AudioMetaInformationDTO] = audioRepository .withExternalId(externalId) .flatMap(audio => converterService.toApiAudioMetaInformation(audio, language).toOption) - def getAudiosByIds(audioIds: List[Long], language: Option[String]): Try[List[api.AudioMetaInformation]] = { + def getAudiosByIds(audioIds: List[Long], language: Option[String]): Try[List[api.AudioMetaInformationDTO]] = { for { ids <- if (audioIds.isEmpty) Failure(ValidationException("ids", "Query parameter 'ids' is missing")) @@ -65,11 +65,11 @@ trait ReadService { } yield api } - def getMetaAudioDomainDump(pageNo: Int, pageSize: Int): api.AudioMetaDomainDump = { + def getMetaAudioDomainDump(pageNo: Int, pageSize: Int): api.AudioMetaDomainDumpDTO = { val (safePageNo, safePageSize) = (math.max(pageNo, 1), math.max(pageSize, 0)) val results = audioRepository.getByPage(safePageSize, (safePageNo - 1) * safePageSize) - api.AudioMetaDomainDump(audioRepository.audioCount, pageNo, pageSize, results) + api.AudioMetaDomainDumpDTO(audioRepository.audioCount, pageNo, pageSize, results) } } } diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/WriteService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/WriteService.scala index 47a0a6c23d..6dc06af43b 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/WriteService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/WriteService.scala @@ -40,7 +40,7 @@ trait WriteService { class WriteService extends StrictLogging { - def updateSeries(id: Long, toUpdateSeries: api.NewSeries): Try[api.Series] = { + def updateSeries(id: Long, toUpdateSeries: api.NewSeriesDTO): Try[api.SeriesDTO] = { seriesRepository.withId(id) match { case Failure(ex) => Failure(ex) case Success(None) => Failure(new NotFoundException(s"Could not find series to update with id: '$id'")) @@ -68,7 +68,7 @@ trait WriteService { } } - def newSeries(newSeries: api.NewSeries): Try[api.Series] = { + def newSeries(newSeries: api.NewSeriesDTO): Try[api.SeriesDTO] = { val domainSeries = converterService.toDomainSeries(newSeries) val episodes = newSeries.episodes.map(id => id -> audioRepository.withId(id)) @@ -136,7 +136,7 @@ trait WriteService { } yield reindexed }) - def deleteAudioLanguageVersion(audioId: Long, language: String): Try[Option[api.AudioMetaInformation]] = + def deleteAudioLanguageVersion(audioId: Long, language: String): Try[Option[api.AudioMetaInformationDTO]] = audioRepository.withId(audioId) match { case Some(existing) if existing.supportedLanguages.contains(language) => val newAudio = converterService.withoutLanguage(existing, language) @@ -163,7 +163,7 @@ trait WriteService { Failure(new NotFoundException(s"Audio with id $audioId was not found, and could not be deleted.")) } - def deleteSeriesLanguageVersion(seriesId: Long, language: String): Try[Option[api.Series]] = { + def deleteSeriesLanguageVersion(seriesId: Long, language: String): Try[Option[api.SeriesDTO]] = { seriesRepository.withId(seriesId) match { case Success(Some(existing)) if existing.supportedLanguages.contains(language) => val newSeries = converterService.withoutLanguage(existing, language) @@ -194,10 +194,10 @@ trait WriteService { } def storeNewAudio( - newAudioMeta: api.NewAudioMetaInformation, + newAudioMeta: api.NewAudioMetaInformationDTO, file: UploadedFile, tokenUser: TokenUser - ): Try[api.AudioMetaInformation] = { + ): Try[api.AudioMetaInformationDTO] = { validationService.validateAudioFile(file) match { case msgs if msgs.nonEmpty => Failure(new ValidationException(errors = msgs)) case _ => @@ -273,10 +273,10 @@ trait WriteService { def updateAudio( id: Long, - metadataToUpdate: api.UpdatedAudioMetaInformation, + metadataToUpdate: api.UpdatedAudioMetaInformationDTO, fileOpt: Option[UploadedFile], user: TokenUser - ): Try[api.AudioMetaInformation] = { + ): Try[api.AudioMetaInformationDTO] = { audioRepository.withId(id) match { case None => Failure(new NotFoundException) case Some(existingMetadata) => @@ -338,7 +338,7 @@ trait WriteService { oldAudio: domain.AudioMetaInformation, language: Option[String], seriesId: Option[Long] - ): Try[api.AudioMetaInformation] = { + ): Try[api.AudioMetaInformationDTO] = { for { maybeSeries <- getSeriesFromOpt(seriesId) validated <- validationService.validate(toSave, Some(oldAudio), maybeSeries, language) @@ -358,7 +358,7 @@ trait WriteService { private[service] def mergeAudioMeta( existing: domain.AudioMetaInformation, - toUpdate: api.UpdatedAudioMetaInformation, + toUpdate: api.UpdatedAudioMetaInformationDTO, savedAudio: Option[Audio], user: TokenUser ): Try[(domain.AudioMetaInformation, Option[Audio])] = { diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/search/AudioSearchService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/search/AudioSearchService.scala index 509a97e163..0ef6631d9e 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/search/AudioSearchService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/search/AudioSearchService.scala @@ -34,19 +34,19 @@ trait AudioSearchService { with ErrorHandling => val audioSearchService: AudioSearchService - class AudioSearchService extends StrictLogging with SearchService[api.AudioSummary] { + class AudioSearchService extends StrictLogging with SearchService[api.AudioSummaryDTO] { import props._ override val searchIndex: String = SearchIndex - override def hitToApiModel(hitString: String, language: String): Try[api.AudioSummary] = { + override def hitToApiModel(hitString: String, language: String): Try[api.AudioSummaryDTO] = { for { searchable <- CirceUtil.tryParseAs[SearchableAudioInformation](hitString) result <- searchConverterService.asAudioSummary(searchable, language) } yield result } - def matchingQuery(settings: SearchSettings): Try[domain.SearchResult[api.AudioSummary]] = { + def matchingQuery(settings: SearchSettings): Try[domain.SearchResult[api.AudioSummaryDTO]] = { val fullSearch = settings.query.emptySomeToNone match { case Some(query) => @@ -76,7 +76,10 @@ trait AudioSearchService { executeSearch(settings, fullSearch) } - def executeSearch(settings: SearchSettings, queryBuilder: BoolQuery): Try[domain.SearchResult[api.AudioSummary]] = { + def executeSearch( + settings: SearchSettings, + queryBuilder: BoolQuery + ): Try[domain.SearchResult[api.AudioSummaryDTO]] = { val licenseFilter = settings.license match { case None => Some(boolQuery().not(termQuery("license", "copyrighted"))) diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/search/SearchConverterService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/search/SearchConverterService.scala index 6dd0c75bf2..2b42d5f968 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/search/SearchConverterService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/search/SearchConverterService.scala @@ -12,7 +12,7 @@ import cats.implicits._ import com.sksamuel.elastic4s.requests.searches.SearchHit import com.typesafe.scalalogging.StrictLogging import no.ndla.audioapi.Props -import no.ndla.audioapi.model.api.Title +import no.ndla.audioapi.model.api.TitleDTO import no.ndla.audioapi.model.domain.{AudioMetaInformation, SearchResult, SearchableTag} import no.ndla.audioapi.model.search._ import no.ndla.audioapi.model.{api, domain} @@ -45,7 +45,7 @@ trait SearchConverterService { }) } - def asAudioSummary(searchable: SearchableAudioInformation, language: String): Try[api.AudioSummary] = { + def asAudioSummary(searchable: SearchableAudioInformation, language: String): Try[api.AudioSummaryDTO] = { val titles = searchable.titles.languageValues.map(lv => common.Title(lv.value, lv.language)) val domainPodcastMeta = searchable.podcastMetaIntroduction.languageValues.flatMap(lv => { @@ -61,8 +61,8 @@ trait SearchConverterService { }) val title = findByLanguageOrBestEffort(titles, language) match { - case None => Title("", language) - case Some(x) => Title(x.title, x.language) + case None => TitleDTO("", language) + case Some(x) => TitleDTO(x.title, x.language) } val podcastMeta = findByLanguageOrBestEffort(domainPodcastMeta, language) @@ -79,7 +79,7 @@ trait SearchConverterService { searchable.series .traverse(s => asSeriesSummary(s, language)) .map(series => - api.AudioSummary( + api.AudioSummaryDTO( id = searchable.id.toLong, title = title, audioType = searchable.audioType, @@ -94,15 +94,15 @@ trait SearchConverterService { ) } - def asSeriesSummary(searchable: SearchableSeries, language: String): Try[api.SeriesSummary] = { + def asSeriesSummary(searchable: SearchableSeries, language: String): Try[api.SeriesSummaryDTO] = { for { title <- converterService .findAndConvertDomainToApiField(searchable.titles.languageValues, Some(language)) - .map(lv => api.Title(lv.value, lv.language)) + .map(lv => api.TitleDTO(lv.value, lv.language)) description <- converterService .findAndConvertDomainToApiField(searchable.descriptions.languageValues, Some(language)) - .map(lv => api.Description(lv.value, lv.language)) + .map(lv => api.DescriptionDTO(lv.value, lv.language)) episodes <- searchable.episodes.traverse(eps => eps.traverse(ep => searchConverterService.asAudioSummary(ep, language)) @@ -112,7 +112,7 @@ trait SearchConverterService { searchable.titles.languageValues, searchable.descriptions.languageValues ) - } yield api.SeriesSummary( + } yield api.SeriesSummaryDTO( id = searchable.id.toLong, title = title, description = description, @@ -193,9 +193,9 @@ trait SearchConverterService { } def asApiAudioSummarySearchResult( - searchResult: domain.SearchResult[api.AudioSummary] - ): api.AudioSummarySearchResult = - api.AudioSummarySearchResult( + searchResult: domain.SearchResult[api.AudioSummaryDTO] + ): api.AudioSummarySearchResultDTO = + api.AudioSummarySearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, @@ -204,9 +204,9 @@ trait SearchConverterService { ) def asApiSeriesSummarySearchResult( - searchResult: domain.SearchResult[api.SeriesSummary] - ): api.SeriesSummarySearchResult = - api.SeriesSummarySearchResult( + searchResult: domain.SearchResult[api.SeriesSummaryDTO] + ): api.SeriesSummarySearchResultDTO = + api.SeriesSummarySearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, @@ -224,8 +224,8 @@ trait SearchConverterService { ) ) - def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResult = - api.TagsSearchResult( + def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResultDTO = + api.TagsSearchResultDTO( searchResult.totalCount, searchResult.page.getOrElse(1), searchResult.pageSize, diff --git a/audio-api/src/main/scala/no/ndla/audioapi/service/search/SeriesSearchService.scala b/audio-api/src/main/scala/no/ndla/audioapi/service/search/SeriesSearchService.scala index 2eab3e87ea..beba3fb59e 100644 --- a/audio-api/src/main/scala/no/ndla/audioapi/service/search/SeriesSearchService.scala +++ b/audio-api/src/main/scala/no/ndla/audioapi/service/search/SeriesSearchService.scala @@ -36,19 +36,19 @@ trait SeriesSearchService { with ErrorHandling => val seriesSearchService: SeriesSearchService - class SeriesSearchService extends StrictLogging with SearchService[api.SeriesSummary] { + class SeriesSearchService extends StrictLogging with SearchService[api.SeriesSummaryDTO] { import props._ override val searchIndex: String = SeriesSearchIndex - override def hitToApiModel(hitString: String, language: String): Try[api.SeriesSummary] = { + override def hitToApiModel(hitString: String, language: String): Try[api.SeriesSummaryDTO] = { for { searchable <- CirceUtil.tryParseAs[SearchableSeries](hitString) result <- searchConverterService.asSeriesSummary(searchable, language) } yield result } - def matchingQuery(settings: SeriesSearchSettings): Try[domain.SearchResult[api.SeriesSummary]] = { + def matchingQuery(settings: SeriesSearchSettings): Try[domain.SearchResult[api.SeriesSummaryDTO]] = { val fullSearch = settings.query.emptySomeToNone match { case Some(query) => @@ -79,7 +79,7 @@ trait SeriesSearchService { def executeSearch( settings: SeriesSearchSettings, queryBuilder: BoolQuery - ): Try[domain.SearchResult[api.SeriesSummary]] = { + ): Try[domain.SearchResult[api.SeriesSummaryDTO]] = { val (languageFilter, searchLanguage) = settings.language match { case None | Some(AllLanguages) => (None, "*") diff --git a/audio-api/src/test/scala/no/ndla/audioapi/TestData.scala b/audio-api/src/test/scala/no/ndla/audioapi/TestData.scala index 4e5c151ec0..fda483f2fc 100644 --- a/audio-api/src/test/scala/no/ndla/audioapi/TestData.scala +++ b/audio-api/src/test/scala/no/ndla/audioapi/TestData.scala @@ -112,13 +112,13 @@ object TestData { val updated: NDLADate = NDLADate.of(2017, 4, 1, 12, 15, 32) val created: NDLADate = NDLADate.of(2017, 3, 1, 12, 15, 32) - val DefaultApiImageMetaInformation: api.AudioMetaInformation = api.AudioMetaInformation( + val DefaultApiImageMetaInformation: api.AudioMetaInformationDTO = api.AudioMetaInformationDTO( 1, 1, - api.Title("title", "nb"), - api.Audio("audio/test.mp3", "audio/mpeg", 1024, "nb"), - commonApi.Copyright(commonApi.License("by-sa", None, None), None, Seq(), Seq(), Seq(), None, None, false), - api.Tag(Seq("tag"), "nb"), + api.TitleDTO("title", "nb"), + api.AudioDTO("audio/test.mp3", "audio/mpeg", 1024, "nb"), + commonApi.CopyrightDTO(commonApi.LicenseDTO("by-sa", None, None), None, Seq(), Seq(), Seq(), None, None, false), + api.TagDTO(Seq("tag"), "nb"), Seq("nb"), "standard", None, diff --git a/audio-api/src/test/scala/no/ndla/audioapi/controller/AudioControllerTest.scala b/audio-api/src/test/scala/no/ndla/audioapi/controller/AudioControllerTest.scala index fd9b5f9fdd..3ed8361f78 100644 --- a/audio-api/src/test/scala/no/ndla/audioapi/controller/AudioControllerTest.scala +++ b/audio-api/src/test/scala/no/ndla/audioapi/controller/AudioControllerTest.scala @@ -14,7 +14,7 @@ import no.ndla.audioapi.model.domain.SearchSettings import no.ndla.audioapi.model.{api, domain} import no.ndla.audioapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.common.CirceUtil.unsafeParseAs -import no.ndla.common.model.api.{Copyright, License} +import no.ndla.common.model.api.{CopyrightDTO, LicenseDTO} import no.ndla.tapirtesting.TapirControllerTest import org.mockito.ArgumentMatchers.{eq as eqTo, *} import org.mockito.ArgumentCaptor @@ -110,13 +110,13 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi test("That POST / returns 200 if everything is fine and dandy", Retryable) { val sampleAudioMeta = - api.AudioMetaInformation( + api.AudioMetaInformationDTO( 1, 1, - Title("title", "nb"), - Audio("", "", -1, "nb"), - Copyright(License("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), - Tag(Seq(), "nb"), + TitleDTO("title", "nb"), + AudioDTO("", "", -1, "nb"), + CopyrightDTO(LicenseDTO("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), + TagDTO(Seq(), "nb"), Seq("nb"), "podcast", None, @@ -125,7 +125,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi TestData.yesterday, TestData.today ) - when(writeService.storeNewAudio(any[NewAudioMetaInformation], any, any)).thenReturn(Success(sampleAudioMeta)) + when(writeService.storeNewAudio(any[NewAudioMetaInformationDTO], any, any)).thenReturn(Success(sampleAudioMeta)) val file = multipart("file", fileBody) val metadata = multipart("metadata", sampleNewAudioMeta) @@ -145,7 +145,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi doNothing.when(runtimeMock).printStackTrace() when(runtimeMock.getMessage).thenReturn("Something (not really) wrong (this is a test hehe)") - when(writeService.storeNewAudio(any[NewAudioMetaInformation], any, any)) + when(writeService.storeNewAudio(any[NewAudioMetaInformationDTO], any, any)) .thenReturn(Failure(runtimeMock)) val file = multipart("file", fileBody) @@ -188,7 +188,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi test("That scrollId is in header, and not in body") { val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.AudioSummary]( + val searchResponse = domain.SearchResult[api.AudioSummaryDTO]( 0, Some(1), 10, @@ -212,7 +212,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi reset(audioSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.AudioSummary]( + val searchResponse = domain.SearchResult[api.AudioSummaryDTO]( 0, Some(1), 10, @@ -237,7 +237,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi reset(audioSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.AudioSummary]( + val searchResponse = domain.SearchResult[api.AudioSummaryDTO]( 0, Some(1), 10, @@ -264,7 +264,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi reset(audioSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.AudioSummary]( + val searchResponse = domain.SearchResult[api.AudioSummaryDTO]( 0, Some(1), 10, @@ -305,7 +305,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi response.code.code should be(200) val parsedBody = parser.parse(response.body) val jsonObject = parsedBody.toTry.get - val deserializedE = jsonObject.as[api.AudioMetaInformation] + val deserializedE = jsonObject.as[api.AudioMetaInformationDTO] val deserialized = deserializedE.toTry.get deserialized should be(TestData.DefaultApiImageMetaInformation) } @@ -324,13 +324,13 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi } test("That GET /ids returns 200 and handles comma separated list") { - val one = api.AudioMetaInformation( + val one = api.AudioMetaInformationDTO( 1, 1, - Title("one", "nb"), - Audio("", "", -1, "nb"), - Copyright(License("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), - Tag(Seq(), "nb"), + TitleDTO("one", "nb"), + AudioDTO("", "", -1, "nb"), + CopyrightDTO(LicenseDTO("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), + TagDTO(Seq(), "nb"), Seq("nb"), "podcast", None, @@ -339,8 +339,8 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi TestData.yesterday, TestData.today ) - val two = one.copy(id = 2, title = Title("two", "nb")) - val three = one.copy(id = 3, title = Title("three", "nb")) + val two = one.copy(id = 2, title = TitleDTO("two", "nb")) + val three = one.copy(id = 3, title = TitleDTO("three", "nb")) val expectedResult = List(one, two, three) @@ -352,7 +352,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi ) response.code.code should be(200) import io.circe.generic.auto._ - val parsedBody = unsafeParseAs[List[api.AudioMetaInformation]](response.body) + val parsedBody = unsafeParseAs[List[api.AudioMetaInformationDTO]](response.body) parsedBody should be(expectedResult) verify(readService, times(1)).getAudiosByIds(eqTo(List(1, 2, 3)), any) @@ -360,7 +360,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi test("That GET /?query= doesnt pass empty-string search parameter") { reset(audioSearchService, searchConverterService) - val searchResponse = domain.SearchResult[api.AudioSummary]( + val searchResponse = domain.SearchResult[api.AudioSummaryDTO]( 0, Some(1), 10, @@ -383,13 +383,13 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi test("That uploading a file bigger than max filesize returns 413", Retryable) { val sampleAudioMeta = - api.AudioMetaInformation( + api.AudioMetaInformationDTO( 1, 1, - Title("title", "nb"), - Audio("", "", -1, "nb"), - Copyright(License("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), - Tag(Seq(), "nb"), + TitleDTO("title", "nb"), + AudioDTO("", "", -1, "nb"), + CopyrightDTO(LicenseDTO("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), + TagDTO(Seq(), "nb"), Seq("nb"), "podcast", None, @@ -398,7 +398,7 @@ class AudioControllerTest extends UnitSuite with TestEnvironment with Retries wi TestData.yesterday, TestData.today ) - when(writeService.storeNewAudio(any[NewAudioMetaInformation], any, any)).thenReturn(Success(sampleAudioMeta)) + when(writeService.storeNewAudio(any[NewAudioMetaInformationDTO], any, any)).thenReturn(Success(sampleAudioMeta)) val tooBigFile = multipart("file", Array[Byte](0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21)) diff --git a/audio-api/src/test/scala/no/ndla/audioapi/service/ConverterServiceTest.scala b/audio-api/src/test/scala/no/ndla/audioapi/service/ConverterServiceTest.scala index 3a6b331360..d792468ece 100644 --- a/audio-api/src/test/scala/no/ndla/audioapi/service/ConverterServiceTest.scala +++ b/audio-api/src/test/scala/no/ndla/audioapi/service/ConverterServiceTest.scala @@ -46,13 +46,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that toApiAudioMetaInformation converts a domain class to an api class") { - val expected = api.AudioMetaInformation( + val expected = api.AudioMetaInformationDTO( audioMeta.id.get, audioMeta.revision.get, - api.Title("Batmen er på vift med en bil", "nb"), + api.TitleDTO("Batmen er på vift med en bil", "nb"), service.toApiAudio(audioMeta.filePaths.headOption), service.toApiCopyright(audioMeta.copyright), - api.Tag(Seq("fisk"), "nb"), + api.TagDTO(Seq("fisk"), "nb"), Seq("nb"), "standard", None, @@ -66,13 +66,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("that toApiAudioMetaInformation should return DefaultLanguage if language is not supported") { - val expectedDefaultLanguage = api.AudioMetaInformation( + val expectedDefaultLanguage = api.AudioMetaInformationDTO( audioMeta.id.get, audioMeta.revision.get, - api.Title("Batmen er på vift med en bil", "nb"), + api.TitleDTO("Batmen er på vift med en bil", "nb"), service.toApiAudio(audioMeta.filePaths.headOption), service.toApiCopyright(audioMeta.copyright), - api.Tag(Seq("fisk"), "nb"), + api.TagDTO(Seq("fisk"), "nb"), Seq("nb"), "standard", None, @@ -82,7 +82,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { updated ) - val expectedNoTitles = expectedDefaultLanguage.copy(title = api.Title("", "nb")) + val expectedNoTitles = expectedDefaultLanguage.copy(title = api.TitleDTO("", "nb")) val audioWithNoTitles = audioMeta.copy(titles = Seq.empty) val randomLanguage = "norsk" @@ -93,7 +93,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("That toApiLicense converts to an api.License") { val licenseAbbr = CC_BY_SA.toString - val license = commonApi.License( + val license = commonApi.LicenseDTO( licenseAbbr, Some("Creative Commons Attribution-ShareAlike 4.0 International"), Some("https://creativecommons.org/licenses/by-sa/4.0/") @@ -105,7 +105,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("That toApiLicense returns unknown if the license is invalid") { val licenseAbbr = "garbage" - service.toApiLicence(licenseAbbr) should equal(commonApi.License("unknown", None, None)) + service.toApiLicence(licenseAbbr) should equal(commonApi.LicenseDTO("unknown", None, None)) } test("That mergeLanguageField merges language fields as expected") { diff --git a/audio-api/src/test/scala/no/ndla/audioapi/service/WriteServiceTest.scala b/audio-api/src/test/scala/no/ndla/audioapi/service/WriteServiceTest.scala index dba17278f6..8190e83b8c 100644 --- a/audio-api/src/test/scala/no/ndla/audioapi/service/WriteServiceTest.scala +++ b/audio-api/src/test/scala/no/ndla/audioapi/service/WriteServiceTest.scala @@ -14,7 +14,7 @@ import no.ndla.audioapi.model.{api, domain} import no.ndla.audioapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.common.errors.{ValidationException, ValidationMessage} import no.ndla.common.model -import no.ndla.common.model.api.{Copyright, License} +import no.ndla.common.model.api.{CopyrightDTO, LicenseDTO} import no.ndla.common.model.domain.UploadedFile import no.ndla.common.model.{NDLADate, domain as common} import org.mockito.ArgumentMatchers.{any, eq as eqTo} @@ -34,10 +34,10 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val filePartMock: UploadedFile = mock[UploadedFile] val s3ObjectMock: HeadObjectResponse = mock[HeadObjectResponse] - val newAudioMeta: NewAudioMetaInformation = NewAudioMetaInformation( + val newAudioMeta: NewAudioMetaInformationDTO = NewAudioMetaInformationDTO( "title", "en", - Copyright(License("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), + CopyrightDTO(LicenseDTO("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), Seq("tag"), None, None, @@ -45,11 +45,11 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None ) - val updatedAudioMeta: UpdatedAudioMetaInformation = UpdatedAudioMetaInformation( + val updatedAudioMeta: UpdatedAudioMetaInformationDTO = UpdatedAudioMetaInformationDTO( revision = 1, title = "title", language = "en", - copyright = Copyright(License("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), + copyright = CopyrightDTO(LicenseDTO("by", None, None), None, Seq(), Seq(), Seq(), None, None, false), tags = Seq("tag"), audioType = None, podcastMeta = None, @@ -291,7 +291,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { } test("that mergeAudioMeta overwrites fields from toUpdate for given language") { - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "A new english title", "en", @@ -308,7 +308,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { } test("that mergeAudioMeta adds fields from toUpdate for new language") { - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "En ny norsk tittel", "nb", @@ -326,7 +326,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { } test("that mergeAudioMeta does not merge filePaths if no new audio") { - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "A new english title", "en", @@ -346,7 +346,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("that mergeAudioMeta overwrites filepath if new audio for same language") { val newAudio = Audio(newFileName2, "audio/mp3", 1024, "en") - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "A new english title", "en", @@ -368,7 +368,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("that mergeAudioMeta adds filepath if new audio for new language") { val newAudio = Audio(newFileName2, "audio/mp3", 1024, "nb") - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "En ny norsk tittel", "nb", @@ -664,7 +664,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { when(seriesRepository.insert(any[domain.Series])(any[DBSession])) .thenReturn(Failure(new RuntimeException("weird failure there buddy"))) - val updateSeries = api.NewSeries( + val updateSeries = api.NewSeriesDTO( title = "nyTittel", description = "nyBeskrivelse", coverPhotoId = "555", @@ -704,7 +704,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { .thenReturn(Failure(new Helpers.OptimisticLockException)) setupSuccessfulSeriesValidation() - val updateSeries = api.NewSeries( + val updateSeries = api.NewSeriesDTO( title = "nyTittel", description = "nyBeskrivelse", coverPhotoId = "555", @@ -754,7 +754,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) }) - val updateSeries = api.NewSeries( + val updateSeries = api.NewSeriesDTO( title = "nyTittel", description = "nyBeskrivelse", coverPhotoId = "555", @@ -803,7 +803,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { Success(i.getArgument(0)) ) - val updateSeries = api.NewSeries( + val updateSeries = api.NewSeriesDTO( title = "nyTittel", description = "nyBeskrivelse", coverPhotoId = "555", @@ -843,7 +843,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { Success(i.getArgument[domain.Series](0)) }) - val updateSeries = api.NewSeries( + val updateSeries = api.NewSeriesDTO( title = "nyTittel", description = "nyBeskrivelse", coverPhotoId = "555", @@ -861,7 +861,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { } test("that mergeAudioMeta removes duplicate tags from toUpdate for given language") { - val toUpdate = UpdatedAudioMetaInformation( + val toUpdate = UpdatedAudioMetaInformationDTO( 1, "A new english title", "en", diff --git a/audio-api/src/test/scala/no/ndla/audioapi/service/search/SearchConverterServiceTest.scala b/audio-api/src/test/scala/no/ndla/audioapi/service/search/SearchConverterServiceTest.scala index 593c1b5df8..480aa5de7e 100644 --- a/audio-api/src/test/scala/no/ndla/audioapi/service/search/SearchConverterServiceTest.scala +++ b/audio-api/src/test/scala/no/ndla/audioapi/service/search/SearchConverterServiceTest.scala @@ -36,14 +36,14 @@ class SearchConverterServiceTest extends UnitSuite with TestEnvironment { Title("Nekonata titolo", "unknown") ) - val apiTitles: List[api.Title] = List( - api.Title("Bokmål tittel", "nb"), - api.Title("Nynorsk tittel", "nn"), - api.Title("English title", "en"), - api.Title("Titre francais", "fr"), - api.Title("Deutsch titel", "de"), - api.Title("Titulo espanol", "es"), - api.Title("Nekonata titolo", "unknown") + val apiTitles: List[api.TitleDTO] = List( + api.TitleDTO("Bokmål tittel", "nb"), + api.TitleDTO("Nynorsk tittel", "nn"), + api.TitleDTO("English title", "en"), + api.TitleDTO("Titre francais", "fr"), + api.TitleDTO("Deutsch titel", "de"), + api.TitleDTO("Titulo espanol", "es"), + api.TitleDTO("Nekonata titolo", "unknown") ) val audioFiles: Seq[Audio] = Seq( diff --git a/common/src/main/scala/no/ndla/common/model/api/Author.scala b/common/src/main/scala/no/ndla/common/model/api/AuthorDTO.scala similarity index 77% rename from common/src/main/scala/no/ndla/common/model/api/Author.scala rename to common/src/main/scala/no/ndla/common/model/api/AuthorDTO.scala index 20ba243159..506299d513 100644 --- a/common/src/main/scala/no/ndla/common/model/api/Author.scala +++ b/common/src/main/scala/no/ndla/common/model/api/AuthorDTO.scala @@ -14,7 +14,7 @@ import no.ndla.common.model.domain import sttp.tapir.Schema.annotations.description @description("Information about an author") -case class Author( +case class AuthorDTO( @description("The description of the author. Eg. Photographer or Supplier") `type`: String, @description("The name of the of the author") name: String ) { @@ -24,7 +24,7 @@ case class Author( ) } -object Author { - implicit def encoder: Encoder[Author] = deriveEncoder[Author] - implicit def decoder: Decoder[Author] = deriveDecoder[Author] +object AuthorDTO { + implicit def encoder: Encoder[AuthorDTO] = deriveEncoder[AuthorDTO] + implicit def decoder: Decoder[AuthorDTO] = deriveDecoder[AuthorDTO] } diff --git a/common/src/main/scala/no/ndla/common/model/api/Copyright.scala b/common/src/main/scala/no/ndla/common/model/api/CopyrightDTO.scala similarity index 69% rename from common/src/main/scala/no/ndla/common/model/api/Copyright.scala rename to common/src/main/scala/no/ndla/common/model/api/CopyrightDTO.scala index 2d98a45d90..256d2871e2 100644 --- a/common/src/main/scala/no/ndla/common/model/api/Copyright.scala +++ b/common/src/main/scala/no/ndla/common/model/api/CopyrightDTO.scala @@ -14,18 +14,18 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Description of copyright information") -case class Copyright( - @description("Describes the license of the article") license: License, +case class CopyrightDTO( + @description("Describes the license of the article") license: LicenseDTO, @description("Reference to where the article is procured") origin: Option[String], - @description("List of creators") creators: Seq[Author] = Seq.empty, - @description("List of processors") processors: Seq[Author] = Seq.empty, - @description("List of rightsholders") rightsholders: Seq[Author] = Seq.empty, + @description("List of creators") creators: Seq[AuthorDTO] = Seq.empty, + @description("List of processors") processors: Seq[AuthorDTO] = Seq.empty, + @description("List of rightsholders") rightsholders: Seq[AuthorDTO] = Seq.empty, @description("Date from which the copyright is valid") validFrom: Option[NDLADate], @description("Date to which the copyright is valid") validTo: Option[NDLADate], @description("Whether or not the content has been processed") processed: Boolean ) -object Copyright { - implicit val encoder: Encoder[Copyright] = deriveEncoder - implicit val decoder: Decoder[Copyright] = deriveDecoder +object CopyrightDTO { + implicit val encoder: Encoder[CopyrightDTO] = deriveEncoder + implicit val decoder: Decoder[CopyrightDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/DraftCopyright.scala b/common/src/main/scala/no/ndla/common/model/api/DraftCopyrightDTO.scala similarity index 68% rename from common/src/main/scala/no/ndla/common/model/api/DraftCopyright.scala rename to common/src/main/scala/no/ndla/common/model/api/DraftCopyrightDTO.scala index 7bc35368b7..5b745ad4f7 100644 --- a/common/src/main/scala/no/ndla/common/model/api/DraftCopyright.scala +++ b/common/src/main/scala/no/ndla/common/model/api/DraftCopyrightDTO.scala @@ -14,18 +14,18 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Description of copyright information") -case class DraftCopyright( - @description("Describes the license of the article") license: Option[License], +case class DraftCopyrightDTO( + @description("Describes the license of the article") license: Option[LicenseDTO], @description("Reference to where the article is procured") origin: Option[String], - @description("List of creators") creators: Seq[Author], - @description("List of processors") processors: Seq[Author], - @description("List of rightsholders") rightsholders: Seq[Author], + @description("List of creators") creators: Seq[AuthorDTO], + @description("List of processors") processors: Seq[AuthorDTO], + @description("List of rightsholders") rightsholders: Seq[AuthorDTO], @description("Date from which the copyright is valid") validFrom: Option[NDLADate], @description("Date to which the copyright is valid") validTo: Option[NDLADate], @description("Whether or not the content has been processed") processed: Boolean ) -object DraftCopyright { - implicit def encoder: Encoder[DraftCopyright] = deriveEncoder[DraftCopyright] - implicit def decoder: Decoder[DraftCopyright] = deriveDecoder[DraftCopyright] +object DraftCopyrightDTO { + implicit def encoder: Encoder[DraftCopyrightDTO] = deriveEncoder[DraftCopyrightDTO] + implicit def decoder: Decoder[DraftCopyrightDTO] = deriveDecoder[DraftCopyrightDTO] } diff --git a/common/src/main/scala/no/ndla/common/model/api/FrontPage.scala b/common/src/main/scala/no/ndla/common/model/api/FrontPage.scala deleted file mode 100644 index a6a049149b..0000000000 --- a/common/src/main/scala/no/ndla/common/model/api/FrontPage.scala +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Part of NDLA common - * Copyright (C) 2024 NDLA - * - * See LICENSE - */ - -package no.ndla.common.model.api - -import cats.implicits.toFunctorOps -import com.scalatsi.{TSIType, TSNamedType, TSType} -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.syntax.EncoderOps -import io.circe.{Decoder, Encoder} -import sttp.tapir.Schema.annotations.description - -import scala.annotation.unused - -@description("The Menu object") -case class Menu( - @description("Id of the article") articleId: Long, - @description("List of submenu objects") menu: List[MenuData], - @description("Hide this level in menu") hideLevel: Option[Boolean] -) extends MenuData - -@description("Object containing frontpage data") -case class FrontPage( - @description("Id of the frontpage") articleId: Long, - @description("List of Menu objects") menu: List[Menu] -) - -object FrontPage { - implicit val encodeFrontPage: Encoder[FrontPage] = deriveEncoder - implicit val decodeFrontPage: Decoder[FrontPage] = deriveDecoder -} - -object Menu { - implicit val encodeMenu: Encoder[Menu] = deriveEncoder - implicit val decodeMenu: Decoder[Menu] = deriveDecoder - - implicit val encodeMenuData: Encoder[MenuData] = Encoder.instance { case menu: Menu => menu.asJson } - implicit val decodeMenuData: Decoder[MenuData] = Decoder[Menu].widen - - implicit val menuTSI: TSIType[Menu] = { - @unused - implicit val menuData: TSNamedType[MenuData] = TSType.external[MenuData]("IMenuData") - TSType.fromCaseClass[Menu] - } -} - -sealed trait MenuData {} -object MenuData { - implicit val menuDataAlias: TSNamedType[MenuData] = TSType.alias[MenuData]("IMenuData", Menu.menuTSI.get) -} diff --git a/common/src/main/scala/no/ndla/common/model/api/FrontPageDTO.scala b/common/src/main/scala/no/ndla/common/model/api/FrontPageDTO.scala new file mode 100644 index 0000000000..10d1e63747 --- /dev/null +++ b/common/src/main/scala/no/ndla/common/model/api/FrontPageDTO.scala @@ -0,0 +1,54 @@ +/* + * Part of NDLA common + * Copyright (C) 2024 NDLA + * + * See LICENSE + */ + +package no.ndla.common.model.api + +import cats.implicits.toFunctorOps +import com.scalatsi.{TSIType, TSNamedType, TSType} +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.syntax.EncoderOps +import io.circe.{Decoder, Encoder} +import sttp.tapir.Schema.annotations.description + +import scala.annotation.unused + +@description("The Menu object") +case class MenuDTO( + @description("Id of the article") articleId: Long, + @description("List of submenu objects") menu: List[MenuDataDTO], + @description("Hide this level in menu") hideLevel: Option[Boolean] +) extends MenuDataDTO + +@description("Object containing frontpage data") +case class FrontPageDTO( + @description("Id of the frontpage") articleId: Long, + @description("List of Menu objects") menu: List[MenuDTO] +) + +object FrontPageDTO { + implicit val encodeFrontPage: Encoder[FrontPageDTO] = deriveEncoder + implicit val decodeFrontPage: Decoder[FrontPageDTO] = deriveDecoder +} + +object MenuDTO { + implicit val encodeMenu: Encoder[MenuDTO] = deriveEncoder + implicit val decodeMenu: Decoder[MenuDTO] = deriveDecoder + + implicit val encodeMenuData: Encoder[MenuDataDTO] = Encoder.instance { case menu: MenuDTO => menu.asJson } + implicit val decodeMenuData: Decoder[MenuDataDTO] = Decoder[MenuDTO].widen + + implicit val menuTSI: TSIType[MenuDTO] = { + @unused + implicit val menuData: TSNamedType[MenuDataDTO] = TSType.external[MenuDataDTO]("IMenuDataDTO") + TSType.fromCaseClass[MenuDTO] + } +} + +sealed trait MenuDataDTO {} +object MenuDataDTO { + implicit val menuDataAlias: TSNamedType[MenuDataDTO] = TSType.alias[MenuDataDTO]("IMenuDataDTO", MenuDTO.menuTSI.get) +} diff --git a/common/src/main/scala/no/ndla/common/model/api/License.scala b/common/src/main/scala/no/ndla/common/model/api/LicenseDTO.scala similarity index 74% rename from common/src/main/scala/no/ndla/common/model/api/License.scala rename to common/src/main/scala/no/ndla/common/model/api/LicenseDTO.scala index 1b330efa80..d265e4df78 100644 --- a/common/src/main/scala/no/ndla/common/model/api/License.scala +++ b/common/src/main/scala/no/ndla/common/model/api/LicenseDTO.scala @@ -13,13 +13,13 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import sttp.tapir.Schema.annotations.description @description("Description of license information") -case class License( +case class LicenseDTO( @description("The name of the license") license: String, @description("Description of the license") description: Option[String], @description("Url to where the license can be found") url: Option[String] ) -object License { - implicit def encoder: Encoder[License] = deriveEncoder[License] - implicit def decoder: Decoder[License] = deriveDecoder[License] +object LicenseDTO { + implicit def encoder: Encoder[LicenseDTO] = deriveEncoder[LicenseDTO] + implicit def decoder: Decoder[LicenseDTO] = deriveDecoder[LicenseDTO] } diff --git a/common/src/main/scala/no/ndla/common/model/api/MyNDLABundle.scala b/common/src/main/scala/no/ndla/common/model/api/MyNDLABundleDTO.scala similarity index 68% rename from common/src/main/scala/no/ndla/common/model/api/MyNDLABundle.scala rename to common/src/main/scala/no/ndla/common/model/api/MyNDLABundleDTO.scala index b3ebf49df5..55f6391e19 100644 --- a/common/src/main/scala/no/ndla/common/model/api/MyNDLABundle.scala +++ b/common/src/main/scala/no/ndla/common/model/api/MyNDLABundleDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import no.ndla.common.model.domain.ResourceType /** Data to pass between search-api and myndla-api for indexing */ -case class MyNDLABundle( +case class MyNDLABundleDTO( favorites: Map[String, Map[String, Long]] ) { @@ -27,17 +27,17 @@ case class MyNDLABundle( } } -object MyNDLABundle { - implicit val encoder: Encoder[MyNDLABundle] = deriveEncoder - implicit val decoder: Decoder[MyNDLABundle] = deriveDecoder +object MyNDLABundleDTO { + implicit val encoder: Encoder[MyNDLABundleDTO] = deriveEncoder + implicit val decoder: Decoder[MyNDLABundleDTO] = deriveDecoder } -case class FavoriteEntry( +case class FavoriteEntryDTO( id: String, resourceType: String ) -object FavoriteEntry { - implicit val encoder: Encoder[FavoriteEntry] = deriveEncoder - implicit val decoder: Decoder[FavoriteEntry] = deriveDecoder +object FavoriteEntryDTO { + implicit val encoder: Encoder[FavoriteEntryDTO] = deriveEncoder + implicit val decoder: Decoder[FavoriteEntryDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/RelatedContentLink.scala b/common/src/main/scala/no/ndla/common/model/api/RelatedContentLinkDTO.scala similarity index 68% rename from common/src/main/scala/no/ndla/common/model/api/RelatedContentLink.scala rename to common/src/main/scala/no/ndla/common/model/api/RelatedContentLinkDTO.scala index d9c4099fb8..af4fa0d934 100644 --- a/common/src/main/scala/no/ndla/common/model/api/RelatedContentLink.scala +++ b/common/src/main/scala/no/ndla/common/model/api/RelatedContentLinkDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("External link related to the article") -case class RelatedContentLink( +case class RelatedContentLinkDTO( @description("Title of the article") title: String, @description("The url to where the article can be viewed") url: String ) -object RelatedContentLink { - implicit def encoder: Encoder[RelatedContentLink] = deriveEncoder - implicit def decoder: Decoder[RelatedContentLink] = deriveDecoder +object RelatedContentLinkDTO { + implicit def encoder: Encoder[RelatedContentLinkDTO] = deriveEncoder + implicit def decoder: Decoder[RelatedContentLinkDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/SingleResourceStats.scala b/common/src/main/scala/no/ndla/common/model/api/SingleResourceStatsDTO.scala similarity index 67% rename from common/src/main/scala/no/ndla/common/model/api/SingleResourceStats.scala rename to common/src/main/scala/no/ndla/common/model/api/SingleResourceStatsDTO.scala index 7fada56047..c36764d16b 100644 --- a/common/src/main/scala/no/ndla/common/model/api/SingleResourceStats.scala +++ b/common/src/main/scala/no/ndla/common/model/api/SingleResourceStatsDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Stats for single resource") -case class SingleResourceStats( +case class SingleResourceStatsDTO( @description("Id of the resource") id: String, @description("The number of times the resource has been favorited") favourites: Long ) -object SingleResourceStats { - implicit val encoder: Encoder[SingleResourceStats] = deriveEncoder - implicit val decoder: Decoder[SingleResourceStats] = deriveDecoder +object SingleResourceStatsDTO { + implicit val encoder: Encoder[SingleResourceStatsDTO] = deriveEncoder + implicit val decoder: Decoder[SingleResourceStatsDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMeta.scala b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaDTO.scala similarity index 83% rename from common/src/main/scala/no/ndla/common/model/api/config/ConfigMeta.scala rename to common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaDTO.scala index b2874da9b3..aab1c8d8f3 100644 --- a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMeta.scala +++ b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaDTO.scala @@ -14,17 +14,17 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Describes configuration value.") -case class ConfigMeta( +case class ConfigMetaDTO( @description("Configuration key") key: String, @description("Configuration value.") value: Either[Boolean, List[String]], @description("Date of when configuration was last updated") updatedAt: NDLADate, @description("UserId of who last updated the configuration parameter.") updatedBy: String ) -object ConfigMeta { +object ConfigMetaDTO { import no.ndla.common.implicits._ implicit def eitherEnc: Encoder[Either[Boolean, List[String]]] = eitherEncoder implicit def eitherDec: Decoder[Either[Boolean, List[String]]] = eitherDecoder - implicit def encoder: Encoder[ConfigMeta] = deriveEncoder - implicit def decoder: Decoder[ConfigMeta] = deriveDecoder + implicit def encoder: Encoder[ConfigMetaDTO] = deriveEncoder + implicit def decoder: Decoder[ConfigMetaDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestricted.scala b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestrictedDTO.scala similarity index 77% rename from common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestricted.scala rename to common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestrictedDTO.scala index e7d6fe33b3..e145524471 100644 --- a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestricted.scala +++ b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaRestrictedDTO.scala @@ -13,15 +13,15 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Describes configuration value.") -case class ConfigMetaRestricted( +case class ConfigMetaRestrictedDTO( @description("Configuration key") key: String, @description("Configuration value.") value: Either[Boolean, List[String]] ) -object ConfigMetaRestricted { +object ConfigMetaRestrictedDTO { import no.ndla.common.implicits._ implicit def eitherEnc: Encoder[Either[Boolean, List[String]]] = eitherEncoder implicit def eitherDec: Decoder[Either[Boolean, List[String]]] = eitherDecoder - implicit def encoder: Encoder[ConfigMetaRestricted] = deriveEncoder - implicit def decoder: Decoder[ConfigMetaRestricted] = deriveDecoder + implicit def encoder: Encoder[ConfigMetaRestrictedDTO] = deriveEncoder + implicit def decoder: Decoder[ConfigMetaRestrictedDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValue.scala b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValueDTO.scala similarity index 56% rename from common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValue.scala rename to common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValueDTO.scala index 9225784533..6aacb0e7cc 100644 --- a/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValue.scala +++ b/common/src/main/scala/no/ndla/common/model/api/config/ConfigMetaValueDTO.scala @@ -14,25 +14,25 @@ import no.ndla.common.model.domain.config import no.ndla.common.model.domain.config.{BooleanValue, StringListValue} import sttp.tapir.Schema.annotations.description -case class ConfigMetaValue( +case class ConfigMetaValueDTO( @description("Value to set configuration param to.") value: Either[Boolean, List[String]] ) -object ConfigMetaValue { +object ConfigMetaValueDTO { import no.ndla.common.implicits._ implicit def eitherEnc: Encoder[Either[Boolean, List[String]]] = eitherEncoder implicit def eitherDec: Decoder[Either[Boolean, List[String]]] = eitherDecoder - implicit def encoder: Encoder[ConfigMetaValue] = deriveEncoder - implicit def decoder: Decoder[ConfigMetaValue] = deriveDecoder + implicit def encoder: Encoder[ConfigMetaValueDTO] = deriveEncoder + implicit def decoder: Decoder[ConfigMetaValueDTO] = deriveDecoder - def from(value: config.ConfigMetaValue): ConfigMetaValue = { + def from(value: config.ConfigMetaValue): ConfigMetaValueDTO = { value match { - case BooleanValue(value) => ConfigMetaValue(Left(value)) - case StringListValue(value) => ConfigMetaValue(Right(value)) + case BooleanValue(value) => ConfigMetaValueDTO(Left(value)) + case StringListValue(value) => ConfigMetaValueDTO(Right(value)) } } - def apply(value: Boolean): ConfigMetaValue = ConfigMetaValue(Left(value)) - def apply(value: List[String]): ConfigMetaValue = ConfigMetaValue(Right(value)) + def apply(value: Boolean): ConfigMetaValueDTO = ConfigMetaValueDTO(Left(value)) + def apply(value: List[String]): ConfigMetaValueDTO = ConfigMetaValueDTO(Right(value)) } diff --git a/common/src/main/scala/no/ndla/common/model/api/draft/Comment.scala b/common/src/main/scala/no/ndla/common/model/api/draft/CommentDTO.scala similarity index 82% rename from common/src/main/scala/no/ndla/common/model/api/draft/Comment.scala rename to common/src/main/scala/no/ndla/common/model/api/draft/CommentDTO.scala index a5ed5ff2dd..b4c76b0069 100644 --- a/common/src/main/scala/no/ndla/common/model/api/draft/Comment.scala +++ b/common/src/main/scala/no/ndla/common/model/api/draft/CommentDTO.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about a comment attached to an article") -case class Comment( +case class CommentDTO( @description("Id of the comment") id: String, @description("Content of the comment") content: String, @description("When the comment was created") created: NDLADate, @@ -22,7 +22,7 @@ case class Comment( @description("If the comment is solved or not") solved: Boolean ) -object Comment { - implicit def encoder: Encoder[Comment] = deriveEncoder - implicit def decoder: Decoder[Comment] = deriveDecoder +object CommentDTO { + implicit def encoder: Encoder[CommentDTO] = deriveEncoder + implicit def decoder: Decoder[CommentDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUser.scala b/common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUserDTO.scala similarity index 73% rename from common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUser.scala rename to common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUserDTO.scala index b2c8d0f442..8f2d902dd3 100644 --- a/common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUser.scala +++ b/common/src/main/scala/no/ndla/common/model/api/myndla/MyNDLAUserDTO.scala @@ -12,19 +12,19 @@ import io.circe.{Decoder, Encoder} import no.ndla.common.model.domain.myndla.ArenaGroup import sttp.tapir.Schema.annotations.description -case class MyNDLAGroup( +case class MyNDLAGroupDTO( @description("ID of the group") id: String, @description("Name of the group") displayName: String, @description("Is this the primary school") isPrimarySchool: Boolean, @description("ID of parent group") parentId: Option[String] ) -object MyNDLAGroup { - implicit def encoder: Encoder[MyNDLAGroup] = deriveEncoder - implicit def decoder: Decoder[MyNDLAGroup] = deriveDecoder +object MyNDLAGroupDTO { + implicit def encoder: Encoder[MyNDLAGroupDTO] = deriveEncoder + implicit def decoder: Decoder[MyNDLAGroupDTO] = deriveDecoder } -case class MyNDLAUser( +case class MyNDLAUserDTO( @description("ID of the user") id: Long, @description("FeideID of the user") feideId: String, @description("Username of the user") username: String, @@ -33,26 +33,26 @@ case class MyNDLAUser( @description("Favorite subjects of the user") favoriteSubjects: Seq[String], @description("User role") role: String, @description("User root organization") organization: String, - @description("User groups") groups: Seq[MyNDLAGroup], + @description("User groups") groups: Seq[MyNDLAGroupDTO], @description("Whether arena is explicitly enabled for the user") arenaEnabled: Boolean, @description("Whether users name is shared with folders or not") shareName: Boolean, @description("Arena user groups") arenaGroups: List[ArenaGroup] ) -object MyNDLAUser { - implicit def encoder: Encoder[MyNDLAUser] = deriveEncoder - implicit def decoder: Decoder[MyNDLAUser] = deriveDecoder +object MyNDLAUserDTO { + implicit def encoder: Encoder[MyNDLAUserDTO] = deriveEncoder + implicit def decoder: Decoder[MyNDLAUserDTO] = deriveDecoder } // format: off -case class UpdatedMyNDLAUser( +case class UpdatedMyNDLAUserDTO( @description("Favorite subjects of the user") favoriteSubjects: Option[Seq[String]], @description("Whether arena should explicitly be enabled for the user") arenaEnabled: Option[Boolean], @description("Whether users name should be shared with folder or not") shareName: Option[Boolean], @description("Which arena groups the user should be in, only modifiable by admins") arenaGroups: Option[List[ArenaGroup]] ) -object UpdatedMyNDLAUser { - implicit def encoder: Encoder[UpdatedMyNDLAUser] = deriveEncoder - implicit def decoder: Decoder[UpdatedMyNDLAUser] = deriveDecoder +object UpdatedMyNDLAUserDTO { + implicit def encoder: Encoder[UpdatedMyNDLAUserDTO] = deriveEncoder + implicit def decoder: Decoder[UpdatedMyNDLAUserDTO] = deriveDecoder } diff --git a/common/src/main/scala/no/ndla/common/model/api/package.scala b/common/src/main/scala/no/ndla/common/model/api/package.scala index 7918993f21..63e33b8a42 100644 --- a/common/src/main/scala/no/ndla/common/model/api/package.scala +++ b/common/src/main/scala/no/ndla/common/model/api/package.scala @@ -9,5 +9,5 @@ package no.ndla.common.model package object api { // We use the `Deletable` type to make json4s understand the difference between null and undefined/missing fields type Deletable[T] = Either[Null, Option[T]] - type RelatedContent = Either[api.RelatedContentLink, Long] + type RelatedContent = Either[api.RelatedContentLinkDTO, Long] } diff --git a/common/src/main/scala/no/ndla/common/model/domain/Author.scala b/common/src/main/scala/no/ndla/common/model/domain/Author.scala index b983fb90b5..ba940fe1d8 100644 --- a/common/src/main/scala/no/ndla/common/model/domain/Author.scala +++ b/common/src/main/scala/no/ndla/common/model/domain/Author.scala @@ -12,7 +12,7 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import no.ndla.common.model.api case class Author(`type`: String, name: String) { - def toApi: api.Author = api.Author( + def toApi: api.AuthorDTO = api.AuthorDTO( `type` = this.`type`, name = this.name ) diff --git a/common/src/main/scala/no/ndla/common/model/domain/config/ConfigMeta.scala b/common/src/main/scala/no/ndla/common/model/domain/config/ConfigMeta.scala index 9ac861c535..d2a2451e79 100644 --- a/common/src/main/scala/no/ndla/common/model/domain/config/ConfigMeta.scala +++ b/common/src/main/scala/no/ndla/common/model/domain/config/ConfigMeta.scala @@ -40,7 +40,7 @@ object ConfigMetaValue { ).reduceLeft(_ or _) } - def from(configMetaValue: api.config.ConfigMetaValue): ConfigMetaValue = configMetaValue.value match { + def from(configMetaValue: api.config.ConfigMetaValueDTO): ConfigMetaValue = configMetaValue.value match { case Left(value) => config.BooleanValue(value) case Right(value) => config.StringListValue(value) } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/controller/DraftConceptController.scala b/concept-api/src/main/scala/no/ndla/conceptapi/controller/DraftConceptController.scala index ea192abbdd..58d9146eb9 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/controller/DraftConceptController.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/controller/DraftConceptController.scala @@ -71,8 +71,8 @@ trait DraftConceptController { ) private def scrollSearchOr(scrollId: Option[String], language: String)( - orFunction: => Try[(ConceptSearchResult, DynamicHeaders)] - ): Try[(ConceptSearchResult, DynamicHeaders)] = + orFunction: => Try[(ConceptSearchResultDTO, DynamicHeaders)] + ): Try[(ConceptSearchResultDTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => draftConceptSearchService.scroll(scroll, language) match { @@ -103,7 +103,7 @@ trait DraftConceptController { responsibleId: List[String], conceptType: Option[String], aggregatePaths: List[String] - ): Try[(ConceptSearchResult, DynamicHeaders)] = { + ): Try[(ConceptSearchResultDTO, DynamicHeaders)] = { val settings = DraftSearchSettings( withIdIn = idList, searchLanguage = language, @@ -146,7 +146,7 @@ trait DraftConceptController { .in(language) .in(fallback) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) - .out(jsonBody[Concept]) + .out(jsonBody[ConceptDTO]) .errorOut(errorOutputsFor(404)) .withOptionalUser .serverLogicPure { user => @@ -158,7 +158,7 @@ trait DraftConceptController { def getAllConcepts: ServerEndpoint[Any, Eff] = endpoint.get .summary("Show all concepts") .description("Shows all concepts. You can search it too.") - .out(jsonBody[ConceptSearchResult]) + .out(jsonBody[ConceptSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400)) @@ -248,7 +248,7 @@ trait DraftConceptController { .out( oneOf[TagOutput]( oneOfVariant[SomeTagList]( - statusCode(StatusCode.Ok).and(jsonBody[List[SubjectTags]]).map(x => SomeTagList(x))(x => x.list) + statusCode(StatusCode.Ok).and(jsonBody[List[SubjectTagsDTO]]).map(x => SomeTagList(x))(x => x.list) ), oneOfDefaultVariant[SomeStringList]( statusCode(StatusCode.Ok).and(jsonBody[List[String]]).map(x => SomeStringList(x))(x => x.list) @@ -271,8 +271,8 @@ trait DraftConceptController { .in("search") .summary("Show all concepts") .description("Shows all concepts. You can search it too.") - .in(jsonBody[DraftConceptSearchParams]) - .out(jsonBody[ConceptSearchResult]) + .in(jsonBody[DraftConceptSearchParamsDTO]) + .out(jsonBody[ConceptSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 403, 404)) @@ -326,7 +326,7 @@ trait DraftConceptController { .description("Delete language from concept") .in(pathConceptId) .in(language) - .out(jsonBody[Concept]) + .out(jsonBody[ConceptDTO]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 403, 404)) .requirePermission(CONCEPT_API_WRITE) @@ -340,7 +340,7 @@ trait DraftConceptController { .summary("Update status of a concept") .description("Update status of a concept") .in(pathConceptId / "status" / pathStatus) - .out(jsonBody[Concept]) + .out(jsonBody[ConceptDTO]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 401, 403, 404)) .requirePermission(CONCEPT_API_WRITE) @@ -372,7 +372,7 @@ trait DraftConceptController { .in(pageSize) .in(pageNo) .in(language) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 403, 404)) .serverLogicPure { case (query, pageSize, pageNo, language) => @@ -383,8 +383,8 @@ trait DraftConceptController { def postNewConcept: ServerEndpoint[Any, Eff] = endpoint.post .summary("Create new concept") .description("Create new concept") - .in(jsonBody[NewConcept]) - .out(statusCode(StatusCode.Created).and(jsonBody[Concept])) + .in(jsonBody[NewConceptDTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[ConceptDTO])) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 403, 404)) .requirePermission(CONCEPT_API_WRITE) @@ -394,8 +394,8 @@ trait DraftConceptController { .summary("Update a concept") .description("Update a concept") .in(pathConceptId) - .in(jsonBody[UpdatedConcept]) - .out(jsonBody[Concept]) + .in(jsonBody[UpdatedConceptDTO]) + .out(jsonBody[ConceptDTO]) .out(header(HeaderNames.CacheControl, CacheDirective.Private.toString)) .errorOut(errorOutputsFor(400, 403, 404)) .requirePermission(CONCEPT_API_WRITE) diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/controller/InternController.scala b/concept-api/src/main/scala/no/ndla/conceptapi/controller/InternController.scala index 03e1db3a35..00898a799b 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/controller/InternController.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/controller/InternController.scala @@ -9,7 +9,7 @@ package no.ndla.conceptapi.controller import cats.implicits.* import no.ndla.common.model.domain.concept.Concept -import no.ndla.conceptapi.model.api.{ConceptDomainDump, ConceptImportResults, ErrorHandling, NotFoundException} +import no.ndla.conceptapi.model.api.{ConceptDomainDump, ConceptImportResultsDTO, ErrorHandling, NotFoundException} import no.ndla.conceptapi.repository.{DraftConceptRepository, PublishedConceptRepository} import no.ndla.conceptapi.service.search.{DraftConceptIndexService, IndexService, PublishedConceptIndexService} import no.ndla.conceptapi.service.{ConverterService, ImportService, ReadService} @@ -176,8 +176,8 @@ trait InternController { def importConcept: ServerEndpoint[Any, Eff] = endpoint.post .in("import" / "concept") - .out(jsonBody[ConceptImportResults]) - .errorOut(statusCode(StatusCode.InternalServerError).and(jsonBody[ConceptImportResults])) + .out(jsonBody[ConceptImportResultsDTO]) + .errorOut(statusCode(StatusCode.InternalServerError).and(jsonBody[ConceptImportResultsDTO])) .errorOutEither(statusCode(StatusCode.InternalServerError).and(stringBody)) .in(query[Boolean]("forceUpdate").default(false)) .withOptionalUser diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/controller/PublishedConceptController.scala b/concept-api/src/main/scala/no/ndla/conceptapi/controller/PublishedConceptController.scala index e8c8c306ab..100be78a97 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/controller/PublishedConceptController.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/controller/PublishedConceptController.scala @@ -54,8 +54,8 @@ trait PublishedConceptController { ) private def scrollSearchOr(scrollId: Option[String], language: String)( - orFunction: => Try[(ConceptSearchResult, DynamicHeaders)] - ): Try[(ConceptSearchResult, DynamicHeaders)] = + orFunction: => Try[(ConceptSearchResultDTO, DynamicHeaders)] + ): Try[(ConceptSearchResultDTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => publishedConceptSearchService.scroll(scroll, language) match { @@ -124,7 +124,7 @@ trait PublishedConceptController { .in(pathConceptId) .in(language) .in(fallback) - .out(jsonBody[Concept]) + .out(jsonBody[ConceptDTO]) .errorOut(errorOutputsFor(404)) .withOptionalUser .serverLogicPure { user => @@ -151,7 +151,7 @@ trait PublishedConceptController { .in(embedId) .in(conceptType) .in(aggregatePaths) - .out(jsonBody[ConceptSearchResult]) + .out(jsonBody[ConceptSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { @@ -200,8 +200,8 @@ trait PublishedConceptController { .summary("Show all concepts") .description("Shows all concepts. You can search it too.") .in("search") - .in(jsonBody[ConceptSearchParams]) - .out(jsonBody[ConceptSearchResult]) + .in(jsonBody[ConceptSearchParamsDTO]) + .out(jsonBody[ConceptSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400, 403, 404)) .serverLogicPure { searchParams => @@ -262,7 +262,7 @@ trait PublishedConceptController { .out( oneOf[TagOutput]( oneOfVariant[SomeTagList]( - statusCode(StatusCode.Ok).and(jsonBody[List[SubjectTags]]).map(x => SomeTagList(x))(x => x.list) + statusCode(StatusCode.Ok).and(jsonBody[List[SubjectTagsDTO]]).map(x => SomeTagList(x))(x => x.list) ), oneOfDefaultVariant[SomeStringList]( statusCode(StatusCode.Ok).and(jsonBody[List[String]]).map(x => SomeStringList(x))(x => x.list) diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Concept.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Concept.scala deleted file mode 100644 index 3c440a25e1..0000000000 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Concept.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Part of NDLA concept-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.conceptapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.DraftCopyright -import sttp.tapir.Schema.annotations.description - -@description("Information about the concept") -case class Concept( - // format: off - @description("The unique id of the concept") id: Long, - @description("The revision of the concept") revision: Int, - @description("Available titles for the concept") title: ConceptTitle, - @description("The content of the concept") content: Option[ConceptContent], - @description("Describes the copyright information for the concept") copyright: Option[DraftCopyright], - @description("URL for the source of the concept") source: Option[String], - @description("A meta image for the concept") metaImage: Option[ConceptMetaImage], - @description("Search tags the concept is tagged with") tags: Option[ConceptTags], - @description("Taxonomy subject ids the concept is connected to") subjectIds: Option[Set[String]], - @description("When the concept was created") created: NDLADate, - @description("When the concept was last updated") updated: NDLADate, - @description("List of people that updated this concept") updatedBy: Option[Seq[String]], - @description("All available languages of the current concept") supportedLanguages: Set[String], - @description("Article ids to which the concept is connected to") articleIds: Seq[Long], - @description("Status information of the concept") status: Status, - @description("A visual element for the concept") visualElement: Option[VisualElement], - @description("Object with data representing the editor responsible for this concept") responsible: Option[ConceptResponsible], - @description("Type of concept. 'concept', or 'gloss'") conceptType: String, - @description("Information about the gloss") glossData: Option[GlossData], - @description("Describes the changes made to the concept, only visible to editors") editorNotes: Option[Seq[EditorNote]], - // format: on -) - -object Concept { - implicit val encoder: Encoder[Concept] = deriveEncoder - implicit val decoder: Decoder[Concept] = deriveDecoder -} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptDTO.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptDTO.scala new file mode 100644 index 0000000000..47ede097a5 --- /dev/null +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptDTO.scala @@ -0,0 +1,45 @@ +/* + * Part of NDLA concept-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.conceptapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.DraftCopyrightDTO +import sttp.tapir.Schema.annotations.description + +@description("Information about the concept") +case class ConceptDTO( + // format: off + @description("The unique id of the concept") id: Long, + @description("The revision of the concept") revision: Int, + @description("Available titles for the concept") title: ConceptTitleDTO, + @description("The content of the concept") content: Option[ConceptContent], + @description("Describes the copyright information for the concept") copyright: Option[DraftCopyrightDTO], + @description("URL for the source of the concept") source: Option[String], + @description("A meta image for the concept") metaImage: Option[ConceptMetaImageDTO], + @description("Search tags the concept is tagged with") tags: Option[ConceptTagsDTO], + @description("Taxonomy subject ids the concept is connected to") subjectIds: Option[Set[String]], + @description("When the concept was created") created: NDLADate, + @description("When the concept was last updated") updated: NDLADate, + @description("List of people that updated this concept") updatedBy: Option[Seq[String]], + @description("All available languages of the current concept") supportedLanguages: Set[String], + @description("Article ids to which the concept is connected to") articleIds: Seq[Long], + @description("Status information of the concept") status: StatusDTO, + @description("A visual element for the concept") visualElement: Option[VisualElementDTO], + @description("Object with data representing the editor responsible for this concept") responsible: Option[ConceptResponsibleDTO], + @description("Type of concept. 'concept', or 'gloss'") conceptType: String, + @description("Information about the gloss") glossData: Option[GlossDataDTO], + @description("Describes the changes made to the concept, only visible to editors") editorNotes: Option[Seq[EditorNoteDTO]], + // format: on +) + +object ConceptDTO { + implicit val encoder: Encoder[ConceptDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptDTO] = deriveDecoder +} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResults.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResultsDTO.scala similarity index 60% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResults.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResultsDTO.scala index 571afa7f79..cb326ecc4d 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResults.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptImportResultsDTO.scala @@ -10,13 +10,13 @@ package no.ndla.conceptapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -case class ConceptImportResults( +case class ConceptImportResultsDTO( numSuccessfullyImportedConcepts: Int, totalAttemptedImportedConcepts: Int, warnings: Seq[String] ) -object ConceptImportResults { - implicit val encoder: Encoder[ConceptImportResults] = deriveEncoder - implicit val decoder: Decoder[ConceptImportResults] = deriveDecoder +object ConceptImportResultsDTO { + implicit val encoder: Encoder[ConceptImportResultsDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptImportResultsDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImage.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImageDTO.scala similarity index 74% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImage.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImageDTO.scala index 6c556fedd0..6f0d55ce97 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImage.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptMetaImageDTO.scala @@ -11,7 +11,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta image for the concept") -case class ConceptMetaImage( +case class ConceptMetaImageDTO( @description("The meta image url") url: String, @description("The alt text for the meta image") alt: String, @description( @@ -19,7 +19,7 @@ case class ConceptMetaImage( ) language: String ) -object ConceptMetaImage { - implicit val encoder: Encoder[ConceptMetaImage] = deriveEncoder - implicit val decoder: Decoder[ConceptMetaImage] = deriveDecoder +object ConceptMetaImageDTO { + implicit val encoder: Encoder[ConceptMetaImageDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptMetaImageDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsible.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsibleDTO.scala similarity index 71% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsible.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsibleDTO.scala index 045b7f201e..fdbe357637 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsible.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptResponsibleDTO.scala @@ -12,12 +12,12 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about the responsible") -case class ConceptResponsible( +case class ConceptResponsibleDTO( @description("NDLA ID of responsible editor") responsibleId: String, @description("Date of when the responsible editor was last updated") lastUpdated: NDLADate ) -object ConceptResponsible { - implicit val encoder: Encoder[ConceptResponsible] = deriveEncoder - implicit val decoder: Decoder[ConceptResponsible] = deriveDecoder +object ConceptResponsibleDTO { + implicit val encoder: Encoder[ConceptResponsibleDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptResponsibleDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParams.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParamsDTO.scala similarity index 89% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParams.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParamsDTO.scala index e0129c7ae8..fcd0feca28 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParams.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchParamsDTO.scala @@ -14,7 +14,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class ConceptSearchParams( +case class ConceptSearchParamsDTO( @description("The search query.") query: Option[String], @description("The ISO 639-1 language code describing language used in query-params.") language: Option[String], @description("The page number of the search hits to display.") page: Option[Int], @@ -32,7 +32,7 @@ case class ConceptSearchParams( @description("A list of index paths to aggregate over") aggregatePaths: Option[List[String]], ) -object ConceptSearchParams { - implicit val encoder: Encoder[ConceptSearchParams] = deriveEncoder - implicit val decoder: Decoder[ConceptSearchParams] = deriveDecoder +object ConceptSearchParamsDTO { + implicit val encoder: Encoder[ConceptSearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptSearchParamsDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResult.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResultDTO.scala similarity index 69% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResult.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResultDTO.scala index 42f8838c71..9ad657099b 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResult.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSearchResultDTO.scala @@ -9,22 +9,20 @@ package no.ndla.conceptapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.search.api.MultiSearchTermsAggregation +import no.ndla.search.api.MultiSearchTermsAggregationDTO import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class ConceptSearchResult( +case class ConceptSearchResultDTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ConceptSummary], - @description("The aggregated fields if specified in query") aggregations: Seq[ - MultiSearchTermsAggregation - ] + @description("The search results") results: Seq[ConceptSummaryDTO], + @description("The aggregated fields if specified in query") aggregations: Seq[MultiSearchTermsAggregationDTO] ) -object ConceptSearchResult { - implicit val encoder: Encoder[ConceptSearchResult] = deriveEncoder - implicit val decoder: Decoder[ConceptSearchResult] = deriveDecoder +object ConceptSearchResultDTO { + implicit val encoder: Encoder[ConceptSearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptSearchResultDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummary.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummary.scala deleted file mode 100644 index eaeeb94c1f..0000000000 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummary.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Part of NDLA concept-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.conceptapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.DraftCopyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Information about the concept") -case class ConceptSummary( - @description("The unique id of the concept") id: Long, - @description("Available titles for the concept") title: ConceptTitle, - @description("The content of the concept in available languages") content: ConceptContent, - @description("The metaImage of the concept") metaImage: ConceptMetaImage, - @description("Search tags the concept is tagged with") tags: Option[ConceptTags], - @description("Taxonomy subject ids the concept is connected to") subjectIds: Option[Set[String]], - @description("All available languages of the current concept") supportedLanguages: Seq[String], - @description("The time when the article was last updated") lastUpdated: NDLADate, - @description("When the concept was created") created: NDLADate, - @description("Status information of the concept") status: Status, - @description("List of people that edited the concept") updatedBy: Seq[String], - @description("Describes the license of the concept") license: Option[String], - @description("Describes the copyright of the concept") copyright: Option[DraftCopyright], - @description("A visual element for the concept") visualElement: Option[VisualElement], - @description("Article ids to which the concept is connected to") articleIds: Seq[Long], - @description("URL for the source of the concept") source: Option[String], - @description("Object with data representing the editor responsible for this concept") responsible: Option[ConceptResponsible], - @description("Type of concept. 'concept', or 'gloss'") conceptType: String, - @description("Information about the gloss") glossData: Option[GlossData], - @description("A name of the concepts subject(s)") subjectName: Option[String], - @description("A translated name of the concept type") conceptTypeName: String -) -// format: on - -object ConceptSummary { - implicit val encoder: Encoder[ConceptSummary] = deriveEncoder - implicit val decoder: Decoder[ConceptSummary] = deriveDecoder -} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummaryDTO.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummaryDTO.scala new file mode 100644 index 0000000000..f0e48722f1 --- /dev/null +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptSummaryDTO.scala @@ -0,0 +1,46 @@ +/* + * Part of NDLA concept-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.conceptapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.DraftCopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Information about the concept") +case class ConceptSummaryDTO( + @description("The unique id of the concept") id: Long, + @description("Available titles for the concept") title: ConceptTitleDTO, + @description("The content of the concept in available languages") content: ConceptContent, + @description("The metaImage of the concept") metaImage: ConceptMetaImageDTO, + @description("Search tags the concept is tagged with") tags: Option[ConceptTagsDTO], + @description("Taxonomy subject ids the concept is connected to") subjectIds: Option[Set[String]], + @description("All available languages of the current concept") supportedLanguages: Seq[String], + @description("The time when the article was last updated") lastUpdated: NDLADate, + @description("When the concept was created") created: NDLADate, + @description("Status information of the concept") status: StatusDTO, + @description("List of people that edited the concept") updatedBy: Seq[String], + @description("Describes the license of the concept") license: Option[String], + @description("Describes the copyright of the concept") copyright: Option[DraftCopyrightDTO], + @description("A visual element for the concept") visualElement: Option[VisualElementDTO], + @description("Article ids to which the concept is connected to") articleIds: Seq[Long], + @description("URL for the source of the concept") source: Option[String], + @description("Object with data representing the editor responsible for this concept") responsible: Option[ConceptResponsibleDTO], + @description("Type of concept. 'concept', or 'gloss'") conceptType: String, + @description("Information about the gloss") glossData: Option[GlossDataDTO], + @description("A name of the concepts subject(s)") subjectName: Option[String], + @description("A translated name of the concept type") conceptTypeName: String +) +// format: on + +object ConceptSummaryDTO { + implicit val encoder: Encoder[ConceptSummaryDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptSummaryDTO] = deriveDecoder +} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTags.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTagsDTO.scala similarity index 73% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTags.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTagsDTO.scala index 7af93df380..45fc1a2615 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTags.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTagsDTO.scala @@ -12,14 +12,14 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta image for the concept") -case class ConceptTags( +case class ConceptTagsDTO( @description("Searchable tags") tags: Seq[String], @description( "The ISO 639-1 language code describing which concept translation these tags belongs to" ) language: String ) -object ConceptTags { - implicit val encoder: Encoder[ConceptTags] = deriveEncoder - implicit val decoder: Decoder[ConceptTags] = deriveDecoder +object ConceptTagsDTO { + implicit val encoder: Encoder[ConceptTagsDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptTagsDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitle.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitleDTO.scala similarity index 70% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitle.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitleDTO.scala index ab807d8a40..f485e8be9a 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitle.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ConceptTitleDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about the concept") -case class ConceptTitle( +case class ConceptTitleDTO( @description("The title of this concept") title: String, @description("The language of this concept") language: String ) -object ConceptTitle { - implicit val encoder: Encoder[ConceptTitle] = deriveEncoder - implicit val decoder: Decoder[ConceptTitle] = deriveDecoder +object ConceptTitleDTO { + implicit val encoder: Encoder[ConceptTitleDTO] = deriveEncoder + implicit val decoder: Decoder[ConceptTitleDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParams.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParamsDTO.scala similarity index 90% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParams.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParamsDTO.scala index 3c83da1726..40dfd2a7af 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParams.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/DraftConceptSearchParamsDTO.scala @@ -14,7 +14,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class DraftConceptSearchParams( +case class DraftConceptSearchParamsDTO( @description("The search query.") query: Option[String], @description("The ISO 639-1 language code describing language used in query-params.") language: Option[String], @description("The page number of the search hits to display.") page: Option[Int], @@ -34,7 +34,7 @@ case class DraftConceptSearchParams( @description("A list of index paths to aggregate over") aggregatePaths: Option[List[String]], ) -object DraftConceptSearchParams{ - implicit val encoder: Encoder[DraftConceptSearchParams] = deriveEncoder - implicit val decoder: Decoder[DraftConceptSearchParams] = deriveDecoder +object DraftConceptSearchParamsDTO{ + implicit val encoder: Encoder[DraftConceptSearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[DraftConceptSearchParamsDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNote.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNoteDTO.scala similarity index 77% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNote.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNoteDTO.scala index 60da471ad3..1ab1c02bb0 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNote.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/EditorNoteDTO.scala @@ -13,14 +13,14 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about the editorial notes") -case class EditorNote( +case class EditorNoteDTO( @description("Editorial note") note: String, @description("User which saved the note") updatedBy: String, - @description("Status of concept at saved time") status: Status, + @description("Status of concept at saved time") status: StatusDTO, @description("Timestamp of when note was saved") timestamp: NDLADate ) -object EditorNote { - implicit val encoder: Encoder[EditorNote] = deriveEncoder - implicit val decoder: Decoder[EditorNote] = deriveDecoder +object EditorNoteDTO { + implicit val encoder: Encoder[EditorNoteDTO] = deriveEncoder + implicit val decoder: Decoder[EditorNoteDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Gloss.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Gloss.scala index 18d31842b4..563f6e9d6b 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Gloss.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Gloss.scala @@ -13,28 +13,28 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Information about the gloss example") -case class GlossExample( +case class GlossExampleDTO( @description("Example use of the gloss") example: String, @description("Language of the example") language: String, @description("Alternative writing of the example") transcriptions: Map[String, String], ) -object GlossExample { - implicit val encoder: Encoder[GlossExample] = deriveEncoder - implicit val decoder: Decoder[GlossExample] = deriveDecoder +object GlossExampleDTO { + implicit val encoder: Encoder[GlossExampleDTO] = deriveEncoder + implicit val decoder: Decoder[GlossExampleDTO] = deriveDecoder } @description("Information about the gloss data") -case class GlossData( +case class GlossDataDTO( @description("The gloss itself") gloss: String, @description("Word class / part of speech, ex. noun, adjective, verb, adverb, ...") wordClass: String, @description("Original language of the gloss") originalLanguage: String, @description("Alternative writing of the gloss") transcriptions: Map[String, String], - @description("List of examples of how the gloss can be used") examples: List[List[GlossExample]], + @description("List of examples of how the gloss can be used") examples: List[List[GlossExampleDTO]], ) // format: on -object GlossData { - implicit val encoder: Encoder[GlossData] = deriveEncoder - implicit val decoder: Decoder[GlossData] = deriveDecoder +object GlossDataDTO { + implicit val encoder: Encoder[GlossDataDTO] = deriveEncoder + implicit val decoder: Decoder[GlossDataDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConcept.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConcept.scala deleted file mode 100644 index 554d771534..0000000000 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConcept.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Part of NDLA concept-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.conceptapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.DraftCopyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Information about the concept") -case class NewConcept( - @description("The language of this concept") language: String, - @description("Available titles for the concept") title: String, - @description("The content of the concept") content: Option[String], - @description("Describes the copyright information for the concept") copyright: Option[DraftCopyright], - @description("An image-api ID for the concept meta image") metaImage: Option[NewConceptMetaImage], - @description("A list of searchable tags") tags: Option[Seq[String]], - @description("A list of taxonomy subject ids the concept is connected to") subjectIds: Option[Seq[String]], - @description("Article id to which the concept is connected to") articleIds: Option[Seq[Long]], - @description("A visual element for the concept. May be anything from an image to a video or H5P") visualElement: Option[String], - @description("NDLA ID representing the editor responsible for this article") responsibleId: Option[String], - @description("Type of concept. 'concept', or 'gloss'") conceptType: String, - @description("Information about the gloss") glossData: Option[GlossData], -) -// format: on - -object NewConcept { - implicit val encoder: Encoder[NewConcept] = deriveEncoder - implicit val decoder: Decoder[NewConcept] = deriveDecoder -} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptDTO.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptDTO.scala new file mode 100644 index 0000000000..fffd4ee4f2 --- /dev/null +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptDTO.scala @@ -0,0 +1,36 @@ +/* + * Part of NDLA concept-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.conceptapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.api.DraftCopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Information about the concept") +case class NewConceptDTO( + @description("The language of this concept") language: String, + @description("Available titles for the concept") title: String, + @description("The content of the concept") content: Option[String], + @description("Describes the copyright information for the concept") copyright: Option[DraftCopyrightDTO], + @description("An image-api ID for the concept meta image") metaImage: Option[NewConceptMetaImageDTO], + @description("A list of searchable tags") tags: Option[Seq[String]], + @description("A list of taxonomy subject ids the concept is connected to") subjectIds: Option[Seq[String]], + @description("Article id to which the concept is connected to") articleIds: Option[Seq[Long]], + @description("A visual element for the concept. May be anything from an image to a video or H5P") visualElement: Option[String], + @description("NDLA ID representing the editor responsible for this article") responsibleId: Option[String], + @description("Type of concept. 'concept', or 'gloss'") conceptType: String, + @description("Information about the gloss") glossData: Option[GlossDataDTO], +) +// format: on + +object NewConceptDTO { + implicit val encoder: Encoder[NewConceptDTO] = deriveEncoder + implicit val decoder: Decoder[NewConceptDTO] = deriveDecoder +} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImage.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImageDTO.scala similarity index 65% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImage.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImageDTO.scala index cf9e0e1edb..e0b30e579d 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImage.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/NewConceptMetaImageDTO.scala @@ -10,12 +10,12 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description -case class NewConceptMetaImage( +case class NewConceptMetaImageDTO( @description("The image-api id of the meta image") id: String, @description("The alt text of the meta image") alt: String ) -object NewConceptMetaImage { - implicit val encoder: Encoder[NewConceptMetaImage] = deriveEncoder - implicit val decoder: Decoder[NewConceptMetaImage] = deriveDecoder +object NewConceptMetaImageDTO { + implicit val encoder: Encoder[NewConceptMetaImageDTO] = deriveEncoder + implicit val decoder: Decoder[NewConceptMetaImageDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Status.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/StatusDTO.scala similarity index 75% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/Status.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/StatusDTO.scala index 3eda3c48de..16c90be00c 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/Status.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/StatusDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Status information for the concept") -case class Status( +case class StatusDTO( @description("The current status of the concept") current: String, @description("Previous statuses this concept has been in") other: Seq[String] ) -object Status { - implicit val encoder: Encoder[Status] = deriveEncoder - implicit val decoder: Decoder[Status] = deriveDecoder +object StatusDTO { + implicit val encoder: Encoder[StatusDTO] = deriveEncoder + implicit val decoder: Decoder[StatusDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTags.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTagsDTO.scala similarity index 64% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTags.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTagsDTO.scala index b8ffbe9a45..99de37f146 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTags.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/SubjectTagsDTO.scala @@ -12,17 +12,17 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description sealed trait TagOutput -case class SomeStringList(list: List[String]) extends TagOutput -case class SomeTagList(list: List[SubjectTags]) extends TagOutput +case class SomeStringList(list: List[String]) extends TagOutput +case class SomeTagList(list: List[SubjectTagsDTO]) extends TagOutput @description("A subject id, and list of tags used in the subject") -case class SubjectTags( +case class SubjectTagsDTO( @description("Taxonomy id of the subject") subjectId: String, @description("List of tags used in the subject") tags: List[String], @description("Language for the specified tags") language: String ) -object SubjectTags { - implicit val encoder: Encoder[SubjectTags] = deriveEncoder - implicit val decoder: Decoder[SubjectTags] = deriveDecoder +object SubjectTagsDTO { + implicit val encoder: Encoder[SubjectTagsDTO] = deriveEncoder + implicit val decoder: Decoder[SubjectTagsDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResult.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResultDTO.scala similarity index 77% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResult.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResultDTO.scala index bd93862527..5909470b9e 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResult.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/TagsSearchResultDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about tags-search-results") -case class TagsSearchResult( +case class TagsSearchResultDTO( @description("The total number of tags matching this query") totalCount: Int, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @@ -20,7 +20,7 @@ case class TagsSearchResult( @description("The search results") results: Seq[String] ) -object TagsSearchResult { - implicit val encoder: Encoder[TagsSearchResult] = deriveEncoder - implicit val decoder: Decoder[TagsSearchResult] = deriveDecoder +object TagsSearchResultDTO { + implicit val encoder: Encoder[TagsSearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[TagsSearchResultDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConcept.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConcept.scala deleted file mode 100644 index bdf3f03a71..0000000000 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConcept.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Part of NDLA concept-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.conceptapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.{DraftCopyright, UpdateOrDelete} -import sttp.tapir.Schema.annotations.description -import com.scalatsi.TypescriptType.{TSNull, TSUndefined, TSUnion} -import com.scalatsi._ - -// format: off -@description("Information about the concept") -case class UpdatedConcept( - @description("The language of this concept") language: String, - @description("Available titles for the concept") title: Option[String], - @description("The content of the concept") content: Option[String], - @description("An image-api ID for the concept meta image") metaImage: UpdateOrDelete[NewConceptMetaImage], - @description("Describes the copyright information for the concept") copyright: Option[DraftCopyright], - @description("A list of searchable tags") tags: Option[Seq[String]], - @description("A list of taxonomy subject ids the concept is connected to") subjectIds: Option[Seq[String]], - @description("Article id to which the concept is connected to") articleIds: Option[Seq[Long]], - @description("The new status of the concept") status: Option[String], - @description("A visual element for the concept. May be anything from an image to a video or H5P") visualElement: Option[String], - @description("NDLA ID representing the editor responsible for this article") responsibleId: UpdateOrDelete[String], - @description("Type of concept. 'concept', or 'gloss'") conceptType: Option[String], - @description("Information about the gloss") glossData: Option[GlossData], -) -// format: on - -object UpdatedConcept { - implicit val encoder: Encoder[UpdatedConcept] = UpdateOrDelete.filterMarkers(deriveEncoder) - implicit val decoder: Decoder[UpdatedConcept] = deriveDecoder - - implicit val typescriptUpdatedArticle: TSType[UpdatedConcept] = TSType.fromCaseClass[UpdatedConcept] - implicit def typescriptNewMetaImage: TSType[NewConceptMetaImage] = TSType.fromCaseClass[NewConceptMetaImage] - implicit def typescriptNewMetaImageUnion: TSType[UpdateOrDelete[NewConceptMetaImage]] = { - TSType.alias[UpdateOrDelete[NewConceptMetaImage]]( - "UpdateOrDeleteNewConceptMetaImage", - TSUnion(Seq(TSNull, TSUndefined, typescriptNewMetaImage.get)) - ) - } -} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConceptDTO.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConceptDTO.scala new file mode 100644 index 0000000000..fe7c1bb353 --- /dev/null +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/UpdatedConceptDTO.scala @@ -0,0 +1,48 @@ +/* + * Part of NDLA concept-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.conceptapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.api.{DraftCopyrightDTO, UpdateOrDelete} +import sttp.tapir.Schema.annotations.description +import com.scalatsi.TypescriptType.{TSNull, TSUndefined, TSUnion} +import com.scalatsi._ + +// format: off +@description("Information about the concept") +case class UpdatedConceptDTO( + @description("The language of this concept") language: String, + @description("Available titles for the concept") title: Option[String], + @description("The content of the concept") content: Option[String], + @description("An image-api ID for the concept meta image") metaImage: UpdateOrDelete[NewConceptMetaImageDTO], + @description("Describes the copyright information for the concept") copyright: Option[DraftCopyrightDTO], + @description("A list of searchable tags") tags: Option[Seq[String]], + @description("A list of taxonomy subject ids the concept is connected to") subjectIds: Option[Seq[String]], + @description("Article id to which the concept is connected to") articleIds: Option[Seq[Long]], + @description("The new status of the concept") status: Option[String], + @description("A visual element for the concept. May be anything from an image to a video or H5P") visualElement: Option[String], + @description("NDLA ID representing the editor responsible for this article") responsibleId: UpdateOrDelete[String], + @description("Type of concept. 'concept', or 'gloss'") conceptType: Option[String], + @description("Information about the gloss") glossData: Option[GlossDataDTO], +) +// format: on + +object UpdatedConceptDTO { + implicit val encoder: Encoder[UpdatedConceptDTO] = UpdateOrDelete.filterMarkers(deriveEncoder) + implicit val decoder: Decoder[UpdatedConceptDTO] = deriveDecoder + + implicit val typescriptUpdatedArticle: TSType[UpdatedConceptDTO] = TSType.fromCaseClass[UpdatedConceptDTO] + implicit def typescriptNewMetaImage: TSType[NewConceptMetaImageDTO] = TSType.fromCaseClass[NewConceptMetaImageDTO] + implicit def typescriptNewMetaImageUnion: TSType[UpdateOrDelete[NewConceptMetaImageDTO]] = { + TSType.alias[UpdateOrDelete[NewConceptMetaImageDTO]]( + "UpdateOrDeleteNewConceptMetaImageDTO", + TSUnion(Seq(TSNull, TSUndefined, typescriptNewMetaImage.get)) + ) + } +} diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ValidationError.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ValidationError.scala deleted file mode 100644 index 01aa40b7e5..0000000000 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/ValidationError.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Part of NDLA concept-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.conceptapi.model.api - -import no.ndla.common.errors.ValidationMessage -import sttp.tapir.Schema.annotations.description - -import java.time.LocalDateTime - -@description("Information about validation errors") -case class ValidationError( - @description("Code stating the type of error") code: String, - @description("Description of the error") description: String, - @description("List of validation messages") messages: Seq[ValidationMessage], - @description("When the error occured") occuredAt: LocalDateTime = LocalDateTime.now() -) diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElement.scala b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElementDTO.scala similarity index 76% rename from concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElement.scala rename to concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElementDTO.scala index 36a18493b0..e3dbf7d5d9 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElement.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/model/api/VisualElementDTO.scala @@ -13,13 +13,13 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Description of a visual element") -case class VisualElement( +case class VisualElementDTO( @description("Html containing the visual element. May contain any legal html element, including the embed-tag") visualElement: String, @description("The ISO 639-1 language code describing which article translation this visual element belongs to") language: String ) // format: on -object VisualElement { - implicit val encoder: Encoder[VisualElement] = deriveEncoder - implicit val decoder: Decoder[VisualElement] = deriveDecoder +object VisualElementDTO { + implicit val encoder: Encoder[VisualElementDTO] = deriveEncoder + implicit val decoder: Decoder[VisualElementDTO] = deriveDecoder } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/ConverterService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/ConverterService.scala index 05f853ade9..0be2ed7fe2 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/ConverterService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/ConverterService.scala @@ -29,7 +29,7 @@ import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.model.api.{Delete, Missing, UpdateWith} import no.ndla.common.model.{api as commonApi, domain as commonDomain} import no.ndla.conceptapi.Props -import no.ndla.conceptapi.model.api.{ConceptTags, NotFoundException} +import no.ndla.conceptapi.model.api.{ConceptTagsDTO, NotFoundException} import no.ndla.conceptapi.model.api import no.ndla.conceptapi.repository.DraftConceptRepository import no.ndla.language.Language.{AllLanguages, UnknownLanguage, findByLanguageOrBestEffort, mergeLanguageFields} @@ -56,19 +56,19 @@ trait ConverterService { language: String, fallback: Boolean, user: Option[TokenUser] - ): Try[api.Concept] = { + ): Try[api.ConceptDTO] = { val isLanguageNeutral = concept.supportedLanguages.contains(UnknownLanguage.toString) && concept.supportedLanguages.size == 1 if (concept.supportedLanguages.contains(language) || fallback || isLanguageNeutral || language == AllLanguages) { val title = findByLanguageOrBestEffort(concept.title, language) .map(toApiConceptTitle) - .getOrElse(api.ConceptTitle("", UnknownLanguage.toString)) + .getOrElse(api.ConceptTitleDTO("", UnknownLanguage.toString)) val content = findByLanguageOrBestEffort(concept.content, language) .map(toApiConceptContent) .getOrElse(api.ConceptContent("", "", UnknownLanguage.toString)) val metaImage = findByLanguageOrBestEffort(concept.metaImage, language) .map(toApiMetaImage) - .getOrElse(api.ConceptMetaImage("", "", UnknownLanguage.toString)) + .getOrElse(api.ConceptMetaImageDTO("", "", UnknownLanguage.toString)) val tags = findByLanguageOrBestEffort(concept.tags, language).map(toApiTags) @@ -79,7 +79,7 @@ trait ConverterService { val editorNotes = Option.when(user.hasPermission(CONCEPT_API_WRITE))(concept.editorNotes.map(toApiEditorNote)) Success( - api.Concept( + api.ConceptDTO( id = concept.id.get, revision = concept.revision.getOrElse(-1), title = title, @@ -112,14 +112,14 @@ trait ConverterService { } } - def toApiGlossData(domainGlossData: Option[GlossData]): Option[api.GlossData] = { + def toApiGlossData(domainGlossData: Option[GlossData]): Option[api.GlossDataDTO] = { domainGlossData.map(glossData => - api.GlossData( + api.GlossDataDTO( gloss = glossData.gloss, wordClass = glossData.wordClass.entryName, examples = glossData.examples.map(ge => ge.map(g => - api.GlossExample( + api.GlossExampleDTO( example = g.example, language = g.language, transcriptions = g.transcriptions @@ -132,14 +132,14 @@ trait ConverterService { ) } - def toApiStatus(status: Status): api.Status = { - api.Status( + def toApiStatus(status: Status): api.StatusDTO = { + api.StatusDTO( current = status.current.toString, other = status.other.map(_.toString).toSeq ) } private def toApiEditorNote(editorNote: ConceptEditorNote) = { - api.EditorNote( + api.EditorNoteDTO( note = editorNote.note, updatedBy = editorNote.user, status = toApiStatus(editorNote.status), @@ -147,15 +147,15 @@ trait ConverterService { ) } - def toApiTags(tags: Tag): ConceptTags = { - api.ConceptTags( + def toApiTags(tags: Tag): ConceptTagsDTO = { + api.ConceptTagsDTO( tags.tags, tags.language ) } - private def toApiCopyright(copyright: commonDomain.draft.DraftCopyright): commonApi.DraftCopyright = { - commonApi.DraftCopyright( + private def toApiCopyright(copyright: commonDomain.draft.DraftCopyright): commonApi.DraftCopyrightDTO = { + commonApi.DraftCopyrightDTO( copyright.license.flatMap(toMaybeApiLicense), copyright.origin, copyright.creators.map(_.toApi), @@ -167,37 +167,37 @@ trait ConverterService { ) } - private def toMaybeApiLicense(shortLicense: String): Option[commonApi.License] = { + private def toMaybeApiLicense(shortLicense: String): Option[commonApi.LicenseDTO] = { getLicense(shortLicense) - .map(l => commonApi.License(l.license.toString, Option(l.description), l.url)) + .map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)) } - def toApiLicense(maybeShortLicense: Option[String]): commonApi.License = - maybeShortLicense.flatMap(toMaybeApiLicense).getOrElse(commonApi.License("unknown", None, None)) + def toApiLicense(maybeShortLicense: Option[String]): commonApi.LicenseDTO = + maybeShortLicense.flatMap(toMaybeApiLicense).getOrElse(commonApi.LicenseDTO("unknown", None, None)) - def toApiLicense(shortLicense: String): commonApi.License = - toMaybeApiLicense(shortLicense).getOrElse(commonApi.License("unknown", None, None)) + def toApiLicense(shortLicense: String): commonApi.LicenseDTO = + toMaybeApiLicense(shortLicense).getOrElse(commonApi.LicenseDTO("unknown", None, None)) - def toApiConceptTitle(title: Title): api.ConceptTitle = - api.ConceptTitle(title.title, title.language) + def toApiConceptTitle(title: Title): api.ConceptTitleDTO = + api.ConceptTitleDTO(title.title, title.language) def toApiConceptContent(content: ConceptContent): api.ConceptContent = api.ConceptContent(Jsoup.parseBodyFragment(content.content).body().text(), content.content, content.language) - def toApiMetaImage(metaImage: ConceptMetaImage): api.ConceptMetaImage = - api.ConceptMetaImage( + def toApiMetaImage(metaImage: ConceptMetaImage): api.ConceptMetaImageDTO = + api.ConceptMetaImageDTO( s"${externalApiUrls("raw-image")}/${metaImage.imageId}", metaImage.altText, metaImage.language ) - def toApiVisualElement(visualElement: VisualElement): api.VisualElement = - api.VisualElement(converterService.addUrlOnElement(visualElement.visualElement), visualElement.language) + def toApiVisualElement(visualElement: VisualElement): api.VisualElementDTO = + api.VisualElementDTO(converterService.addUrlOnElement(visualElement.visualElement), visualElement.language) - private def toApiConceptResponsible(responsible: Responsible): api.ConceptResponsible = - api.ConceptResponsible(responsibleId = responsible.responsibleId, lastUpdated = responsible.lastUpdated) + private def toApiConceptResponsible(responsible: Responsible): api.ConceptResponsibleDTO = + api.ConceptResponsibleDTO(responsibleId = responsible.responsibleId, lastUpdated = responsible.lastUpdated) - def toDomainGlossData(apiGlossData: Option[api.GlossData]): Try[Option[GlossData]] = { + def toDomainGlossData(apiGlossData: Option[api.GlossDataDTO]): Try[Option[GlossData]] = { apiGlossData .map(glossData => WordClass.valueOfOrError(glossData.wordClass) match { @@ -221,7 +221,7 @@ trait ConverterService { .sequence } - def toDomainConcept(concept: api.NewConcept, userInfo: TokenUser): Try[DomainConcept] = { + def toDomainConcept(concept: api.NewConceptDTO, userInfo: TokenUser): Try[DomainConcept] = { val conceptType = ConceptType.valueOfOrError(concept.conceptType).getOrElse(ConceptType.CONCEPT) val content = concept.content .map(content => Seq(model.domain.concept.ConceptContent(content, concept.language))) @@ -284,7 +284,7 @@ trait ConverterService { def toDomainConcept( toMergeInto: DomainConcept, - updateConcept: api.UpdatedConcept, + updateConcept: api.UpdatedConceptDTO, userInfo: TokenUser ): Try[DomainConcept] = { val domainTitle = updateConcept.title @@ -348,7 +348,7 @@ trait ConverterService { def updateStatus(status: ConceptStatus, concept: DomainConcept, user: TokenUser): Try[DomainConcept] = StateTransitionRules.doTransition(concept, status, user) - def toDomainConcept(id: Long, concept: api.UpdatedConcept, userInfo: TokenUser): DomainConcept = { + def toDomainConcept(id: Long, concept: api.UpdatedConceptDTO, userInfo: TokenUser): DomainConcept = { val lang = concept.language val newMetaImage = concept.metaImage match { @@ -398,7 +398,7 @@ trait ConverterService { ) } - private def toDomainCopyright(copyright: commonApi.DraftCopyright): commonDomain.draft.DraftCopyright = + private def toDomainCopyright(copyright: commonApi.DraftCopyrightDTO): commonDomain.draft.DraftCopyright = commonDomain.draft.DraftCopyright( copyright.license.map(_.license), copyright.origin, @@ -416,8 +416,8 @@ trait ConverterService { pageSize: Int, offset: Int, language: String - ): api.TagsSearchResult = { - api.TagsSearchResult(tagsCount, offset, pageSize, language, tags) + ): api.TagsSearchResultDTO = { + api.TagsSearchResultDTO(tagsCount, offset, pageSize, language, tags) } def stateTransitionsToApi(user: TokenUser): Map[String, List[String]] = diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/ImportService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/ImportService.scala index a88efbd298..ebb9d060de 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/ImportService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/ImportService.scala @@ -10,7 +10,7 @@ package no.ndla.conceptapi.service import cats.implicits._ import com.typesafe.scalalogging.StrictLogging import no.ndla.conceptapi.integration.ArticleApiClient -import no.ndla.conceptapi.model.api.ConceptImportResults +import no.ndla.conceptapi.model.api.ConceptImportResultsDTO import no.ndla.conceptapi.repository.DraftConceptRepository import no.ndla.network.tapir.auth.TokenUser @@ -22,7 +22,7 @@ trait ImportService { class ImportService extends StrictLogging { - def importConcepts(forceUpdate: Boolean, user: TokenUser): Try[ConceptImportResults] = { + def importConcepts(forceUpdate: Boolean, user: TokenUser): Try[ConceptImportResultsDTO] = { val start = System.currentTimeMillis() val pageStream = articleApiClient.getChunks(user) pageStream @@ -48,7 +48,7 @@ trait ImportService { val usedTime = System.currentTimeMillis() - startTime logger.info(s"Successfully saved $totalSaved out of $totalAttempted attempted imported concepts in $usedTime ms.") - ConceptImportResults(totalSaved, totalAttempted, allWarnings) + ConceptImportResultsDTO(totalSaved, totalAttempted, allWarnings) } } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/ReadService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/ReadService.scala index 50be318965..b16cbe6c3c 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/ReadService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/ReadService.scala @@ -21,7 +21,7 @@ trait ReadService { class ReadService { - def conceptWithId(id: Long, language: String, fallback: Boolean, user: Option[TokenUser]): Try[api.Concept] = + def conceptWithId(id: Long, language: String, fallback: Boolean, user: Option[TokenUser]): Try[api.ConceptDTO] = draftConceptRepository.withId(id).map(converterService.addUrlOnVisualElement) match { case Some(concept) => converterService.toApiConcept(concept, language, fallback, user) @@ -34,7 +34,7 @@ trait ReadService { language: String, fallback: Boolean, user: Option[TokenUser] - ): Try[api.Concept] = + ): Try[api.ConceptDTO] = publishedConceptRepository.withId(id).map(converterService.addUrlOnVisualElement) match { case Some(concept) => converterService.toApiConcept(concept, language, fallback, user) @@ -74,7 +74,7 @@ trait ReadService { }).flatMap(_.tags).distinct } - def getAllTags(input: String, pageSize: Int, offset: Int, language: String): api.TagsSearchResult = { + def getAllTags(input: String, pageSize: Int, offset: Int, language: String): api.TagsSearchResultDTO = { val (tags, tagsCount) = draftConceptRepository.getTags(input, pageSize, (offset - 1) * pageSize, language) converterService.toApiConceptTags(tags, tagsCount, pageSize, offset, language) } diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/WriteService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/WriteService.scala index cbef59301b..f9d07610b3 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/WriteService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/WriteService.scala @@ -77,7 +77,7 @@ trait WriteService { }) } - def newConcept(newConcept: api.NewConcept, user: TokenUser): Try[api.Concept] = { + def newConcept(newConcept: api.NewConceptDTO, user: TokenUser): Try[api.ConceptDTO] = { for { concept <- converterService.toDomainConcept(newConcept, user) _ <- contentValidator.validateConcept(concept) @@ -132,7 +132,7 @@ trait WriteService { private def updateNotes( old: DomainConcept, - updated: api.UpdatedConcept, + updated: api.UpdatedConceptDTO, changed: DomainConcept, user: TokenUser ): DomainConcept = { @@ -174,7 +174,7 @@ trait WriteService { searchApiClient.indexConcept(toIndex, user)(ec): Unit } - def updateConcept(id: Long, updatedConcept: api.UpdatedConcept, user: TokenUser): Try[api.Concept] = { + def updateConcept(id: Long, updatedConcept: api.UpdatedConceptDTO, user: TokenUser): Try[api.ConceptDTO] = { draftConceptRepository.withId(id) match { case Some(existingConcept) => for { @@ -206,7 +206,7 @@ trait WriteService { } } - def deleteLanguage(id: Long, language: String, user: TokenUser): Try[api.Concept] = { + def deleteLanguage(id: Long, language: String, user: TokenUser): Try[api.ConceptDTO] = { draftConceptRepository.withId(id) match { case Some(existingConcept) => existingConcept.title.size match { @@ -252,7 +252,7 @@ trait WriteService { } - def updateConceptStatus(status: ConceptStatus, id: Long, user: TokenUser): Try[api.Concept] = { + def updateConceptStatus(status: ConceptStatus, id: Long, user: TokenUser): Try[api.ConceptDTO] = { draftConceptRepository.withId(id) match { case None => Failure(NotFoundException(s"No article with id $id was found")) case Some(draft) => diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/DraftConceptSearchService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/DraftConceptSearchService.scala index 427a6affa8..fdf2e29161 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/DraftConceptSearchService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/DraftConceptSearchService.scala @@ -14,7 +14,7 @@ import com.typesafe.scalalogging.StrictLogging import no.ndla.common.model.domain.concept.ConceptStatus import no.ndla.conceptapi.Props import no.ndla.conceptapi.model.api -import no.ndla.conceptapi.model.api.{ErrorHandling, OperationNotAllowedException, SubjectTags} +import no.ndla.conceptapi.model.api.{ErrorHandling, OperationNotAllowedException, SubjectTagsDTO} import no.ndla.conceptapi.model.domain.SearchResult import no.ndla.conceptapi.model.search.{DraftSearchSettings, DraftSearchSettingsHelper} import no.ndla.conceptapi.service.ConverterService @@ -40,18 +40,18 @@ trait DraftConceptSearchService { with DraftSearchSettingsHelper => val draftConceptSearchService: DraftConceptSearchService - class DraftConceptSearchService extends StrictLogging with SearchService[api.ConceptSummary] { + class DraftConceptSearchService extends StrictLogging with SearchService[api.ConceptSummaryDTO] { import props._ override val searchIndex: String = DraftConceptSearchIndex - override def hitToApiModel(hitString: String, language: String): api.ConceptSummary = + override def hitToApiModel(hitString: String, language: String): api.ConceptSummaryDTO = searchConverterService.hitAsConceptSummary(hitString, language) def getTagsWithSubjects( subjectIds: List[String], language: String, fallback: Boolean - ): Try[List[api.SubjectTags]] = { + ): Try[List[api.SubjectTagsDTO]] = { if (subjectIds.size <= 0) { Failure(OperationNotAllowedException("Will not generate list of subject tags with no specified subjectIds")) } else { @@ -64,7 +64,7 @@ trait DraftConceptSearchService { private def searchSubjectIdTags(subjectId: String, language: String, fallback: Boolean)(implicit executor: ExecutionContext - ): Future[Try[List[SubjectTags]]] = + ): Future[Try[List[SubjectTagsDTO]]] = Future { val settings = draftSearchSettings.empty.copy( subjects = Set(subjectId), @@ -89,8 +89,8 @@ trait DraftConceptSearchService { @tailrec private def searchUntilNoMoreResults( searchSettings: DraftSearchSettings, - prevResults: List[SearchResult[api.ConceptSummary]] = List.empty - ): Try[List[SearchResult[api.ConceptSummary]]] = { + prevResults: List[SearchResult[api.ConceptSummaryDTO]] = List.empty + ): Try[List[SearchResult[api.ConceptSummaryDTO]]] = { val page = prevResults.lastOption.flatMap(_.page).getOrElse(0) + 1 val result = prevResults.lastOption.flatMap(_.scrollId) match { @@ -105,9 +105,10 @@ trait DraftConceptSearchService { } } - def all(settings: DraftSearchSettings): Try[SearchResult[api.ConceptSummary]] = executeSearch(boolQuery(), settings) + def all(settings: DraftSearchSettings): Try[SearchResult[api.ConceptSummaryDTO]] = + executeSearch(boolQuery(), settings) - def matchingQuery(query: String, settings: DraftSearchSettings): Try[SearchResult[api.ConceptSummary]] = { + def matchingQuery(query: String, settings: DraftSearchSettings): Try[SearchResult[api.ConceptSummaryDTO]] = { val language = if (settings.searchLanguage == AllLanguages || settings.fallback) "*" else settings.searchLanguage @@ -130,7 +131,10 @@ trait DraftConceptSearchService { executeSearch(fullQuery, settings) } - def executeSearch(queryBuilder: BoolQuery, settings: DraftSearchSettings): Try[SearchResult[api.ConceptSummary]] = { + def executeSearch( + queryBuilder: BoolQuery, + settings: DraftSearchSettings + ): Try[SearchResult[api.ConceptSummaryDTO]] = { val idFilter = if (settings.withIdIn.isEmpty) None else Some(idsQuery(settings.withIdIn)) val typeFilter = settings.conceptType.map(ct => termsQuery("conceptType", ct)) val statusFilter = boolStatusFilter(settings.statusFilter) diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchService.scala index a6ebd93cc2..9c5ac7efa7 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchService.scala @@ -14,7 +14,7 @@ import com.sksamuel.elastic4s.requests.searches.queries.compound.BoolQuery import com.typesafe.scalalogging.StrictLogging import no.ndla.conceptapi.Props import no.ndla.conceptapi.model.api -import no.ndla.conceptapi.model.api.{ErrorHandling, OperationNotAllowedException, SubjectTags} +import no.ndla.conceptapi.model.api.{ErrorHandling, OperationNotAllowedException, SubjectTagsDTO} import no.ndla.conceptapi.model.domain.SearchResult import no.ndla.conceptapi.model.search.{SearchSettings, SearchSettingsHelper} import no.ndla.conceptapi.service.ConverterService @@ -41,18 +41,18 @@ trait PublishedConceptSearchService { with SearchSettingsHelper => val publishedConceptSearchService: PublishedConceptSearchService - class PublishedConceptSearchService extends StrictLogging with SearchService[api.ConceptSummary] { + class PublishedConceptSearchService extends StrictLogging with SearchService[api.ConceptSummaryDTO] { import props._ override val searchIndex: String = PublishedConceptSearchIndex - override def hitToApiModel(hitString: String, language: String): api.ConceptSummary = + override def hitToApiModel(hitString: String, language: String): api.ConceptSummaryDTO = searchConverterService.hitAsConceptSummary(hitString, language) def getTagsWithSubjects( subjectIds: List[String], language: String, fallback: Boolean - ): Try[List[api.SubjectTags]] = { + ): Try[List[api.SubjectTagsDTO]] = { if (subjectIds.size <= 0) { Failure(OperationNotAllowedException("Will not generate list of subject tags with no specified subjectIds")) } else { @@ -65,7 +65,7 @@ trait PublishedConceptSearchService { private def searchSubjectIdTags(subjectId: String, language: String, fallback: Boolean)(implicit executor: ExecutionContext - ): Future[Try[List[SubjectTags]]] = + ): Future[Try[List[SubjectTagsDTO]]] = Future { val settings = SearchSettings.empty.copy( subjects = Set(subjectId), @@ -90,8 +90,8 @@ trait PublishedConceptSearchService { @tailrec private def searchUntilNoMoreResults( searchSettings: SearchSettings, - prevResults: List[SearchResult[api.ConceptSummary]] = List.empty - ): Try[List[SearchResult[api.ConceptSummary]]] = { + prevResults: List[SearchResult[api.ConceptSummaryDTO]] = List.empty + ): Try[List[SearchResult[api.ConceptSummaryDTO]]] = { val page = prevResults.lastOption.flatMap(_.page).getOrElse(0) + 1 val result = prevResults.lastOption.flatMap(_.scrollId) match { @@ -106,9 +106,9 @@ trait PublishedConceptSearchService { } } - def all(settings: SearchSettings): Try[SearchResult[api.ConceptSummary]] = executeSearch(boolQuery(), settings) + def all(settings: SearchSettings): Try[SearchResult[api.ConceptSummaryDTO]] = executeSearch(boolQuery(), settings) - def matchingQuery(query: String, settings: SearchSettings): Try[SearchResult[api.ConceptSummary]] = { + def matchingQuery(query: String, settings: SearchSettings): Try[SearchResult[api.ConceptSummaryDTO]] = { val language = if (settings.fallback) "*" else settings.searchLanguage @@ -133,7 +133,7 @@ trait PublishedConceptSearchService { executeSearch(fullQuery, settings) } - def executeSearch(queryBuilder: BoolQuery, settings: SearchSettings): Try[SearchResult[api.ConceptSummary]] = { + def executeSearch(queryBuilder: BoolQuery, settings: SearchSettings): Try[SearchResult[api.ConceptSummaryDTO]] = { val idFilter = if (settings.withIdIn.isEmpty) None else Some(idsQuery(settings.withIdIn)) val typeFilter = settings.conceptType.map(ct => termsQuery("conceptType", ct)) val subjectFilter = orFilter(settings.subjects, "subjectIds") diff --git a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/SearchConverterService.scala b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/SearchConverterService.scala index 4268e49fdc..4d99e1eb22 100644 --- a/concept-api/src/main/scala/no/ndla/conceptapi/service/search/SearchConverterService.scala +++ b/concept-api/src/main/scala/no/ndla/conceptapi/service/search/SearchConverterService.scala @@ -15,7 +15,7 @@ import no.ndla.common.model.domain.{Tag, Title, concept} import no.ndla.common.model.api as commonApi import no.ndla.common.model.domain.concept.{Concept, ConceptContent, ConceptMetaImage, ConceptType, VisualElement} import no.ndla.conceptapi.integration.model.TaxonomyData -import no.ndla.conceptapi.model.api.{ConceptResponsible, ConceptSearchResult, SubjectTags} +import no.ndla.conceptapi.model.api.{ConceptResponsibleDTO, ConceptSearchResultDTO, SubjectTagsDTO} import no.ndla.conceptapi.model.domain.SearchResult import no.ndla.conceptapi.model.search.* import no.ndla.conceptapi.model.api @@ -123,7 +123,7 @@ trait SearchConverterService { ) } - def hitAsConceptSummary(hitString: String, language: String): api.ConceptSummary = { + def hitAsConceptSummary(hitString: String, language: String): api.ConceptSummaryDTO = { val searchableConcept = CirceUtil.unsafeParseAs[SearchableConcept](hitString) val titles = searchableConcept.title.languageValues.map(lv => Title(lv.value, lv.language)) val contents = searchableConcept.content.languageValues.map(lv => ConceptContent(lv.value, lv.language)) @@ -135,20 +135,20 @@ trait SearchConverterService { val title = findByLanguageOrBestEffort(titles, language) .map(converterService.toApiConceptTitle) - .getOrElse(api.ConceptTitle("", UnknownLanguage.toString())) + .getOrElse(api.ConceptTitleDTO("", UnknownLanguage.toString())) val content = findByLanguageOrBestEffort(contents, language) .map(converterService.toApiConceptContent) .getOrElse(api.ConceptContent("", "", UnknownLanguage.toString())) val metaImage = findByLanguageOrBestEffort(searchableConcept.metaImage, language) .map(converterService.toApiMetaImage) - .getOrElse(api.ConceptMetaImage("", "", UnknownLanguage.toString())) + .getOrElse(api.ConceptMetaImageDTO("", "", UnknownLanguage.toString())) val tag = findByLanguageOrBestEffort(tags, language).map(converterService.toApiTags) val visualElement = findByLanguageOrBestEffort(visualElements, language).map(converterService.toApiVisualElement) val subjectIds = Option(searchableConcept.subjectIds.toSet).filter(_.nonEmpty) val license = converterService.toApiLicense(searchableConcept.license) val copyright = searchableConcept.copyright.map(c => { - commonApi.DraftCopyright( + commonApi.DraftCopyrightDTO( license = Some(license), origin = c.origin, creators = c.creators.map(_.toApi), @@ -160,14 +160,14 @@ trait SearchConverterService { ) }) - val responsible = searchableConcept.responsible.map(r => ConceptResponsible(r.responsibleId, r.lastUpdated)) + val responsible = searchableConcept.responsible.map(r => ConceptResponsibleDTO(r.responsibleId, r.lastUpdated)) val glossData = converterService.toApiGlossData(searchableConcept.domainObject.glossData) val subjectName = searchableConcept.sortableSubject.getLanguageOrDefault(language) val conceptTypeName = searchableConcept.sortableConceptType .getLanguageOrDefault(language) .getOrElse(searchableConcept.conceptType) - api.ConceptSummary( + api.ConceptSummaryDTO( id = searchableConcept.id, title = title, content = content, @@ -192,12 +192,12 @@ trait SearchConverterService { ) } - def groupSubjectTagsByLanguage(subjectId: String, tags: List[api.ConceptTags]): List[SubjectTags] = + def groupSubjectTagsByLanguage(subjectId: String, tags: List[api.ConceptTagsDTO]): List[SubjectTagsDTO] = tags .groupBy(_.language) .map { case (lang, conceptTags) => val tagsForLang = conceptTags.flatMap(_.tags).distinct - api.SubjectTags(subjectId, tagsForLang, lang) + api.SubjectTagsDTO(subjectId, tagsForLang, lang) } .toList @@ -235,8 +235,8 @@ trait SearchConverterService { } } - def asApiConceptSearchResult(searchResult: SearchResult[api.ConceptSummary]): ConceptSearchResult = - api.ConceptSearchResult( + def asApiConceptSearchResult(searchResult: SearchResult[api.ConceptSummaryDTO]): ConceptSearchResultDTO = + api.ConceptSearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, @@ -245,8 +245,8 @@ trait SearchConverterService { searchResult.aggregations.map(toApiMultiTermsAggregation) ) - def toApiStatus(status: Status): api.Status = { - api.Status( + def toApiStatus(status: Status): api.StatusDTO = { + api.StatusDTO( current = status.current, other = status.other ) diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/TestData.scala b/concept-api/src/test/scala/no/ndla/conceptapi/TestData.scala index 115bec8353..95485da9de 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/TestData.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/TestData.scala @@ -51,26 +51,26 @@ object TestData { val visualElementStringWithUrl: String = s"""<$EmbedTagName data-caption="some capt" data-align="" data-resource_id="1" data-resource="image" data-alt="some alt" data-size="full" data-url="http://api-gateway.ndla-local/image-api/v2/images/1" />""" - val sampleNbApiConcept: api.Concept = api.Concept( + val sampleNbApiConcept: api.ConceptDTO = api.ConceptDTO( 1.toLong, 1, - api.ConceptTitle("Tittel", "nb"), + api.ConceptTitleDTO("Tittel", "nb"), Some(api.ConceptContent("Innhold", "Innhold", "nb")), None, None, - Some(api.ConceptMetaImage("http://api-gateway.ndla-local/image-api/raw/id/1", "Hei", "nb")), - Some(api.ConceptTags(Seq("stor", "kaktus"), "nb")), + Some(api.ConceptMetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/1", "Hei", "nb")), + Some(api.ConceptTagsDTO(Seq("stor", "kaktus"), "nb")), Some(Set("urn:subject:3", "urn:subject:4")), yesterday, today, Some(Seq("")), Set("nn", "nb"), Seq(42), - api.Status( + api.StatusDTO( current = "IN_PROGRESS", other = Seq.empty ), - Some(api.VisualElement(visualElementStringWithUrl, "nb")), + Some(api.VisualElementDTO(visualElementStringWithUrl, "nb")), responsible = None, conceptType = "concept", glossData = None, @@ -163,33 +163,33 @@ object TestData { editorNotes = Seq.empty ) - val sampleNnApiConcept: api.Concept = api.Concept( + val sampleNnApiConcept: api.ConceptDTO = api.ConceptDTO( 1.toLong, 1, - api.ConceptTitle("Tittelur", "nn"), + api.ConceptTitleDTO("Tittelur", "nn"), Some(api.ConceptContent("Innhald", "Innhald", "nn")), None, None, - Some(api.ConceptMetaImage("http://api-gateway.ndla-local/image-api/raw/id/2", "Hej", "nn")), - Some(api.ConceptTags(Seq("liten", "fisk"), "nn")), + Some(api.ConceptMetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/2", "Hej", "nn")), + Some(api.ConceptTagsDTO(Seq("liten", "fisk"), "nn")), Some(Set("urn:subject:3", "urn:subject:4")), yesterday, today, updatedBy = Some(Seq("")), Set("nn", "nb"), Seq(42), - api.Status( + api.StatusDTO( current = "IN_PROGRESS", other = Seq.empty ), - Some(api.VisualElement(visualElementStringWithUrl, "nb")), + Some(api.VisualElementDTO(visualElementStringWithUrl, "nb")), responsible = None, conceptType = "concept", glossData = None, editorNotes = Some(Seq.empty) ) - val emptyApiUpdatedConcept: api.UpdatedConcept = api.UpdatedConcept( + val emptyApiUpdatedConcept: api.UpdatedConceptDTO = api.UpdatedConceptDTO( language = "", title = None, content = None, @@ -205,8 +205,8 @@ object TestData { glossData = None ) - val sampleNewConcept: api.NewConcept = - api.NewConcept( + val sampleNewConcept: api.NewConceptDTO = + api.NewConceptDTO( "nb", "Tittel", Some("Innhold"), @@ -221,7 +221,7 @@ object TestData { None ) - val emptyApiNewConcept: api.NewConcept = api.NewConcept( + val emptyApiNewConcept: api.NewConceptDTO = api.NewConceptDTO( language = "", title = "", content = None, @@ -236,8 +236,8 @@ object TestData { glossData = None ) - val updatedConcept: api.UpdatedConcept = - api.UpdatedConcept( + val updatedConcept: api.UpdatedConceptDTO = + api.UpdatedConceptDTO( "nb", None, Some("Innhold"), @@ -252,5 +252,5 @@ object TestData { conceptType = None, glossData = None ) - val sampleApiTagsSearchResult: api.TagsSearchResult = api.TagsSearchResult(10, 1, 1, "nb", Seq("a", "b")) + val sampleApiTagsSearchResult: api.TagsSearchResultDTO = api.TagsSearchResultDTO(10, 1, 1, "nb", Seq("a", "b")) } diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/controller/DraftConceptControllerTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/controller/DraftConceptControllerTest.scala index 632b16bc6a..e1a7238a1c 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/controller/DraftConceptControllerTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/controller/DraftConceptControllerTest.scala @@ -82,7 +82,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap test("POST / should return 201 on created") { when( writeService - .newConcept(any[NewConcept], any[TokenUser]) + .newConcept(any[NewConceptDTO], any[TokenUser]) ) .thenReturn(Success(TestData.sampleNbApiConcept)) simpleHttpClient @@ -99,7 +99,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap test("POST / should return 403 if no write role") { when( writeService - .newConcept(any[NewConcept], any) + .newConcept(any[NewConceptDTO], any) ) .thenReturn(Success(TestData.sampleNbApiConcept)) simpleHttpClient @@ -116,7 +116,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap test("PATCH / should return 200 on updated") { when( writeService - .updateConcept(eqTo(1.toLong), any[UpdatedConcept], any) + .updateConcept(eqTo(1.toLong), any[UpdatedConceptDTO], any) ) .thenReturn(Success(TestData.sampleNbApiConcept)) @@ -136,7 +136,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap test("PATCH / should return 403 if no write role") { when( writeService - .updateConcept(eqTo(1.toLong), any[UpdatedConcept], any) + .updateConcept(eqTo(1.toLong), any[UpdatedConceptDTO], any) ) .thenReturn(Success(TestData.sampleNbApiConcept)) @@ -155,7 +155,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap reset(writeService) when( writeService - .updateConcept(eqTo(1.toLong), any[UpdatedConcept], any[TokenUser]) + .updateConcept(eqTo(1.toLong), any[UpdatedConceptDTO], any[TokenUser]) ) .thenReturn(Success(TestData.sampleNbApiConcept)) @@ -167,7 +167,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap val existingArtId = """{"language":"nb","metaImage":{"id":"123","alt":"alt123"}}""" val existingExpected = TestData.emptyApiUpdatedConcept - .copy(language = "nb", metaImage = UpdateWith(NewConceptMetaImage(id = "123", alt = "alt123"))) + .copy(language = "nb", metaImage = UpdateWith(NewConceptMetaImageDTO(id = "123", alt = "alt123"))) { simpleHttpClient @@ -225,7 +225,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap reset(writeService) when( writeService - .updateConcept(eqTo(1.toLong), any[UpdatedConcept], any[TokenUser]) + .updateConcept(eqTo(1.toLong), any[UpdatedConceptDTO], any[TokenUser]) ) .thenReturn(Success(TestData.sampleNbApiConcept)) @@ -238,7 +238,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap val existingArtId = """{"language":"nb","metaImage": {"id": "1", | "alt": "alt-text"}}""".stripMargin val existingExpected = TestData.emptyApiUpdatedConcept - .copy(language = "nb", metaImage = UpdateWith(api.NewConceptMetaImage("1", "alt-text"))) + .copy(language = "nb", metaImage = UpdateWith(api.NewConceptMetaImageDTO("1", "alt-text"))) { simpleHttpClient @@ -284,7 +284,7 @@ class DraftConceptControllerTest extends UnitSuite with TestEnvironment with Tap reset(draftConceptSearchService) val multiResult = - SearchResult[ConceptSummary](0, None, 10, "nn", Seq.empty, Seq.empty, Some("heiheihei")) + SearchResult[ConceptSummaryDTO](0, None, 10, "nn", Seq.empty, Seq.empty, Some("heiheihei")) when(draftConceptSearchService.all(any[search.DraftSearchSettings])).thenReturn(Success(multiResult)) when(searchConverterService.asApiConceptSearchResult(any)).thenCallRealMethod() diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/controller/PublishedConceptControllerTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/controller/PublishedConceptControllerTest.scala index ac6ea6e833..dcf66405b9 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/controller/PublishedConceptControllerTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/controller/PublishedConceptControllerTest.scala @@ -6,7 +6,7 @@ */ package no.ndla.conceptapi.controller -import no.ndla.conceptapi.model.api.{ConceptSummary, NotFoundException} +import no.ndla.conceptapi.model.api.{ConceptSummaryDTO, NotFoundException} import no.ndla.conceptapi.model.domain.{SearchResult, Sort} import no.ndla.conceptapi.model.search.SearchSettings import no.ndla.conceptapi.{TestData, TestEnvironment, UnitSuite} @@ -80,7 +80,7 @@ class PublishedConceptControllerTest extends UnitSuite with TestEnvironment with reset(publishedConceptSearchService) val multiResult = - SearchResult[ConceptSummary](0, None, 10, "nn", Seq.empty, Seq.empty, Some("heiheihei")) + SearchResult[ConceptSummaryDTO](0, None, 10, "nn", Seq.empty, Seq.empty, Some("heiheihei")) when(publishedConceptSearchService.all(any[SearchSettings])).thenReturn(Success(multiResult)) when(searchConverterService.asApiConceptSearchResult(any)).thenCallRealMethod() diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/service/ConverterServiceTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/service/ConverterServiceTest.scala index b4d58935fd..1b9f9ef404 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/service/ConverterServiceTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/service/ConverterServiceTest.scala @@ -12,7 +12,7 @@ import no.ndla.common.model.domain.concept.* import no.ndla.common.model.domain.{Responsible, concept} import no.ndla.common.model.{NDLADate, api as commonApi, domain as common} import no.ndla.conceptapi.model.api -import no.ndla.conceptapi.model.api.{NewConcept, NotFoundException, UpdatedConcept} +import no.ndla.conceptapi.model.api.{NewConceptDTO, NotFoundException, UpdatedConceptDTO} import no.ndla.conceptapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.network.tapir.auth.Permission.{CONCEPT_API_ADMIN, CONCEPT_API_WRITE} import no.ndla.network.tapir.auth.TokenUser @@ -56,7 +56,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { when(clock.now()).thenReturn(updated) val updateWith = - UpdatedConcept( + UpdatedConceptDTO( "nb", Some("heisann"), None, @@ -87,7 +87,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { when(clock.now()).thenReturn(updated) val updateWith = - UpdatedConcept( + UpdatedConceptDTO( "nn", None, Some("Nytt innhald"), @@ -118,7 +118,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { when(clock.now()).thenReturn(updated) val updateWith = - UpdatedConcept( + UpdatedConceptDTO( "en", Some("Title"), Some("My content"), @@ -154,18 +154,18 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val updated = NDLADate.now() when(clock.now()).thenReturn(updated) - val updateWith = UpdatedConcept( + val updateWith = UpdatedConceptDTO( "nn", None, Some("Nytt innhald"), Missing, Option( - commonApi.DraftCopyright( + commonApi.DraftCopyrightDTO( None, None, - Seq(commonApi.Author("Photographer", "Photographer")), - Seq(commonApi.Author("Photographer", "Photographer")), - Seq(commonApi.Author("Photographer", "Photographer")), + Seq(commonApi.AuthorDTO("Photographer", "Photographer")), + Seq(commonApi.AuthorDTO("Photographer", "Photographer")), + Seq(commonApi.AuthorDTO("Photographer", "Photographer")), None, None, false @@ -331,7 +331,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { ) val updateWith = TestData.emptyApiUpdatedConcept.copy( language = "nb", - metaImage = UpdateWith(api.NewConceptMetaImage("1", "Hola")) + metaImage = UpdateWith(api.NewConceptMetaImageDTO("1", "Hola")) ) converterService.toDomainConcept(beforeUpdate, updateWith, userInfo).get should be(afterUpdate) @@ -374,7 +374,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { ) val updateWith = TestData.emptyApiUpdatedConcept.copy( language = "nb", - metaImage = UpdateWith(api.NewConceptMetaImage("1", "Hola")) + metaImage = UpdateWith(api.NewConceptMetaImageDTO("1", "Hola")) ) converterService.toDomainConcept(12, updateWith, userInfo) should be(afterUpdate) @@ -519,13 +519,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that toDomainConcept (new concept) creates glossData correctly") { val newGlossExamples1 = List( - api.GlossExample(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), - api.GlossExample(example = "jog har inta", "nn", transcriptions = Map("b" -> "c")) + api.GlossExampleDTO(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), + api.GlossExampleDTO(example = "jog har inta", "nn", transcriptions = Map("b" -> "c")) ) val newGlossExamples2 = - List(api.GlossExample(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) + List(api.GlossExampleDTO(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) val newGlossData = - api.GlossData( + api.GlossDataDTO( gloss = "juan", wordClass = "noun", originalLanguage = "nb", @@ -559,13 +559,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that toDomainConcept (new concept) fails if either conceptType or wordClass is outside of supported values") { val newGlossExamples1 = List( - api.GlossExample(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), - api.GlossExample(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) + api.GlossExampleDTO(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), + api.GlossExampleDTO(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) ) val newGlossExamples2 = - List(api.GlossExample(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) + List(api.GlossExampleDTO(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) val newGlossData = - api.GlossData( + api.GlossDataDTO( gloss = "huehue", wordClass = "ikke", originalLanguage = "nb", @@ -586,13 +586,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that toDomainConcept (update concept) updates glossData correctly") { val updatedGlossExamples1 = List( - api.GlossExample(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), - api.GlossExample(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) + api.GlossExampleDTO(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), + api.GlossExampleDTO(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) ) val updatedGlossExamples2 = - List(api.GlossExample(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) + List(api.GlossExampleDTO(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) val updatedGlossData = - api.GlossData( + api.GlossDataDTO( gloss = "huehue", wordClass = "noun", originalLanguage = "nb", @@ -632,13 +632,13 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that toDomainConcept (update concept) fails if gloss type is not a valid value") { val updatedGlossExamples1 = List( - api.GlossExample(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), - api.GlossExample(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) + api.GlossExampleDTO(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), + api.GlossExampleDTO(example = "jog har inta", "nn", transcriptions = Map("a" -> "b")) ) val updatedGlossExamples2 = - List(api.GlossExample(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) + List(api.GlossExampleDTO(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) val updatedGlossData = - api.GlossData( + api.GlossDataDTO( gloss = "yesp", wordClass = "ikke eksisterende", originalLanguage = "nb", @@ -680,12 +680,12 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val expectedGlossExamples1 = List( - api.GlossExample(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), - api.GlossExample(example = "jog har inta", "nn", transcriptions = Map("b" -> "c")) + api.GlossExampleDTO(example = "nei men saa", language = "nb", transcriptions = Map("a" -> "b")), + api.GlossExampleDTO(example = "jog har inta", "nn", transcriptions = Map("b" -> "c")) ) val expectedGlossExamples2 = - List(api.GlossExample(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) - val expectedGlossData = api.GlossData( + List(api.GlossExampleDTO(example = "nei men da saa", language = "nb", transcriptions = Map("a" -> "b"))) + val expectedGlossData = api.GlossDataDTO( gloss = "gestalt", wordClass = "noun", originalLanguage = "nb", @@ -698,10 +698,11 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("that toDomainGlossData converts correctly when apiGlossData is Some") { - val apiGlossExample = api.GlossExample(example = "some example", language = "nb", transcriptions = Map("a" -> "b")) + val apiGlossExample = + api.GlossExampleDTO(example = "some example", language = "nb", transcriptions = Map("a" -> "b")) val apiGlossData = Some( - api.GlossData( + api.GlossDataDTO( gloss = "yoink", wordClass = "verb", originalLanguage = "nb", @@ -729,10 +730,11 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("that toDomainGlossData fails if apiGlossData has malformed data") { - val apiGlossExample = api.GlossExample(example = "some example", language = "nb", transcriptions = Map("a" -> "b")) + val apiGlossExample = + api.GlossExampleDTO(example = "some example", language = "nb", transcriptions = Map("a" -> "b")) val apiGlossData = Some( - api.GlossData( + api.GlossDataDTO( gloss = "neie", wordClass = "nonexistent", originalLanguage = "nb", @@ -746,7 +748,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("unknown embed attributes should be stripped from new concepts") { - val newConcept = NewConcept( + val newConcept = NewConceptDTO( language = "nb", title = "tittel", content = Some("Nokko innhald"), @@ -776,7 +778,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("unknown embed attributes should be stripped from updated concepts (if null document)") { - val updatedConcept = UpdatedConcept( + val updatedConcept = UpdatedConceptDTO( language = "nb", title = Some("tittel"), content = Some("Nokko innhald"), @@ -806,7 +808,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("unknown embed attributes should be stripped from updated concepts") { - val updatedConcept = UpdatedConcept( + val updatedConcept = UpdatedConceptDTO( language = "nb", title = Some("tittel"), content = Some("Nokko innhald"), diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/service/WriteServiceTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/service/WriteServiceTest.scala index bed36258d6..71d55d2519 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/service/WriteServiceTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/service/WriteServiceTest.scala @@ -9,7 +9,7 @@ package no.ndla.conceptapi.service import no.ndla.common.model.domain.{Responsible, Tag, Title} import no.ndla.common.model.api as commonApi -import no.ndla.conceptapi.model.api.ConceptResponsible +import no.ndla.conceptapi.model.api.ConceptResponsibleDTO import no.ndla.conceptapi.model.api import no.ndla.conceptapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.network.tapir.auth.TokenUser @@ -41,12 +41,12 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val conceptId = 13L val userInfo: TokenUser = TokenUser.SystemUser - val concept: api.Concept = + val concept: api.ConceptDTO = TestData.sampleNbApiConcept.copy( id = conceptId, updated = today, supportedLanguages = Set("nb"), - responsible = Some(ConceptResponsible("hei", TestData.today)) + responsible = Some(ConceptResponsibleDTO("hei", TestData.today)) ) val domainConcept: Concept = TestData.sampleNbDomainConcept.copy( @@ -87,7 +87,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("That update function updates only content properly") { val newContent = "NewContentTest" val updatedApiConcept = - api.UpdatedConcept( + api.UpdatedConceptDTO( "en", None, content = Some(newContent), @@ -109,7 +109,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { articleIds = Seq.empty, editorNotes = Some( Seq( - api.EditorNote("New language 'en' added", "", api.Status("IN_PROGRESS", Seq.empty), today) + api.EditorNoteDTO("New language 'en' added", "", api.StatusDTO("IN_PROGRESS", Seq.empty), today) ) ) ) @@ -120,7 +120,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("That update function updates only title properly") { val newTitle = "NewTitleTest" val updatedApiConcept = - api.UpdatedConcept( + api.UpdatedConceptDTO( "nn", title = Some(newTitle), None, @@ -136,13 +136,13 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None ) val expectedConcept = concept.copy( - title = api.ConceptTitle(newTitle, "nn"), + title = api.ConceptTitleDTO(newTitle, "nn"), updated = today, supportedLanguages = Set("nb", "nn"), articleIds = Seq.empty, editorNotes = Some( Seq( - api.EditorNote("New language 'nn' added", "", api.Status("IN_PROGRESS", Seq.empty), today) + api.EditorNoteDTO("New language 'nn' added", "", api.StatusDTO("IN_PROGRESS", Seq.empty), today) ) ) ) @@ -153,19 +153,19 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val updatedTitle = "NyTittelTestJee" val updatedContent = "NyContentTestYepp" val updatedCopyright = - commonApi.DraftCopyright( + commonApi.DraftCopyrightDTO( None, Some("https://ndla.no"), - Seq(commonApi.Author("Opphavsmann", "Katrine")), + Seq(commonApi.AuthorDTO("Opphavsmann", "Katrine")), List(), List(), None, None, false ) - val updatedMetaImage = api.NewConceptMetaImage("2", "AltTxt") + val updatedMetaImage = api.NewConceptMetaImageDTO("2", "AltTxt") - val updatedApiConcept = api.UpdatedConcept( + val updatedApiConcept = api.UpdatedConceptDTO( "en", Some(updatedTitle), Some(updatedContent), @@ -182,14 +182,14 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) val expectedConcept = concept.copy( - title = api.ConceptTitle(updatedTitle, "en"), + title = api.ConceptTitleDTO(updatedTitle, "en"), content = Option(api.ConceptContent(updatedContent, updatedContent, "en")), - metaImage = Some(api.ConceptMetaImage("http://api-gateway.ndla-local/image-api/raw/id/2", "AltTxt", "en")), + metaImage = Some(api.ConceptMetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/2", "AltTxt", "en")), copyright = Some( - commonApi.DraftCopyright( + commonApi.DraftCopyrightDTO( None, Some("https://ndla.no"), - Seq(commonApi.Author("Opphavsmann", "Katrine")), + Seq(commonApi.AuthorDTO("Opphavsmann", "Katrine")), List(), List(), None, @@ -199,14 +199,14 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ), source = Some("https://ndla.no"), supportedLanguages = Set("nb", "en"), - tags = Some(api.ConceptTags(Seq("Nye", "Tags"), "en")), + tags = Some(api.ConceptTagsDTO(Seq("Nye", "Tags"), "en")), subjectIds = Some(Set("urn:subject:900")), articleIds = Seq(69L), - responsible = Some(api.ConceptResponsible("123", today)), + responsible = Some(api.ConceptResponsibleDTO("123", today)), editorNotes = Some( Seq( - api.EditorNote("New language 'en' added", "", api.Status("IN_PROGRESS", Seq.empty), today), - api.EditorNote("Responsible changed", "", api.Status("IN_PROGRESS", Seq.empty), today) + api.EditorNoteDTO("New language 'en' added", "", api.StatusDTO("IN_PROGRESS", Seq.empty), today), + api.EditorNoteDTO("Responsible changed", "", api.StatusDTO("IN_PROGRESS", Seq.empty), today) ) ) ) @@ -276,7 +276,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("That update function updates only responsible properly") { val responsibleId = "ResponsibleId" val updatedApiConcept = - api.UpdatedConcept( + api.UpdatedConceptDTO( language = "nb", title = None, content = None, @@ -295,10 +295,10 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { updated = today, supportedLanguages = Set("nb"), articleIds = Seq(42), - responsible = Some(api.ConceptResponsible(responsibleId, today)), + responsible = Some(api.ConceptResponsibleDTO(responsibleId, today)), editorNotes = Some( Seq( - api.EditorNote("Responsible changed", "", api.Status("IN_PROGRESS", Seq.empty), today) + api.EditorNoteDTO("Responsible changed", "", api.StatusDTO("IN_PROGRESS", Seq.empty), today) ) ) ) diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/service/search/DraftConceptSearchServiceTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/service/search/DraftConceptSearchServiceTest.scala index a4f22acea3..13d8e6c73d 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/service/search/DraftConceptSearchServiceTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/service/search/DraftConceptSearchServiceTest.scala @@ -11,7 +11,7 @@ import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.model.domain.draft.DraftCopyright import no.ndla.common.model.domain.{Author, Responsible, Tag, Title, concept} import no.ndla.conceptapi.* -import no.ndla.conceptapi.model.api.SubjectTags +import no.ndla.conceptapi.model.api.SubjectTagsDTO import no.ndla.conceptapi.model.domain.* import no.ndla.conceptapi.model.search.DraftSearchSettings import no.ndla.language.Language @@ -614,12 +614,12 @@ class DraftConceptSearchServiceTest extends IntegrationSuite(EnableElasticsearch tagSearch1 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("burugle"), language = "nb" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" @@ -629,7 +629,7 @@ class DraftConceptSearchServiceTest extends IntegrationSuite(EnableElasticsearch tagSearch2 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("cageowl"), language = "en" @@ -646,12 +646,12 @@ class DraftConceptSearchServiceTest extends IntegrationSuite(EnableElasticsearch tagSearch1 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("burugle"), language = "nb" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" @@ -661,12 +661,12 @@ class DraftConceptSearchServiceTest extends IntegrationSuite(EnableElasticsearch tagSearch2 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("cageowl"), language = "en" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" diff --git a/concept-api/src/test/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchServiceTest.scala b/concept-api/src/test/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchServiceTest.scala index e469e574e0..0f4bc180a7 100644 --- a/concept-api/src/test/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchServiceTest.scala +++ b/concept-api/src/test/scala/no/ndla/conceptapi/service/search/PublishedConceptSearchServiceTest.scala @@ -10,7 +10,7 @@ package no.ndla.conceptapi.service.search import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.model.domain.draft.DraftCopyright import no.ndla.common.model.domain.{Author, Tag, Title} -import no.ndla.conceptapi.model.api.SubjectTags +import no.ndla.conceptapi.model.api.SubjectTagsDTO import no.ndla.conceptapi.model.domain.* import no.ndla.conceptapi.model.search import no.ndla.conceptapi.* @@ -567,12 +567,12 @@ class PublishedConceptSearchServiceTest tagSearch1 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("burugle"), language = "nb" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" @@ -582,7 +582,7 @@ class PublishedConceptSearchServiceTest tagSearch2 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("cageowl"), language = "en" @@ -599,12 +599,12 @@ class PublishedConceptSearchServiceTest tagSearch1 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("burugle"), language = "nb" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" @@ -614,12 +614,12 @@ class PublishedConceptSearchServiceTest tagSearch2 should be( List( - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:2", tags = List("cageowl"), language = "en" ), - SubjectTags( + SubjectTagsDTO( subjectId = "urn:subject:100", tags = List("stor", "klovn"), language = "nb" diff --git a/draft-api/src/main/scala/no/ndla/draftapi/controller/DraftController.scala b/draft-api/src/main/scala/no/ndla/draftapi/controller/DraftController.scala index 78027d73e4..596ab636f8 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/controller/DraftController.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/controller/DraftController.scala @@ -11,7 +11,7 @@ import cats.implicits.* import io.circe.generic.auto.* import no.ndla.common.model.NDLADate import no.ndla.common.model.api.CommaSeparatedList.* -import no.ndla.common.model.api.License +import no.ndla.common.model.api.LicenseDTO import no.ndla.common.model.domain.ArticleType import no.ndla.common.model.domain.draft.DraftStatus import no.ndla.draftapi.model.api.* @@ -133,8 +133,8 @@ trait DraftController { * A Try with scroll result, or the return of the orFunction (Usually a try with a search result). */ private def scrollSearchOr(scrollId: Option[String], language: String)( - orFunction: => Try[(ArticleSearchResult, DynamicHeaders)] - ): Try[(ArticleSearchResult, DynamicHeaders)] = { + orFunction: => Try[(ArticleSearchResultDTO, DynamicHeaders)] + ): Try[(ArticleSearchResultDTO, DynamicHeaders)] = { scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => articleSearchService.scroll(scroll, language) match { @@ -157,7 +157,7 @@ trait DraftController { .in(pageNo) .in(language) .errorOut(errorOutputsFor(401, 403)) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => { case (maybeQuery, pageSize, pageNo, language) => @@ -178,7 +178,7 @@ trait DraftController { fallback: Boolean, grepCodes: Seq[String], shouldScroll: Boolean - ): Try[(ArticleSearchResult, DynamicHeaders)] = { + ): Try[(ArticleSearchResultDTO, DynamicHeaders)] = { val searchSettings = query match { case Some(q) => SearchSettings( @@ -228,7 +228,7 @@ trait DraftController { .in(pageNo) .errorOut(errorOutputsFor(401, 403)) .requirePermission(DRAFT_API_WRITE) - .out(jsonBody[GrepCodesSearchResult]) + .out(jsonBody[GrepCodesSearchResultDTO]) .serverLogicPure { _ => { case (maybeQuery, pageSize, pageNo) => val query = maybeQuery.getOrElse("") @@ -251,7 +251,7 @@ trait DraftController { .in(grepCodes) .in(fallback) .errorOut(errorOutputsFor(401, 403)) - .out(jsonBody[ArticleSearchResult]) + .out(jsonBody[ArticleSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => @@ -297,9 +297,9 @@ trait DraftController { .summary("Show all articles") .description("Shows all articles. You can search it too.") .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[ArticleSearchResult]) + .out(jsonBody[ArticleSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) - .in(jsonBody[ArticleSearchParams]) + .in(jsonBody[ArticleSearchParamsDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => searchParams => val language = searchParams.language.getOrElse(Language.AllLanguages) @@ -338,7 +338,7 @@ trait DraftController { .in(language) .in(fallback) .errorOut(errorOutputsFor(401, 403, 404)) - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .withOptionalUser .serverLogicPure { user => { case (articleId, language, fallback) => @@ -356,7 +356,7 @@ trait DraftController { .in("ids") .summary("Fetch articles that matches ids parameter.") .description("Returns articles that matches ids parameter.") - .out(jsonBody[Seq[Article]]) + .out(jsonBody[Seq[ArticleDTO]]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(DRAFT_API_WRITE) .in(articleIds) @@ -386,7 +386,7 @@ trait DraftController { ) .in(language) .in(fallback) - .out(jsonBody[Seq[Article]]) + .out(jsonBody[Seq[ArticleDTO]]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => @@ -402,7 +402,7 @@ trait DraftController { .summary("Get internal id of article for a specified ndla_node_id") .description("Get internal id of article for a specified ndla_node_id") .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[ContentId]) + .out(jsonBody[ContentIdDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => @@ -419,7 +419,7 @@ trait DraftController { .summary("Show all valid licenses") .description("Shows all valid licenses") .errorOut(errorOutputsFor(401, 403)) - .out(jsonBody[Seq[License]]) + .out(jsonBody[Seq[LicenseDTO]]) .in(filterNot) .in(filter) .serverLogicPure { case (filterNot, filter) => @@ -434,21 +434,21 @@ trait DraftController { } licenses - .map(x => License(x.license.toString, Option(x.description), x.url)) + .map(x => LicenseDTO(x.license.toString, Option(x.description), x.url)) .asRight } def newArticle: ServerEndpoint[Any, Eff] = endpoint.post .summary("Create a new article") .description("Creates a new article") - .in(jsonBody[NewArticle]) + .in(jsonBody[NewArticleDTO]) .in(externalIds) .in(oldCreatedDate) .in(oldUpdatedDate) .in(externalSubjects) .in(importId) .errorOut(errorOutputsFor(401, 403)) - .out(statusCode(StatusCode.Created).and(jsonBody[Article])) + .out(statusCode(StatusCode.Created).and(jsonBody[ArticleDTO])) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => params => val ( @@ -479,14 +479,14 @@ trait DraftController { .in(pathArticleId) .summary("Update an existing article") .description("Update an existing article") - .in(jsonBody[UpdatedArticle]) + .in(jsonBody[UpdatedArticleDTO]) .in(externalIds) .in(oldCreatedDate) .in(oldUpdatedDate) .in(externalSubjects) .in(importId) .errorOut(errorOutputsFor(401, 403, 404, 409, 502)) - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => params => val ( @@ -521,7 +521,7 @@ trait DraftController { .description("Update status of an article") .in(query[Boolean]("import_publish").default(false)) .errorOut(errorOutputsFor(401, 403, 404)) - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => { case (id, status, isImported) => @@ -539,9 +539,9 @@ trait DraftController { .summary("Validate an article") .description("Validate an article") .in(query[Boolean]("import_validate").default(false)) - .in(jsonBody[Option[UpdatedArticle]]) + .in(jsonBody[Option[UpdatedArticleDTO]]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[ContentId]) + .out(jsonBody[ContentIdDTO]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => @@ -560,7 +560,7 @@ trait DraftController { .in(pathArticleId / "language" / pathLanguage) .summary("Delete language from article") .description("Delete language from article") - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => @@ -591,7 +591,7 @@ trait DraftController { .in(language) .in(fallback) .in(copiedTitleFlag) - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => @@ -608,9 +608,9 @@ trait DraftController { .description("Partial publish selected fields") .in(language) .in(fallback) - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .errorOut(errorOutputsFor(401, 403, 404)) - .in(jsonBody[Seq[PartialArticleFields]]) + .in(jsonBody[Seq[PartialArticleFieldsDTO]]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => { case (articleId, language, fallback, articleFieldsToUpdate) => @@ -631,8 +631,8 @@ trait DraftController { .summary("Partial publish selected fields for multiple articles") .description("Partial publish selected fields for multiple articles") .in(language) - .in(jsonBody[PartialBulkArticles]) - .out(jsonBody[MultiPartialPublishResult]) + .in(jsonBody[PartialBulkArticlesDTO]) + .out(jsonBody[MultiPartialPublishResultDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => @@ -661,7 +661,7 @@ trait DraftController { .in("slug" / articleSlug) .summary("Show article with a specified slug") .description("Shows the article for the specified slug.") - .out(jsonBody[Article]) + .out(jsonBody[ArticleDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .in(language) .in(fallback) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/controller/FileController.scala b/draft-api/src/main/scala/no/ndla/draftapi/controller/FileController.scala index 3a633b9b40..643c6dbf65 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/controller/FileController.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/controller/FileController.scala @@ -54,7 +54,7 @@ trait FileController { .summary("Uploads provided file") .description("Uploads provided file") .in(multipartBody[FileForm]) - .out(jsonBody[api.UploadedFile]) + .out(jsonBody[api.UploadedFileDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { diff --git a/draft-api/src/main/scala/no/ndla/draftapi/controller/InternController.scala b/draft-api/src/main/scala/no/ndla/draftapi/controller/InternController.scala index dea66ac076..eb7bf62427 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/controller/InternController.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/controller/InternController.scala @@ -10,7 +10,7 @@ package no.ndla.draftapi.controller import no.ndla.common.model.domain.draft.{Draft, DraftStatus} import no.ndla.draftapi.Props import no.ndla.draftapi.integration.ArticleApiClient -import no.ndla.draftapi.model.api.{ArticleDomainDump, ArticleDump, ContentId, NotFoundException} +import no.ndla.draftapi.model.api.{ArticleDomainDumpDTO, ArticleDumpDTO, ContentIdDTO, NotFoundException} import no.ndla.draftapi.model.domain.{ArticleIds, ImportId} import no.ndla.draftapi.repository.DraftRepository import no.ndla.draftapi.service.* @@ -209,7 +209,7 @@ trait InternController { .in(query[Int]("page-size").default(250)) .in(query[String]("language").default(Language.AllLanguages)) .in(query[Boolean]("fallback").default(false)) - .out(jsonBody[ArticleDump]) + .out(jsonBody[ArticleDumpDTO]) .serverLogicPure { case (pageNo, pageSize, lang, fallback) => readService.getArticlesByPage(pageNo, pageSize, lang, fallback).asRight } @@ -220,7 +220,7 @@ trait InternController { user: TokenUser, maxRetries: Int = 10, retries: Int = 0 - ): Try[ContentId] = { + ): Try[ContentIdDTO] = { articleApiClient.deleteArticle(id, user) match { case Failure(_) if retries <= maxRetries => deleteArticleWithRetries(id, user, maxRetries, retries + 1) case Failure(ex) => Failure(ex) @@ -230,7 +230,7 @@ trait InternController { def deleteArticle: ServerEndpoint[Any, Eff] = endpoint.delete .in("article" / path[Long]("id")) - .out(jsonBody[ContentId]) + .out(jsonBody[ContentIdDTO]) .errorOut(errorOutputsFor(404)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { user => id => @@ -243,7 +243,7 @@ trait InternController { .in("dump" / "article") .in(query[Int]("page").default(1)) .in(query[Int]("page-size").default(250)) - .out(jsonBody[ArticleDomainDump]) + .out(jsonBody[ArticleDomainDumpDTO]) .serverLogicPure { case (pageNo, pageSize) => readService.getArticleDomainDump(pageNo, pageSize).asRight } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/controller/UserDataController.scala b/draft-api/src/main/scala/no/ndla/draftapi/controller/UserDataController.scala index 40eddd6ad0..334719aad1 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/controller/UserDataController.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/controller/UserDataController.scala @@ -8,7 +8,7 @@ package no.ndla.draftapi.controller import io.circe.generic.auto.* -import no.ndla.draftapi.model.api.{ErrorHandling, UpdatedUserData, UserData} +import no.ndla.draftapi.model.api.{ErrorHandling, UpdatedUserDataDTO, UserDataDTO} import no.ndla.draftapi.service.{ReadService, WriteService} import no.ndla.network.tapir.NoNullJsonPrinter.* import no.ndla.network.tapir.TapirController @@ -34,7 +34,7 @@ trait UserDataController { def getUserData: ServerEndpoint[Any, Eff] = endpoint.get .summary("Retrieves user's data") .description("Retrieves user's data") - .out(jsonBody[UserData]) + .out(jsonBody[UserDataDTO]) .errorOut(errorOutputsFor(401, 403)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { userInfo => _ => @@ -44,8 +44,8 @@ trait UserDataController { def updateUserData: ServerEndpoint[Any, Eff] = endpoint.patch .summary("Update data of logged in user") .description("Update data of logged in user") - .in(jsonBody[UpdatedUserData]) - .out(jsonBody[UserData]) + .in(jsonBody[UpdatedUserDataDTO]) + .out(jsonBody[UserDataDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { userInfo => updatedUserData => diff --git a/draft-api/src/main/scala/no/ndla/draftapi/integration/ArticleApiClient.scala b/draft-api/src/main/scala/no/ndla/draftapi/integration/ArticleApiClient.scala index 2f4bf22247..1e1eb8bb7a 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/integration/ArticleApiClient.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/integration/ArticleApiClient.scala @@ -19,7 +19,7 @@ import no.ndla.common.model.domain.Availability import no.ndla.common.model.{NDLADate, RelatedContentLink, domain as common} import no.ndla.draftapi.Props import no.ndla.draftapi.model.api -import no.ndla.draftapi.model.api.{ArticleApiValidationError, ContentId} +import no.ndla.draftapi.model.api.{ArticleApiValidationErrorDTO, ContentIdDTO} import no.ndla.draftapi.service.ConverterService import no.ndla.network.NdlaClient import no.ndla.network.model.HttpRequestException @@ -76,11 +76,11 @@ trait ArticleApiClient { def unpublishArticle(article: Draft, user: TokenUser): Try[Draft] = { val id = article.id.get - post[ContentId](s"$InternalEndpoint/article/$id/unpublish/", Some(user)).map(_ => article) + post[ContentIdDTO](s"$InternalEndpoint/article/$id/unpublish/", Some(user)).map(_ => article) } - def deleteArticle(id: Long, user: TokenUser): Try[ContentId] = { - delete[ContentId](s"$InternalEndpoint/article/$id/", Some(user)) + def deleteArticle(id: Long, user: TokenUser): Try[ContentIdDTO] = { + delete[ContentIdDTO](s"$InternalEndpoint/article/$id/", Some(user)) } def validateArticle( @@ -95,7 +95,7 @@ trait ArticleApiClient { ("import_validate", importValidate.toString) ) match { case Failure(ex: HttpRequestException) => - val validationError = ex.httpResponse.map(r => CirceUtil.unsafeParseAs[ArticleApiValidationError](r.body)) + val validationError = ex.httpResponse.map(r => CirceUtil.unsafeParseAs[ArticleApiValidationErrorDTO](r.body)) Failure( new ValidationException( "Failed to validate article in article-api", @@ -153,9 +153,9 @@ trait ArticleApiClient { availability: Option[Availability], grepCodes: Option[Seq[String]], license: Option[String], - metaDescription: Option[Seq[api.ArticleMetaDescription]], + metaDescription: Option[Seq[api.ArticleMetaDescriptionDTO]], relatedContent: Option[Seq[common.RelatedContent]], - tags: Option[Seq[api.ArticleTag]], + tags: Option[Seq[api.ArticleTagDTO]], revisionDate: UpdateOrDelete[NDLADate], published: Option[NDLADate] ) { @@ -166,23 +166,23 @@ trait ArticleApiClient { tags .find(t => t.language == language) .toSeq - .map(t => api.ArticleTag(t.tags, t.language)) + .map(t => api.ArticleTagDTO(t.tags, t.language)) .some ) def withTags(tags: Seq[common.Tag]): PartialPublishArticle = - copy(tags = tags.map(t => api.ArticleTag(t.tags, t.language)).some) + copy(tags = tags.map(t => api.ArticleTagDTO(t.tags, t.language)).some) def withRelatedContent(relatedContent: Seq[common.RelatedContent]): PartialPublishArticle = copy(relatedContent = relatedContent.some) def withMetaDescription(meta: Seq[common.Description], language: String): PartialPublishArticle = copy(metaDescription = meta .find(m => m.language == language) - .map(m => api.ArticleMetaDescription(m.content, m.language)) + .map(m => api.ArticleMetaDescriptionDTO(m.content, m.language)) .toSeq .some ) def withMetaDescription(meta: Seq[common.Description]): PartialPublishArticle = - copy(metaDescription = meta.map(m => api.ArticleMetaDescription(m.content, m.language)).some) + copy(metaDescription = meta.map(m => api.ArticleMetaDescriptionDTO(m.content, m.language)).some) def withAvailability(availability: Availability): PartialPublishArticle = copy(availability = availability.some) def withEarliestRevisionDate(revisionMeta: Seq[common.draft.RevisionMeta]): PartialPublishArticle = { diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationError.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationErrorDTO.scala similarity index 59% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationError.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationErrorDTO.scala index 7f52de40c9..c63e2b4158 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationError.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleApiValidationErrorDTO.scala @@ -11,13 +11,13 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import no.ndla.common.errors.ValidationMessage -case class ArticleApiValidationError( +case class ArticleApiValidationErrorDTO( code: String, description: String, messages: Seq[ValidationMessage] ) -object ArticleApiValidationError { - implicit val encoder: Encoder[ArticleApiValidationError] = deriveEncoder - implicit val decoder: Decoder[ArticleApiValidationError] = deriveDecoder +object ArticleApiValidationErrorDTO { + implicit val encoder: Encoder[ArticleApiValidationErrorDTO] = deriveEncoder + implicit val decoder: Decoder[ArticleApiValidationErrorDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContent.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContentDTO.scala similarity index 72% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContent.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContentDTO.scala index e1bed07110..29175e9253 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContent.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleContentDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("The content of the article in the specified language") -case class ArticleContent( +case class ArticleContentDTO( @description("The html content") content: String, @description("ISO 639-1 code that represents the language used in the content") language: String ) -object ArticleContent { - implicit def encoder: Encoder[ArticleContent] = deriveEncoder - implicit def decoder: Decoder[ArticleContent] = deriveDecoder +object ArticleContentDTO { + implicit def encoder: Encoder[ArticleContentDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleContentDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/Article.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDTO.scala similarity index 76% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/Article.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDTO.scala index 628361b92d..72995ecf98 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/Article.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDTO.scala @@ -11,52 +11,52 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import no.ndla.common.implicits._ import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.draft.Comment -import no.ndla.common.model.api.{DraftCopyright, RelatedContent, RelatedContentLink} +import no.ndla.common.model.api.draft.CommentDTO +import no.ndla.common.model.api.{DraftCopyrightDTO, RelatedContent, RelatedContentLinkDTO} import sttp.tapir.Schema.annotations.description // format: off @description("Information about the article") -case class Article( +case class ArticleDTO( @description("The unique id of the article") id: Long, @description("Link to article on old platform") oldNdlaUrl: Option[String], @description("The revision number for the article") revision: Int, - @description("The status of this article") status: Status, - @description("Available titles for the article") title: Option[ArticleTitle], - @description("The content of the article in available languages") content: Option[ArticleContent], - @description("Describes the copyright information for the article") copyright: Option[DraftCopyright], - @description("Searchable tags for the article") tags: Option[ArticleTag], - @description("Required libraries in order to render the article") requiredLibraries: Seq[RequiredLibrary], - @description("A visual element article") visualElement: Option[VisualElement], - @description("An introduction for the article") introduction: Option[ArticleIntroduction], - @description("Meta description for the article") metaDescription: Option[ArticleMetaDescription], - @description("Meta image for the article") metaImage: Option[ArticleMetaImage], + @description("The status of this article") status: StatusDTO, + @description("Available titles for the article") title: Option[ArticleTitleDTO], + @description("The content of the article in available languages") content: Option[ArticleContentDTO], + @description("Describes the copyright information for the article") copyright: Option[DraftCopyrightDTO], + @description("Searchable tags for the article") tags: Option[ArticleTagDTO], + @description("Required libraries in order to render the article") requiredLibraries: Seq[RequiredLibraryDTO], + @description("A visual element article") visualElement: Option[VisualElementDTO], + @description("An introduction for the article") introduction: Option[ArticleIntroductionDTO], + @description("Meta description for the article") metaDescription: Option[ArticleMetaDescriptionDTO], + @description("Meta image for the article") metaImage: Option[ArticleMetaImageDTO], @description("When the article was created") created: NDLADate, @description("When the article was last updated") updated: NDLADate, @description("By whom the article was last updated") updatedBy: String, @description("When the article was last published") published: NDLADate, @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: String, @description("The languages this article supports") supportedLanguages: Seq[String], - @description("The notes for this article draft") notes: Seq[EditorNote], + @description("The notes for this article draft") notes: Seq[EditorNoteDTO], @description("The labels attached to this article; meant for editors.") editorLabels: Seq[String], @description("A list of codes from GREP API connected to the article") grepCodes: Seq[String], @description("A list of conceptIds connected to the article") conceptIds: Seq[Long], @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: String, @description("A list of content related to the article") relatedContent: Seq[RelatedContent], - @description("A list of revisions planned for the article") revisions: Seq[RevisionMeta], - @description("Object with data representing the editor responsible for this article") responsible: Option[DraftResponsible], + @description("A list of revisions planned for the article") revisions: Seq[RevisionMetaDTO], + @description("Object with data representing the editor responsible for this article") responsible: Option[DraftResponsibleDTO], @description("The path to the frontpage article") slug: Option[String], - @description("Information about comments attached to the article") comments: Seq[Comment], + @description("Information about comments attached to the article") comments: Seq[CommentDTO], @description("If the article should be prioritized") prioritized: Boolean, @description("If the article should be prioritized. Possible values are prioritized, on-hold, unspecified") priority: String, @description("If the article has been edited after last status or responsible change") started: Boolean, - @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluation], + @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluationDTO], ) -object Article { - implicit def relatedContentEnc: Encoder[Either[RelatedContentLink, Long]] = eitherEncoder[RelatedContentLink, Long] - implicit def relatedContentDec: Decoder[Either[RelatedContentLink, Long]] = eitherDecoder[RelatedContentLink, Long] +object ArticleDTO { + implicit def relatedContentEnc: Encoder[Either[RelatedContentLinkDTO, Long]] = eitherEncoder[RelatedContentLinkDTO, Long] + implicit def relatedContentDec: Decoder[Either[RelatedContentLinkDTO, Long]] = eitherDecoder[RelatedContentLinkDTO, Long] - implicit def encoder: Encoder[Article] = deriveEncoder - implicit def decoder: Decoder[Article] = deriveDecoder + implicit def encoder: Encoder[ArticleDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDump.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDumpDTO.scala similarity index 94% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDump.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDumpDTO.scala index da0a082c43..41cc0517aa 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDump.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleDomainDumpDTO.scala @@ -11,7 +11,7 @@ import no.ndla.common.model.domain.draft import sttp.tapir.Schema.annotations.description @description("Information about articles") -case class ArticleDomainDump( +case class ArticleDomainDumpDTO( @description("The total number of articles in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroduction.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroductionDTO.scala similarity index 74% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroduction.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroductionDTO.scala index 9c728fb0b1..97875d374d 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroduction.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleIntroductionDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of the article introduction") -case class ArticleIntroduction( +case class ArticleIntroductionDTO( @description("The introduction content") introduction: String, @description("The html introduction content") htmlIntroduction: String, @description( @@ -20,7 +20,7 @@ case class ArticleIntroduction( ) language: String ) -object ArticleIntroduction { - implicit def encoder: Encoder[ArticleIntroduction] = deriveEncoder - implicit def decoder: Decoder[ArticleIntroduction] = deriveDecoder +object ArticleIntroductionDTO { + implicit def encoder: Encoder[ArticleIntroductionDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleIntroductionDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescription.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescriptionDTO.scala similarity index 70% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescription.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescriptionDTO.scala index cd1e6054d2..c83fdbdc50 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescription.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaDescriptionDTO.scala @@ -12,14 +12,14 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta description of the article") -case class ArticleMetaDescription( +case class ArticleMetaDescriptionDTO( @description("The meta description") metaDescription: String, @description( "The ISO 639-1 language code describing which article translation this meta description belongs to" ) language: String ) -object ArticleMetaDescription { - implicit def encoder: Encoder[ArticleMetaDescription] = deriveEncoder - implicit def decoder: Decoder[ArticleMetaDescription] = deriveDecoder +object ArticleMetaDescriptionDTO { + implicit def encoder: Encoder[ArticleMetaDescriptionDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleMetaDescriptionDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImage.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImageDTO.scala similarity index 73% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImage.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImageDTO.scala index 03aafc7a2a..5f9bd9887d 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImage.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleMetaImageDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta description of the article") -case class ArticleMetaImage( +case class ArticleMetaImageDTO( @description("The meta image") url: String, @description("The meta image alt text") alt: String, @description( @@ -20,7 +20,7 @@ case class ArticleMetaImage( ) language: String ) -object ArticleMetaImage { - implicit def encoder: Encoder[ArticleMetaImage] = deriveEncoder - implicit def decoder: Decoder[ArticleMetaImage] = deriveDecoder +object ArticleMetaImageDTO { + implicit def encoder: Encoder[ArticleMetaImageDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleMetaImageDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticlePublishReport.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticlePublishReport.scala deleted file mode 100644 index c9b5e11bce..0000000000 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticlePublishReport.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Part of NDLA draft-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.draftapi.model.api - -import sttp.tapir.Schema.annotations.description - -@description("Id for a single Article") -case class ArticlePublishReport( - @description("The ids of articles which was successfully (un)published") succeeded: Seq[Long], - @description("The ids of articles which failed to (un)publish") failed: Seq[FailedArticlePublish] -) { - def addFailed(fail: FailedArticlePublish): ArticlePublishReport = this.copy(failed = failed :+ fail) - def addSuccessful(id: Long): ArticlePublishReport = this.copy(succeeded = succeeded :+ id) -} - -case class FailedArticlePublish( - @description("The id of an article which failed to be (un)published") id: Long, - @description("A message describing the cause") message: String -) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParams.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParamsDTO.scala similarity index 87% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParams.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParamsDTO.scala index bc8397f668..0f9649a7b2 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParams.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchParamsDTO.scala @@ -14,7 +14,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class ArticleSearchParams( +case class ArticleSearchParamsDTO( @description("The search query") query: Option[String], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], @description("Return only articles with provided license.") license: Option[String], @@ -28,7 +28,7 @@ case class ArticleSearchParams( @description("Return only articles containing codes from GREP API") grepCodes: Option[List[String]] ) -object ArticleSearchParams { - implicit def encoder: Encoder[ArticleSearchParams] = deriveEncoder - implicit def decoder: Decoder[ArticleSearchParams] = deriveDecoder +object ArticleSearchParamsDTO { + implicit def encoder: Encoder[ArticleSearchParamsDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleSearchParamsDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResult.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResultDTO.scala similarity index 92% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResult.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResultDTO.scala index 84baff63c9..89a6255b7a 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResult.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSearchResultDTO.scala @@ -10,9 +10,9 @@ package no.ndla.draftapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class ArticleSearchResult( +case class ArticleSearchResultDTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, - @description("The search results") results: Seq[ArticleSummary] + @description("The search results") results: Seq[ArticleSummaryDTO] ) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummary.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummaryDTO.scala similarity index 88% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummary.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummaryDTO.scala index b80ffd060c..5525dbb86f 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummary.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleSummaryDTO.scala @@ -12,19 +12,19 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Short summary of information about the article") -case class ArticleSummary( +case class ArticleSummaryDTO( @description("The unique id of the article") id: Long, - @description("The title of the article") title: ArticleTitle, - @description("A visual element article") visualElement: Option[VisualElement], - @description("An introduction for the article") introduction: Option[ArticleIntroduction], + @description("The title of the article") title: ArticleTitleDTO, + @description("A visual element article") visualElement: Option[VisualElementDTO], + @description("An introduction for the article") introduction: Option[ArticleIntroductionDTO], @description("The full url to where the complete information about the article can be found") url: String, @description("Describes the license of the article") license: String, @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: String, @description("A list of available languages for this audio") supportedLanguages: Seq[String], - @description("Searchable tags for the article") tags: Option[ArticleTag], + @description("Searchable tags for the article") tags: Option[ArticleTagDTO], @description("The notes for this draft article") notes: Seq[String], @description("The users saved for this draft article") users: Seq[String], @description("The codes from GREP API registered for this draft article") grepCodes: Seq[String], - @description("The status of this article") status: Status, + @description("The status of this article") status: StatusDTO, @description("When the article was last updated") updated: NDLADate ) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTag.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTagDTO.scala similarity index 73% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTag.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTagDTO.scala index 40b52f5ba6..f2be9e1b45 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTag.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTagDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of the tags of the article") -case class ArticleTag( +case class ArticleTagDTO( @description("The searchable tag.") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) -object ArticleTag { - implicit def encoder: Encoder[ArticleTag] = deriveEncoder - implicit def decoder: Decoder[ArticleTag] = deriveDecoder +object ArticleTagDTO { + implicit def encoder: Encoder[ArticleTagDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleTagDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitle.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitleDTO.scala similarity index 75% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitle.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitleDTO.scala index cf8eefa1bf..9334663fdc 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitle.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ArticleTitleDTO.scala @@ -12,13 +12,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of a title") -case class ArticleTitle( +case class ArticleTitleDTO( @description("The freetext title of the article") title: String, @description("The freetext html title of the article") htmlTitle: String, @description("ISO 639-1 code that represents the language used in title") language: String ) -object ArticleTitle { - implicit def encoder: Encoder[ArticleTitle] = deriveEncoder - implicit def decoder: Decoder[ArticleTitle] = deriveDecoder +object ArticleTitleDTO { + implicit def encoder: Encoder[ArticleTitleDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleTitleDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentId.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentIdDTO.scala similarity index 57% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentId.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentIdDTO.scala index 1f10a5e081..614c21f16a 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentId.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ContentIdDTO.scala @@ -12,9 +12,9 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Id for a single Article") -case class ContentId(@description("The unique id of the article") id: Long) +case class ContentIdDTO(@description("The unique id of the article") id: Long) -object ContentId { - implicit val encoder: Encoder[ContentId] = deriveEncoder - implicit val decoder: Decoder[ContentId] = deriveDecoder +object ContentIdDTO { + implicit val encoder: Encoder[ContentIdDTO] = deriveEncoder + implicit val decoder: Decoder[ContentIdDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsible.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsibleDTO.scala similarity index 67% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsible.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsibleDTO.scala index a3f88524b8..e46f2adc20 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsible.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/DraftResponsibleDTO.scala @@ -12,14 +12,13 @@ import io.circe.{Decoder, Encoder} import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description -// format: off @description("Information about the responsible") -case class DraftResponsible( +case class DraftResponsibleDTO( @description("NDLA ID of responsible editor") responsibleId: String, - @description("Date of when the responsible editor was last updated") lastUpdated: NDLADate, + @description("Date of when the responsible editor was last updated") lastUpdated: NDLADate ) -object DraftResponsible { - implicit def encoder: Encoder[DraftResponsible] = deriveEncoder - implicit def decoder: Decoder[DraftResponsible] = deriveDecoder +object DraftResponsibleDTO { + implicit def encoder: Encoder[DraftResponsibleDTO] = deriveEncoder + implicit def decoder: Decoder[DraftResponsibleDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNote.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNoteDTO.scala similarity index 76% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNote.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNoteDTO.scala index 6207a4fa5a..96a869e315 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNote.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/EditorNoteDTO.scala @@ -12,14 +12,14 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about the editorial notes") -case class EditorNote( +case class EditorNoteDTO( @description("Editorial note") note: String, @description("User which saved the note") user: String, - @description("Status of article at saved time") status: Status, + @description("Status of article at saved time") status: StatusDTO, @description("Timestamp of when note was saved") timestamp: NDLADate ) -object EditorNote { - implicit def encoder: Encoder[EditorNote] = deriveEncoder - implicit def decoder: Decoder[EditorNote] = deriveDecoder +object EditorNoteDTO { + implicit def encoder: Encoder[EditorNoteDTO] = deriveEncoder + implicit def decoder: Decoder[EditorNoteDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResult.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResultDTO.scala similarity index 83% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResult.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResultDTO.scala index 88006092e2..342cfbf594 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResult.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/MultiPartialPublishResultDTO.scala @@ -10,13 +10,13 @@ package no.ndla.draftapi.model.api import sttp.tapir.Schema.annotations.description @description("Single failed result") -case class PartialPublishFailure( +case class PartialPublishFailureDTO( @description("Id of the article in question") id: Long, @description("Error message") message: String ) @description("A list of articles that were partial published to article-api") -case class MultiPartialPublishResult( +case class MultiPartialPublishResultDTO( @description("Successful ids") successes: Seq[Long], - @description("Failed ids with error messages") failures: Seq[PartialPublishFailure] + @description("Failed ids with error messages") failures: Seq[PartialPublishFailureDTO] ) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticle.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleDTO.scala similarity index 75% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticle.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleDTO.scala index de386afd12..f9fd4c3fd0 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticle.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleDTO.scala @@ -11,12 +11,12 @@ import no.ndla.common.implicits.* import io.circe.{Decoder, Encoder} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.{DraftCopyright, RelatedContentLink} +import no.ndla.common.model.api.{DraftCopyrightDTO, RelatedContentLinkDTO} import sttp.tapir.Schema.annotations.description // format: off @description("Information about the article") -case class NewArticle( +case class NewArticleDTO( @description("The chosen language") language: String, @description("The title of the article") title: String, @description("The date the article is published") published: Option[NDLADate], @@ -24,30 +24,30 @@ case class NewArticle( @description("Searchable tags") tags: Option[Seq[String]], @description("An introduction") introduction: Option[String], @description("A meta description") metaDescription: Option[String], - @description("Meta image for the article") metaImage: Option[NewArticleMetaImage], + @description("Meta image for the article") metaImage: Option[NewArticleMetaImageDTO], @description("A visual element for the article. May be anything from an image to a video or H5P") visualElement: Option[String], - @description("Describes the copyright information for the article") copyright: Option[DraftCopyright], - @description("Required libraries in order to render the article") requiredLibraries: Option[Seq[RequiredLibrary]], + @description("Describes the copyright information for the article") copyright: Option[DraftCopyrightDTO], + @description("Required libraries in order to render the article") requiredLibraries: Option[Seq[RequiredLibraryDTO]], @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: String, @description("The notes for this article draft") notes: Option[Seq[String]], @description("The labels attached to this article; meant for editors.") editorLabels: Option[Seq[String]], @description("A list of codes from GREP API connected to the article") grepCodes: Option[Seq[String]], @description("A list of conceptIds connected to the article") conceptIds: Option[Seq[Long]], @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: Option[String], - @description("A list of content related to the article") relatedContent: Option[Seq[Either[RelatedContentLink, Long]]], - @description("An object describing a future revision") revisionMeta: Option[Seq[RevisionMeta]], + @description("A list of content related to the article") relatedContent: Option[Seq[Either[RelatedContentLinkDTO, Long]]], + @description("An object describing a future revision") revisionMeta: Option[Seq[RevisionMetaDTO]], @description("NDLA ID representing the editor responsible for this article") responsibleId: Option[String], @description("The path to the frontpage article") slug: Option[String], - @description("Information about a comment attached to an article") comments: Option[List[NewComment]], + @description("Information about a comment attached to an article") comments: Option[List[NewCommentDTO]], @description("If the article should be prioritized") prioritized: Option[Boolean], @description("If the article should be prioritized. Possible values are prioritized, on-hold, unspecified") priority: Option[String], - @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluation], + @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluationDTO], ) // format: on -object NewArticle { - implicit def eitherEnc: Encoder[Either[RelatedContentLink, Long]] = eitherEncoder[RelatedContentLink, Long] - implicit def eitherDec: Decoder[Either[RelatedContentLink, Long]] = eitherDecoder[RelatedContentLink, Long] - implicit def encoder: Encoder[NewArticle] = deriveEncoder - implicit def decoder: Decoder[NewArticle] = deriveDecoder +object NewArticleDTO { + implicit def eitherEnc: Encoder[Either[RelatedContentLinkDTO, Long]] = eitherEncoder[RelatedContentLinkDTO, Long] + implicit def eitherDec: Decoder[Either[RelatedContentLinkDTO, Long]] = eitherDecoder[RelatedContentLinkDTO, Long] + implicit def encoder: Encoder[NewArticleDTO] = deriveEncoder + implicit def decoder: Decoder[NewArticleDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImage.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImageDTO.scala similarity index 56% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImage.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImageDTO.scala index 49d32ac63d..8e0830d886 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImage.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewArticleMetaImageDTO.scala @@ -12,13 +12,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema import sttp.tapir.Schema.annotations.description -case class NewArticleMetaImage( +case class NewArticleMetaImageDTO( @description("The image-api id of the meta image") id: String, @description("The alt text of the meta image") alt: String ) -object NewArticleMetaImage { - implicit def schema: Schema[NewArticleMetaImage] = Schema.derived - implicit def encoder: Encoder[NewArticleMetaImage] = deriveEncoder[NewArticleMetaImage] - implicit def decoder: Decoder[NewArticleMetaImage] = deriveDecoder[NewArticleMetaImage] +object NewArticleMetaImageDTO { + implicit def schema: Schema[NewArticleMetaImageDTO] = Schema.derived + implicit def encoder: Encoder[NewArticleMetaImageDTO] = deriveEncoder[NewArticleMetaImageDTO] + implicit def decoder: Decoder[NewArticleMetaImageDTO] = deriveDecoder[NewArticleMetaImageDTO] } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewComment.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewCommentDTO.scala similarity index 72% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/NewComment.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/NewCommentDTO.scala index 7e02576d8a..bcbeca4aca 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewComment.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/NewCommentDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a comment attached to an article") -case class NewComment( +case class NewCommentDTO( @description("Content of the comment") content: String, @description("If the comment is open or closed") isOpen: Option[Boolean] ) -object NewComment { - implicit def encoder: Encoder[NewComment] = deriveEncoder - implicit def decoder: Decoder[NewComment] = deriveDecoder +object NewCommentDTO { + implicit def encoder: Encoder[NewCommentDTO] = deriveEncoder + implicit def decoder: Decoder[NewCommentDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/PartialPublishArticle.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/PartialPublishArticle.scala index c5f9523e6d..d19fd4ee5e 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/PartialPublishArticle.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/PartialPublishArticle.scala @@ -10,24 +10,23 @@ package no.ndla.draftapi.model.api import enumeratum._ import sttp.tapir.Schema.annotations.description -sealed trait PartialArticleFields extends EnumEntry +sealed trait PartialArticleFieldsDTO extends EnumEntry -object PartialArticleFields extends Enum[PartialArticleFields] with CirceEnum[PartialArticleFields] { - override val values: IndexedSeq[PartialArticleFields] = findValues +object PartialArticleFieldsDTO extends Enum[PartialArticleFieldsDTO] with CirceEnum[PartialArticleFieldsDTO] { + override val values: IndexedSeq[PartialArticleFieldsDTO] = findValues - case object availability extends PartialArticleFields - case object grepCodes extends PartialArticleFields - case object license extends PartialArticleFields - case object metaDescription extends PartialArticleFields - case object relatedContent extends PartialArticleFields - case object tags extends PartialArticleFields - case object revisionDate extends PartialArticleFields - case object published extends PartialArticleFields + case object availability extends PartialArticleFieldsDTO + case object grepCodes extends PartialArticleFieldsDTO + case object license extends PartialArticleFieldsDTO + case object metaDescription extends PartialArticleFieldsDTO + case object relatedContent extends PartialArticleFieldsDTO + case object tags extends PartialArticleFieldsDTO + case object revisionDate extends PartialArticleFieldsDTO + case object published extends PartialArticleFieldsDTO } -// format: off @description("Partial data about articles to publish in bulk") -case class PartialBulkArticles( +case class PartialBulkArticlesDTO( @description("A list of article ids to partially publish") articleIds: Seq[Long], - @description("A list of fields that should be partially published") fields: Seq[PartialArticleFields], + @description("A list of fields that should be partially published") fields: Seq[PartialArticleFieldsDTO] ) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluation.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluationDTO.scala similarity index 71% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluation.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluationDTO.scala index 920559a00d..87d7fae7c8 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluation.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/QualityEvaluationDTO.scala @@ -13,12 +13,12 @@ import no.ndla.common.model.domain.draft.Grade import sttp.tapir.Schema.annotations.description @description("Quality evaluation of the article") -case class QualityEvaluation( +case class QualityEvaluationDTO( @description("The grade (1-5) of the article") grade: Grade, @description("Note explaining the score") note: Option[String] ) -object QualityEvaluation { - implicit def encoder: Encoder[QualityEvaluation] = deriveEncoder - implicit def decoder: Decoder[QualityEvaluation] = deriveDecoder +object QualityEvaluationDTO { + implicit def encoder: Encoder[QualityEvaluationDTO] = deriveEncoder + implicit def decoder: Decoder[QualityEvaluationDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibrary.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibraryDTO.scala similarity index 70% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibrary.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibraryDTO.scala index 405fbc079c..c340b614b1 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibrary.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/RequiredLibraryDTO.scala @@ -12,13 +12,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a library required to render the article") -case class RequiredLibrary( +case class RequiredLibraryDTO( @description("The type of the library. E.g. CSS or JavaScript") mediaType: String, @description("The name of the library") name: String, @description("The full url to where the library can be downloaded") url: String ) -object RequiredLibrary { - implicit def encoder: Encoder[RequiredLibrary] = deriveEncoder[RequiredLibrary] - implicit def decoder: Decoder[RequiredLibrary] = deriveDecoder[RequiredLibrary] +object RequiredLibraryDTO { + implicit def encoder: Encoder[RequiredLibraryDTO] = deriveEncoder[RequiredLibraryDTO] + implicit def decoder: Decoder[RequiredLibraryDTO] = deriveDecoder[RequiredLibraryDTO] } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMeta.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMetaDTO.scala similarity index 77% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMeta.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMetaDTO.scala index ee171ce014..75d636b805 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMeta.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/RevisionMetaDTO.scala @@ -12,16 +12,15 @@ import io.circe.{Decoder, Encoder} import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description -// format: off @description("Information about the editorial notes") -case class RevisionMeta( +case class RevisionMetaDTO( @description("An unique uuid of the revision. If none supplied, one is generated.") id: Option[String], @description("A date on which the article would need to be revised") revisionDate: NDLADate, @description("Notes to keep track of what needs to happen before revision") note: String, @description("Status of a revision, either 'revised' or 'needs-revision'") status: String ) -object RevisionMeta { - implicit def encoder: Encoder[RevisionMeta] = deriveEncoder[RevisionMeta] - implicit def decoder: Decoder[RevisionMeta] = deriveDecoder[RevisionMeta] +object RevisionMetaDTO { + implicit def encoder: Encoder[RevisionMetaDTO] = deriveEncoder[RevisionMetaDTO] + implicit def decoder: Decoder[RevisionMetaDTO] = deriveDecoder[RevisionMetaDTO] } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearch.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearchDTO.scala similarity index 70% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearch.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearchDTO.scala index a68499d33b..0d6791f576 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearch.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/SavedSearchDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about saved search") -case class SavedSearch( +case class SavedSearchDTO( @description("The search url") searchUrl: String, @description("The search phrase") searchPhrase: String ) -object SavedSearch { - implicit def encoder: Encoder[SavedSearch] = deriveEncoder - implicit def decoder: Decoder[SavedSearch] = deriveDecoder +object SavedSearchDTO { + implicit def encoder: Encoder[SavedSearchDTO] = deriveEncoder + implicit def decoder: Decoder[SavedSearchDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResult.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResultDTO.scala similarity index 83% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResult.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResultDTO.scala index cd80c3a986..45c3bdc595 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResult.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/SearchResultDTO.scala @@ -12,16 +12,16 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class SearchResult( +case class SearchResultDTO( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ArticleSummary] + @description("The search results") results: Seq[ArticleSummaryDTO] ) @description("Information and metadata about codes from GREP API") -case class GrepCodesSearchResult( +case class GrepCodesSearchResultDTO( @description("The total number of codes from GREP API matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @@ -29,7 +29,7 @@ case class GrepCodesSearchResult( ) @description("Information about tags-search-results") -case class TagsSearchResult( +case class TagsSearchResultDTO( @description("The total number of tags matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @@ -38,15 +38,15 @@ case class TagsSearchResult( ) @description("Information about articles") -case class ArticleDump( +case class ArticleDumpDTO( @description("The total number of articles in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[Article] + @description("The search results") results: Seq[ArticleDTO] ) -object ArticleDump { - implicit def encoder: Encoder[ArticleDump] = deriveEncoder - implicit def decoder: Decoder[ArticleDump] = deriveDecoder +object ArticleDumpDTO { + implicit def encoder: Encoder[ArticleDumpDTO] = deriveEncoder + implicit def decoder: Decoder[ArticleDumpDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/Status.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/StatusDTO.scala similarity index 72% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/Status.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/StatusDTO.scala index c33bd44652..11bb1bc82f 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/Status.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/StatusDTO.scala @@ -11,12 +11,12 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description -case class Status( +case class StatusDTO( @description("The current status of the article") current: String, @description("Previous statuses this article has been in") other: Seq[String] ) -object Status { - implicit def encoder: Encoder[Status] = deriveEncoder - implicit def decoder: Decoder[Status] = deriveDecoder +object StatusDTO { + implicit def encoder: Encoder[StatusDTO] = deriveEncoder + implicit def decoder: Decoder[StatusDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/TSTypes.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/TSTypes.scala index 654a687d4f..fa2a411449 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/TSTypes.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/TSTypes.scala @@ -9,7 +9,7 @@ package no.ndla.draftapi.model.api import com.scalatsi.TypescriptType.TSNull import com.scalatsi._ -import no.ndla.common.model.api.{Author, RelatedContentLink} +import no.ndla.common.model.api.{AuthorDTO, RelatedContentLinkDTO} /** The `scala-tsi` plugin is not always able to derive the types that are used in `Seq` or other generic types. * Therefore we need to explicitly load the case classes here. This is only necessary if the `sbt generateTypescript` @@ -20,9 +20,9 @@ object TSTypes { // See: https://github.com/scala-tsi/scala-tsi/issues/172 implicit val nullTsType: TSType[Null] = TSType(TSNull) - implicit val author: TSIType[Author] = TSType.fromCaseClass[Author] - implicit val requiredLibrary: TSIType[RequiredLibrary] = TSType.fromCaseClass[RequiredLibrary] - implicit val editorNote: TSIType[EditorNote] = TSType.fromCaseClass[EditorNote] - implicit val relatedContentLink: TSIType[RelatedContentLink] = TSType.fromCaseClass[RelatedContentLink] - implicit val newArticleMetaImage: TSIType[NewArticleMetaImage] = TSType.fromCaseClass[NewArticleMetaImage] + implicit val author: TSIType[AuthorDTO] = TSType.fromCaseClass[AuthorDTO] + implicit val requiredLibrary: TSIType[RequiredLibraryDTO] = TSType.fromCaseClass[RequiredLibraryDTO] + implicit val editorNote: TSIType[EditorNoteDTO] = TSType.fromCaseClass[EditorNoteDTO] + implicit val relatedContentLink: TSIType[RelatedContentLinkDTO] = TSType.fromCaseClass[RelatedContentLinkDTO] + implicit val newArticleMetaImage: TSIType[NewArticleMetaImageDTO] = TSType.fromCaseClass[NewArticleMetaImageDTO] } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticle.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticleDTO.scala similarity index 75% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticle.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticleDTO.scala index 76fd58380a..cb24244a22 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticle.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedArticleDTO.scala @@ -12,13 +12,13 @@ import no.ndla.common.implicits._ import io.circe.{Decoder, Encoder} import io.circe.generic.semiauto._ import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.{DraftCopyright, RelatedContent, RelatedContentLink, UpdateOrDelete} +import no.ndla.common.model.api.{DraftCopyrightDTO, RelatedContent, RelatedContentLinkDTO, UpdateOrDelete} import sttp.tapir.Schema.annotations.description import com.scalatsi._ // format: off @description("Information about the article") -case class UpdatedArticle( +case class UpdatedArticleDTO( @description("The revision number for the article") revision: Int, @description("The chosen language") language: Option[String], @description("The title of the article") title: Option[String], @@ -28,10 +28,10 @@ case class UpdatedArticle( @description("Searchable tags") tags: Option[Seq[String]], @description("An introduction") introduction: Option[String], @description("A meta description") metaDescription: Option[String], - @description("An image-api ID for the article meta image") metaImage: UpdateOrDelete[NewArticleMetaImage], + @description("An image-api ID for the article meta image") metaImage: UpdateOrDelete[NewArticleMetaImageDTO], @description("A visual element for the article. May be anything from an image to a video or H5P") visualElement: Option[String], - @description("Describes the copyright information for the article") copyright: Option[DraftCopyright], - @description("Required libraries in order to render the article") requiredLibraries: Option[Seq[RequiredLibrary]], + @description("Describes the copyright information for the article") copyright: Option[DraftCopyrightDTO], + @description("Required libraries in order to render the article") requiredLibraries: Option[Seq[RequiredLibraryDTO]], @description("The type of article this is. Possible values are frontpage-article, standard, topic-article") articleType: Option[String], @description("The notes for this article draft") notes: Option[Seq[String]], @description("The labels attached to this article; meant for editors.") editorLabels: Option[Seq[String]], @@ -39,30 +39,29 @@ case class UpdatedArticle( @description("A list of conceptIds connected to the article") conceptIds: Option[Seq[Long]], @description("Stores the new article as a separate version. Useful when making big changes that should be revertable.") createNewVersion: Option[Boolean], @description("Value that dictates who gets to see the article. Possible values are: everyone/teacher") availability: Option[String], - @description("A list of content related to the article") relatedContent: Option[Seq[Either[RelatedContentLink, Long]]], - @description("A list of all revisions of the article") revisionMeta: Option[Seq[RevisionMeta]], + @description("A list of content related to the article") relatedContent: Option[Seq[Either[RelatedContentLinkDTO, Long]]], + @description("A list of all revisions of the article") revisionMeta: Option[Seq[RevisionMetaDTO]], @description("NDLA ID representing the editor responsible for this article") responsibleId: UpdateOrDelete[String], @description("The path to the frontpage article") slug: Option[String], - @description("Information about a comment attached to an article") comments: Option[List[UpdatedComment]], + @description("Information about a comment attached to an article") comments: Option[List[UpdatedCommentDTO]], @description("If the article should be prioritized") prioritized: Option[Boolean], @description("If the article should be prioritized. Possible values are prioritized, on-hold, unspecified") priority: Option[String], - @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluation], - - ) + @description("The quality evaluation of the article. Consist of a score from 1 to 5 and a comment.") qualityEvaluation : Option[QualityEvaluationDTO], +) // format: on -object UpdatedArticle { - implicit def relatedContentEncoder: Encoder[RelatedContent] = eitherEncoder[RelatedContentLink, Long] - implicit def relatedContentDecoder: Decoder[RelatedContent] = eitherDecoder[RelatedContentLink, Long] +object UpdatedArticleDTO { + implicit def relatedContentEncoder: Encoder[RelatedContent] = eitherEncoder[RelatedContentLinkDTO, Long] + implicit def relatedContentDecoder: Decoder[RelatedContent] = eitherDecoder[RelatedContentLinkDTO, Long] - implicit def encoder: Encoder[UpdatedArticle] = deriveEncoder[UpdatedArticle] - implicit def decoder: Decoder[UpdatedArticle] = deriveDecoder[UpdatedArticle] + implicit def encoder: Encoder[UpdatedArticleDTO] = deriveEncoder[UpdatedArticleDTO] + implicit def decoder: Decoder[UpdatedArticleDTO] = deriveDecoder[UpdatedArticleDTO] - implicit val typescriptUpdatedArticle: TSType[UpdatedArticle] = TSType.fromCaseClass[UpdatedArticle] - implicit def typescriptNewMetaImage: TSType[NewArticleMetaImage] = TSType.fromCaseClass[NewArticleMetaImage] - implicit def typescriptNewMetaImageUnion: TSType[UpdateOrDelete[NewArticleMetaImage]] = { - TSType.alias[UpdateOrDelete[NewArticleMetaImage]]( - "UpdateOrDeleteNewArticleMetaImage", + implicit val typescriptUpdatedArticle: TSType[UpdatedArticleDTO] = TSType.fromCaseClass[UpdatedArticleDTO] + implicit def typescriptNewMetaImage: TSType[NewArticleMetaImageDTO] = TSType.fromCaseClass[NewArticleMetaImageDTO] + implicit def typescriptNewMetaImageUnion: TSType[UpdateOrDelete[NewArticleMetaImageDTO]] = { + TSType.alias[UpdateOrDelete[NewArticleMetaImageDTO]]( + "UpdateOrDeleteNewArticleMetaImageDTO", TSUnion(Seq(TSNull, TSUndefined, typescriptNewMetaImage.get)) ) } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedComment.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedCommentDTO.scala similarity index 76% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedComment.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedCommentDTO.scala index cf1d48bd52..8284949147 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedComment.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedCommentDTO.scala @@ -12,14 +12,14 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a comment attached to an article") -case class UpdatedComment( +case class UpdatedCommentDTO( @description("Id of the comment") id: Option[String], @description("Content of the comment") content: String, @description("If the comment is open or closed") isOpen: Option[Boolean], @description("If the comment is solved or not") solved: Option[Boolean] ) -object UpdatedComment { - implicit def encoder: Encoder[UpdatedComment] = deriveEncoder - implicit def decoder: Decoder[UpdatedComment] = deriveDecoder +object UpdatedCommentDTO { + implicit def encoder: Encoder[UpdatedCommentDTO] = deriveEncoder + implicit def decoder: Decoder[UpdatedCommentDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserData.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserDataDTO.scala similarity index 91% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserData.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserDataDTO.scala index 7cdddf0ece..dcfdb608b7 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserData.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UpdatedUserDataDTO.scala @@ -10,8 +10,8 @@ package no.ndla.draftapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about user data") -case class UpdatedUserData( - @description("User's saved searches") savedSearches: Option[Seq[SavedSearch]], +case class UpdatedUserDataDTO( + @description("User's saved searches") savedSearches: Option[Seq[SavedSearchDTO]], @description("User's last edited articles") latestEditedArticles: Option[Seq[String]], @description("User's last edited concepts") latestEditedConcepts: Option[Seq[String]], @description("User's favorite subjects") favoriteSubjects: Option[Seq[String]] diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFile.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFileDTO.scala similarity index 75% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFile.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFileDTO.scala index 93cc08fe85..6543bc2d6f 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFile.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UploadedFileDTO.scala @@ -11,14 +11,14 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about the uploaded file") -case class UploadedFile( +case class UploadedFileDTO( @description("Uploaded file's basename") filename: String, @description("Uploaded file's mime type") mime: String, @description("Uploaded file's file extension") extension: String, @description("Full path of uploaded file") path: String ) -object UploadedFile { - implicit val encoder: Encoder[UploadedFile] = deriveEncoder - implicit val decoder: Decoder[UploadedFile] = deriveDecoder +object UploadedFileDTO { + implicit val encoder: Encoder[UploadedFileDTO] = deriveEncoder + implicit val decoder: Decoder[UploadedFileDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UserData.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UserDataDTO.scala similarity index 92% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/UserData.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/UserDataDTO.scala index 0c38dac2c4..459c7a0270 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/UserData.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/UserDataDTO.scala @@ -10,9 +10,9 @@ package no.ndla.draftapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about user data") -case class UserData( +case class UserDataDTO( @description("The auth0 id of the user") userId: String, - @description("User's saved searches") savedSearches: Option[Seq[SavedSearch]], + @description("User's saved searches") savedSearches: Option[Seq[SavedSearchDTO]], @description("User's last edited articles") latestEditedArticles: Option[Seq[String]], @description("User's last edited concepts") latestEditedConcepts: Option[Seq[String]], @description("User's favorite subjects") favoriteSubjects: Option[Seq[String]] diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ValidationError.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/ValidationError.scala deleted file mode 100644 index b6d9ce0920..0000000000 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/ValidationError.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Part of NDLA draft-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.draftapi.model.api - -import no.ndla.common.errors.ValidationMessage -import sttp.tapir.Schema.annotations.description - -import java.time.LocalDateTime - -@description("Information about validation errors") -case class ValidationError( - @description("Code stating the type of error") code: String, - @description("Description of the error") description: String, - @description("List of validation messages") messages: Seq[ValidationMessage], - @description("When the error occured") occuredAt: LocalDateTime = LocalDateTime.now() -) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElement.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElementDTO.scala similarity index 76% rename from draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElement.scala rename to draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElementDTO.scala index 7e823e2bb0..c013e2904b 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElement.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/api/VisualElementDTO.scala @@ -12,7 +12,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Description of a visual element") -case class VisualElement( +case class VisualElementDTO( @description( "Html containing the visual element. May contain any legal html element, including the embed-tag" ) visualElement: String, @@ -21,7 +21,7 @@ case class VisualElement( ) language: String ) -object VisualElement { - implicit def encoder: Encoder[VisualElement] = deriveEncoder - implicit def decoder: Decoder[VisualElement] = deriveDecoder +object VisualElementDTO { + implicit def encoder: Encoder[VisualElementDTO] = deriveEncoder + implicit def decoder: Decoder[VisualElementDTO] = deriveDecoder } diff --git a/draft-api/src/main/scala/no/ndla/draftapi/model/domain/Content.scala b/draft-api/src/main/scala/no/ndla/draftapi/model/domain/Content.scala index 2cabc74d97..ea5c08ea60 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/model/domain/Content.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/model/domain/Content.scala @@ -13,7 +13,7 @@ import no.ndla.common.CirceUtil import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.Content import no.ndla.common.model.domain.draft.{Draft, DraftCopyright} -import no.ndla.draftapi.model.api.SavedSearch +import no.ndla.draftapi.model.api.SavedSearchDTO import scalikejdbc.* case class Agreement( @@ -29,7 +29,7 @@ case class Agreement( case class UserData( id: Option[Long], userId: String, - savedSearches: Option[Seq[SavedSearch]], + savedSearches: Option[Seq[SavedSearchDTO]], latestEditedArticles: Option[Seq[String]], latestEditedConcepts: Option[Seq[String]], favoriteSubjects: Option[Seq[String]] diff --git a/draft-api/src/main/scala/no/ndla/draftapi/service/ConverterService.scala b/draft-api/src/main/scala/no/ndla/draftapi/service/ConverterService.scala index 62b8cb942f..0d6f41e176 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/service/ConverterService.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/service/ConverterService.scala @@ -12,7 +12,7 @@ import com.typesafe.scalalogging.StrictLogging import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.errors.{ValidationException, ValidationMessage} import no.ndla.common.implicits.TryQuestionMark -import no.ndla.common.model.api.{Delete, DraftCopyright, Missing, UpdateWith, draft} +import no.ndla.common.model.api.{Delete, DraftCopyrightDTO, Missing, UpdateWith, draft} import no.ndla.common.model.domain.{ArticleContent, Priority, Responsible} import no.ndla.common.model.domain.draft.DraftStatus.{IMPORTED, PLANNED} import no.ndla.common.model.domain.draft.{Comment, Draft, DraftStatus} @@ -20,7 +20,7 @@ import no.ndla.common.model.{NDLADate, RelatedContentLink, api as commonApi, dom import no.ndla.common.{Clock, UUIDUtil, model} import no.ndla.draftapi.Props import no.ndla.draftapi.integration.ArticleApiClient -import no.ndla.draftapi.model.api.{NewComment, NotFoundException, UpdatedArticle, UpdatedComment} +import no.ndla.draftapi.model.api.{NewCommentDTO, NotFoundException, UpdatedArticleDTO, UpdatedCommentDTO} import no.ndla.draftapi.model.{api, domain} import no.ndla.draftapi.repository.DraftRepository import no.ndla.language.Language.{AllLanguages, UnknownLanguage, findByLanguageOrBestEffort, mergeLanguageFields} @@ -45,7 +45,7 @@ trait ConverterService { def toDomainArticle( newArticleId: Long, - newArticle: api.NewArticle, + newArticle: api.NewArticleDTO, externalIds: List[String], user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], @@ -130,7 +130,7 @@ trait ConverterService { } private[service] def updatedCommentToDomain( - updatedComments: List[UpdatedComment], + updatedComments: List[UpdatedCommentDTO], existingComments: Seq[Comment] ): Seq[Comment] = { updatedComments.map(updatedComment => { @@ -157,7 +157,7 @@ trait ConverterService { }) } - private[service] def newCommentToDomain(newComment: List[NewComment]): Seq[Comment] = { + private[service] def newCommentToDomain(newComment: List[NewCommentDTO]): Seq[Comment] = { newComment.map(comment => Comment( id = UUID.randomUUID(), @@ -171,7 +171,7 @@ trait ConverterService { } private[service] def qualityEvaluationToDomain( - newQualityEvaluation: Option[api.QualityEvaluation] + newQualityEvaluation: Option[api.QualityEvaluationDTO] ): Option[common.draft.QualityEvaluation] = newQualityEvaluation.map(qe => common.draft.QualityEvaluation(grade = qe.grade, note = qe.note)) @@ -186,7 +186,7 @@ trait ConverterService { } private[service] def updatedCommentToDomainNullDocument( - updatedComments: List[UpdatedComment] + updatedComments: List[UpdatedCommentDTO] ): Try[Seq[Comment]] = { updatedComments.traverse(comment => comment.id match { @@ -216,7 +216,7 @@ trait ConverterService { ) } - private def toDomainRevisionMeta(revisionMeta: api.RevisionMeta): common.draft.RevisionMeta = { + private def toDomainRevisionMeta(revisionMeta: api.RevisionMetaDTO): common.draft.RevisionMeta = { common.draft.RevisionMeta( id = revisionMeta.id.map(UUID.fromString).getOrElse(uuidUtil.randomUUID()), revisionDate = revisionMeta.revisionDate, @@ -225,8 +225,8 @@ trait ConverterService { ) } - private def toApiRevisionMeta(revisionMeta: common.draft.RevisionMeta): api.RevisionMeta = { - api.RevisionMeta( + private def toApiRevisionMeta(revisionMeta: common.draft.RevisionMeta): api.RevisionMetaDTO = { + api.RevisionMetaDTO( id = Some(revisionMeta.id.toString), revisionDate = revisionMeta.revisionDate, note = revisionMeta.note, @@ -254,10 +254,10 @@ trait ConverterService { } - private def toDomainTitle(articleTitle: api.ArticleTitle): common.Title = + private def toDomainTitle(articleTitle: api.ArticleTitleDTO): common.Title = common.Title(articleTitle.title, articleTitle.language) - private def toDomainContent(articleContent: api.ArticleContent): common.ArticleContent = { + private def toDomainContent(articleContent: api.ArticleContentDTO): common.ArticleContent = { common.ArticleContent(removeUnknownEmbedTagAttribute(articleContent.content), articleContent.language) } @@ -276,10 +276,10 @@ trait ConverterService { private def toDomainMetaDescription(meta: String, language: String): common.Description = common.Description(meta, language) - private def toDomainMetaImage(metaImage: api.NewArticleMetaImage, language: String): common.ArticleMetaImage = + private def toDomainMetaImage(metaImage: api.NewArticleMetaImageDTO, language: String): common.ArticleMetaImage = common.ArticleMetaImage(metaImage.id, metaImage.alt, language) - private def toDomainCopyright(copyright: DraftCopyright): common.draft.DraftCopyright = { + private def toDomainCopyright(copyright: DraftCopyrightDTO): common.draft.DraftCopyright = { common.draft.DraftCopyright( license = copyright.license.map(_.license), origin = copyright.origin, @@ -336,7 +336,7 @@ trait ConverterService { }) } - private def toDomainRequiredLibraries(requiredLibs: api.RequiredLibrary): common.RequiredLibrary = { + private def toDomainRequiredLibraries(requiredLibs: api.RequiredLibraryDTO): common.RequiredLibrary = { common.RequiredLibrary(requiredLibs.mediaType, requiredLibs.name, requiredLibs.url) } @@ -365,13 +365,13 @@ trait ConverterService { isImported: Boolean ): Try[Draft] = StateTransitionRules.doTransition(draft, status, user, isImported) - private def toApiResponsible(responsible: Responsible): api.DraftResponsible = - api.DraftResponsible( + private def toApiResponsible(responsible: Responsible): api.DraftResponsibleDTO = + api.DraftResponsibleDTO( responsibleId = responsible.responsibleId, lastUpdated = responsible.lastUpdated ) - def toApiArticle(article: Draft, language: String, fallback: Boolean = false): Try[api.Article] = { + def toApiArticle(article: Draft, language: String, fallback: Boolean = false): Try[api.ArticleDTO] = { val isLanguageNeutral = article.supportedLanguages.contains(UnknownLanguage.toString) && article.supportedLanguages.length == 1 @@ -388,7 +388,7 @@ trait ConverterService { val responsible = article.responsible.map(toApiResponsible) Success( - api.Article( + api.ArticleDTO( id = article.id.get, oldNdlaUrl = article.id.flatMap(id => getLinkToOldNdla(id)(ReadOnlyAutoSession)), revision = article.revision.get, @@ -434,8 +434,8 @@ trait ConverterService { } } - def toApiUserData(userData: domain.UserData): api.UserData = { - api.UserData( + def toApiUserData(userData: domain.UserData): api.UserDataDTO = { + api.UserDataDTO( userId = userData.userId, savedSearches = userData.savedSearches, latestEditedArticles = userData.latestEditedArticles, @@ -444,28 +444,28 @@ trait ConverterService { ) } - private def toApiEditorNote(note: common.EditorNote): api.EditorNote = - api.EditorNote(note.note, note.user, toApiStatus(note.status), note.timestamp) + private def toApiEditorNote(note: common.EditorNote): api.EditorNoteDTO = + api.EditorNoteDTO(note.note, note.user, toApiStatus(note.status), note.timestamp) - private def toApiStatus(status: common.Status): api.Status = - api.Status(status.current.toString, status.other.map(_.toString).toSeq) + private def toApiStatus(status: common.Status): api.StatusDTO = + api.StatusDTO(status.current.toString, status.other.map(_.toString).toSeq) - def toApiArticleTitle(title: common.Title): api.ArticleTitle = - api.ArticleTitle(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) + def toApiArticleTitle(title: common.Title): api.ArticleTitleDTO = + api.ArticleTitleDTO(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) - private def toApiArticleContent(content: common.ArticleContent): api.ArticleContent = - api.ArticleContent(content.content, content.language) + private def toApiArticleContent(content: common.ArticleContent): api.ArticleContentDTO = + api.ArticleContentDTO(content.content, content.language) - private def toApiArticleMetaImage(metaImage: common.ArticleMetaImage): api.ArticleMetaImage = { - api.ArticleMetaImage( + private def toApiArticleMetaImage(metaImage: common.ArticleMetaImage): api.ArticleMetaImageDTO = { + api.ArticleMetaImageDTO( s"${externalApiUrls("raw-image")}/${metaImage.imageId}", metaImage.altText, metaImage.language ) } - private def toApiCopyright(copyright: common.draft.DraftCopyright): DraftCopyright = { - model.api.DraftCopyright( + private def toApiCopyright(copyright: common.draft.DraftCopyright): DraftCopyrightDTO = { + model.api.DraftCopyrightDTO( copyright.license.map(toApiLicense), copyright.origin, copyright.creators.map(_.toApi), @@ -477,20 +477,20 @@ trait ConverterService { ) } - def toApiLicense(shortLicense: String): commonApi.License = { + def toApiLicense(shortLicense: String): commonApi.LicenseDTO = { getLicense(shortLicense) - .map(l => commonApi.License(l.license.toString, Option(l.description), l.url)) - .getOrElse(commonApi.License("unknown", None, None)) + .map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)) + .getOrElse(commonApi.LicenseDTO("unknown", None, None)) } private def toApiRelatedContent(relatedContent: common.RelatedContent): commonApi.RelatedContent = { relatedContent match { - case Left(x) => Left(commonApi.RelatedContentLink(url = x.url, title = x.title)) + case Left(x) => Left(commonApi.RelatedContentLinkDTO(url = x.url, title = x.title)) case Right(x) => Right(x) } } - private def toApiComment(comment: Comment): draft.Comment = draft.Comment( + private def toApiComment(comment: Comment): draft.CommentDTO = draft.CommentDTO( id = comment.id.toString, content = comment.content, created = comment.created, @@ -501,29 +501,29 @@ trait ConverterService { private def toApiQualityEvaluation( qualityEvaluation: Option[common.draft.QualityEvaluation] - ): Option[api.QualityEvaluation] = { - qualityEvaluation.map(qe => api.QualityEvaluation(grade = qe.grade, note = qe.note)) + ): Option[api.QualityEvaluationDTO] = { + qualityEvaluation.map(qe => api.QualityEvaluationDTO(grade = qe.grade, note = qe.note)) } - def toApiArticleTag(tag: common.Tag): api.ArticleTag = api.ArticleTag(tag.tags, tag.language) + def toApiArticleTag(tag: common.Tag): api.ArticleTagDTO = api.ArticleTagDTO(tag.tags, tag.language) - private def toApiRequiredLibrary(required: common.RequiredLibrary): api.RequiredLibrary = { - api.RequiredLibrary(required.mediaType, required.name, required.url) + private def toApiRequiredLibrary(required: common.RequiredLibrary): api.RequiredLibraryDTO = { + api.RequiredLibraryDTO(required.mediaType, required.name, required.url) } - def toApiVisualElement(visual: common.VisualElement): api.VisualElement = - api.VisualElement(visual.resource, visual.language) + def toApiVisualElement(visual: common.VisualElement): api.VisualElementDTO = + api.VisualElementDTO(visual.resource, visual.language) - def toApiArticleIntroduction(intro: common.Introduction): api.ArticleIntroduction = { - api.ArticleIntroduction( + def toApiArticleIntroduction(intro: common.Introduction): api.ArticleIntroductionDTO = { + api.ArticleIntroductionDTO( Jsoup.parseBodyFragment(intro.introduction).body().text(), intro.introduction, intro.language ) } - private def toApiArticleMetaDescription(metaDescription: common.Description): api.ArticleMetaDescription = { - api.ArticleMetaDescription(metaDescription.content, metaDescription.language) + private def toApiArticleMetaDescription(metaDescription: common.Description): api.ArticleMetaDescriptionDTO = { + api.ArticleMetaDescriptionDTO(metaDescription.content, metaDescription.language) } private def createLinkToOldNdla(nodeId: String): String = s"//red.ndla.no/node/$nodeId" @@ -626,7 +626,7 @@ trait ConverterService { } } - private def languageFieldIsDefined(article: api.UpdatedArticle): Boolean = { + private def languageFieldIsDefined(article: api.UpdatedArticleDTO): Boolean = { val metaImageExists = article.metaImage match { case UpdateWith(_) => true case _ => false @@ -686,7 +686,7 @@ trait ConverterService { private def getNewEditorialNotes( isNewLanguage: Boolean, user: TokenUser, - article: api.UpdatedArticle, + article: api.UpdatedArticleDTO, toMergeInto: Draft ): Try[Seq[common.EditorNote]] = { val newLanguageEditorNote = @@ -709,7 +709,7 @@ trait ConverterService { addedNotes.map(n => toMergeInto.notes ++ n) } - private def getNewResponsible(toMergeInto: Draft, article: UpdatedArticle) = + private def getNewResponsible(toMergeInto: Draft, article: UpdatedArticleDTO) = (article.responsibleId, toMergeInto.responsible) match { case (Delete, _) => None case (UpdateWith(responsibleId), None) => Some(Responsible(responsibleId, clock.now())) @@ -718,7 +718,7 @@ trait ConverterService { case (_, existing) => existing } - private def getNewPriority(toMergeInto: Draft, article: UpdatedArticle) = + private def getNewPriority(toMergeInto: Draft, article: UpdatedArticleDTO) = article.priority .map(v => common.Priority.valueOfOrError(v).getOrElse(toMergeInto.priority)) .getOrElse( @@ -729,7 +729,7 @@ trait ConverterService { } ) - private def getNewMetaImage(toMergeInto: Draft, maybeLang: Option[String], updatedArticle: UpdatedArticle) = + private def getNewMetaImage(toMergeInto: Draft, maybeLang: Option[String], updatedArticle: UpdatedArticleDTO) = maybeLang .map(lang => updatedArticle.metaImage match { @@ -744,7 +744,7 @@ trait ConverterService { def toDomainArticle( toMergeInto: Draft, - article: api.UpdatedArticle, + article: api.UpdatedArticleDTO, isImported: Boolean, user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], @@ -778,13 +778,15 @@ trait ConverterService { val updatedTitles = mergeLanguageFields( toMergeInto.title, maybeLang - .traverse(lang => articleWithNewContent.title.toSeq.map(t => toDomainTitle(api.ArticleTitle(t, t, lang)))) + .traverse(lang => articleWithNewContent.title.toSeq.map(t => toDomainTitle(api.ArticleTitleDTO(t, t, lang)))) .flatten ) val updatedContents = mergeLanguageFields( toMergeInto.content, maybeLang - .traverse(lang => articleWithNewContent.content.toSeq.map(c => toDomainContent(api.ArticleContent(c, lang)))) + .traverse(lang => + articleWithNewContent.content.toSeq.map(c => toDomainContent(api.ArticleContentDTO(c, lang))) + ) .flatten ) val updatedTags = mergeLanguageFields( @@ -851,7 +853,7 @@ trait ConverterService { def toDomainArticle( id: Long, - article: api.UpdatedArticle, + article: api.UpdatedArticleDTO, isImported: Boolean, user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], @@ -953,8 +955,8 @@ trait ConverterService { case None => Success(buildTransitionsMap(user, None)) } - def toApiArticleGrepCodes(result: domain.LanguagelessSearchResult[String]): api.GrepCodesSearchResult = { - api.GrepCodesSearchResult(result.totalCount, result.page.getOrElse(1), result.pageSize, result.results) + def toApiArticleGrepCodes(result: domain.LanguagelessSearchResult[String]): api.GrepCodesSearchResultDTO = { + api.GrepCodesSearchResultDTO(result.totalCount, result.page.getOrElse(1), result.pageSize, result.results) } def addNote(article: Draft, noteText: String, user: TokenUser): Draft = { diff --git a/draft-api/src/main/scala/no/ndla/draftapi/service/ReadService.scala b/draft-api/src/main/scala/no/ndla/draftapi/service/ReadService.scala index a3f2f90a6d..76ab5310fe 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/service/ReadService.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/service/ReadService.scala @@ -41,24 +41,24 @@ trait ReadService { class ReadService { - def getInternalArticleIdByExternalId(externalId: Long): Option[api.ContentId] = - draftRepository.getIdFromExternalId(externalId.toString)(ReadOnlyAutoSession).map(id => api.ContentId(id)) + def getInternalArticleIdByExternalId(externalId: Long): Option[api.ContentIdDTO] = + draftRepository.getIdFromExternalId(externalId.toString)(ReadOnlyAutoSession).map(id => api.ContentIdDTO(id)) - def withId(id: Long, language: String, fallback: Boolean = false): Try[api.Article] = { + def withId(id: Long, language: String, fallback: Boolean = false): Try[api.ArticleDTO] = { draftRepository.withId(id)(ReadOnlyAutoSession).map(addUrlsOnEmbedResources) match { case None => Failure(NotFoundException(s"The article with id $id was not found")) case Some(article) => converterService.toApiArticle(article, language, fallback) } } - def getArticleBySlug(slug: String, language: String, fallback: Boolean = false): Try[api.Article] = { + def getArticleBySlug(slug: String, language: String, fallback: Boolean = false): Try[api.ArticleDTO] = { draftRepository.withSlug(slug)(ReadOnlyAutoSession).map(addUrlsOnEmbedResources) match { case None => Failure(NotFoundException(s"The article with slug '$slug' was not found")) case Some(article) => converterService.toApiArticle(article, language, fallback) } } - def getArticles(id: Long, language: String, fallback: Boolean): Seq[api.Article] = { + def getArticles(id: Long, language: String, fallback: Boolean): Seq[api.ArticleDTO] = { draftRepository .articlesWithId(id) .map(addUrlsOnEmbedResources) @@ -76,32 +76,32 @@ trait ReadService { article.copy(content = articleWithUrls, visualElement = visualElementWithUrls) } - def getArticlesByPage(pageNo: Int, pageSize: Int, lang: String, fallback: Boolean = false): api.ArticleDump = { + def getArticlesByPage(pageNo: Int, pageSize: Int, lang: String, fallback: Boolean = false): api.ArticleDumpDTO = { val (safePageNo, safePageSize) = (max(pageNo, 1), max(pageSize, 0)) draftRepository.withSession { implicit session => val results = draftRepository .getArticlesByPage(safePageSize, (safePageNo - 1) * safePageSize) .flatMap(article => converterService.toApiArticle(article, lang, fallback).toOption) - api.ArticleDump(draftRepository.articleCount, pageNo, pageSize, lang, results) + api.ArticleDumpDTO(draftRepository.articleCount, pageNo, pageSize, lang, results) } } - def getArticleDomainDump(pageNo: Int, pageSize: Int): api.ArticleDomainDump = { + def getArticleDomainDump(pageNo: Int, pageSize: Int): api.ArticleDomainDumpDTO = { draftRepository.withSession(implicit session => { val (safePageNo, safePageSize) = (max(pageNo, 1), max(pageSize, 0)) val results = draftRepository.getArticlesByPage(safePageSize, (safePageNo - 1) * safePageSize) - api.ArticleDomainDump(draftRepository.articleCount, pageNo, pageSize, results) + api.ArticleDomainDumpDTO(draftRepository.articleCount, pageNo, pageSize, results) }) } - def getAllGrepCodes(input: String, pageSize: Int, page: Int): Try[api.GrepCodesSearchResult] = { + def getAllGrepCodes(input: String, pageSize: Int, page: Int): Try[api.GrepCodesSearchResultDTO] = { val result = grepCodesSearchService.matchingQuery(input, page, pageSize) result.map(converterService.toApiArticleGrepCodes) } - def getAllTags(input: String, pageSize: Int, page: Int, language: String): Try[api.TagsSearchResult] = { + def getAllTags(input: String, pageSize: Int, page: Int, language: String): Try[api.TagsSearchResultDTO] = { val result = tagSearchService.matchingQuery( query = input, searchLanguage = language, @@ -152,7 +152,7 @@ trait ReadService { draftRepository.importIdOfArticle(externalId) } - def getUserData(userId: String): Try[api.UserData] = { + def getUserData(userId: String): Try[api.UserDataDTO] = { userDataRepository.withUserId(userId) match { case None => writeService.newUserData(userId) match { @@ -169,7 +169,7 @@ trait ReadService { fallback: Boolean, page: Long, pageSize: Long - ): Try[Seq[api.Article]] = { + ): Try[Seq[api.ArticleDTO]] = { val offset = (page - 1) * pageSize for { ids <- diff --git a/draft-api/src/main/scala/no/ndla/draftapi/service/WriteService.scala b/draft-api/src/main/scala/no/ndla/draftapi/service/WriteService.scala index a36b30b2bb..adfa1b21b2 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/service/WriteService.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/service/WriteService.scala @@ -23,7 +23,7 @@ import no.ndla.common.model.domain.draft.{Draft, DraftStatus} import no.ndla.common.model.{NDLADate, domain as common} import no.ndla.draftapi.Props import no.ndla.draftapi.integration.* -import no.ndla.draftapi.model.api.PartialArticleFields +import no.ndla.draftapi.model.api.PartialArticleFieldsDTO import no.ndla.draftapi.model.{api, domain} import no.ndla.draftapi.repository.{DraftRepository, UserDataRepository} import no.ndla.draftapi.service.search.{ArticleIndexService, GrepCodesIndexService, TagIndexService} @@ -83,7 +83,7 @@ trait WriteService { language: String, fallback: Boolean, usePostFix: Boolean - ): Try[api.Article] = { + ): Try[api.ArticleDTO] = { draftRepository.rollbackOnFailure { implicit session => draftRepository.withId(articleId) match { case None => Failure(api.NotFoundException(s"Article with id '$articleId' was not found in database.")) @@ -154,14 +154,14 @@ trait WriteService { } def newArticle( - newArticle: api.NewArticle, + newArticle: api.NewArticleDTO, externalIds: List[String], externalSubjectIds: Seq[String], user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], oldNdlaUpdatedDate: Option[NDLADate], importId: Option[String] - ): Try[api.Article] = { + ): Try[api.ArticleDTO] = { val newNotes = Some("Opprettet artikkel" +: newArticle.notes.getOrElse(Seq.empty)) val visualElement = newArticle.visualElement.filter(_.nonEmpty) val withNotes = newArticle.copy( @@ -199,7 +199,7 @@ trait WriteService { id: Long, user: TokenUser, isImported: Boolean - ): Try[api.Article] = { + ): Try[api.ArticleDTO] = { draftRepository.withId(id)(ReadOnlyAutoSession) match { case None => Failure(api.NotFoundException(s"No article with id $id was found")) case Some(draft) => @@ -333,7 +333,7 @@ trait WriteService { draft: Draft, oldDraft: Option[Draft], statusWasUpdated: Boolean, - updatedApiArticle: api.UpdatedArticle, + updatedApiArticle: api.UpdatedArticleDTO, shouldNotAutoUpdateStatus: Boolean ): Draft = { val isAutomaticResponsibleChange = updatedApiArticle.responsibleId match { @@ -375,7 +375,7 @@ trait WriteService { private def addPartialPublishNote( draft: Draft, user: TokenUser, - partialPublishFields: Set[PartialArticleFields] + partialPublishFields: Set[PartialArticleFieldsDTO] ): Draft = if (partialPublishFields.nonEmpty) converterService.addNote(draft, "Artikkelen har blitt delpublisert", user) @@ -392,7 +392,7 @@ trait WriteService { oldArticle: Option[Draft], user: TokenUser, statusWasUpdated: Boolean, - updatedApiArticle: api.UpdatedArticle, + updatedApiArticle: api.UpdatedArticleDTO, shouldNotAutoUpdateStatus: Boolean ): Try[Draft] = { val fieldsToPartialPublish = shouldPartialPublish(oldArticle, toUpdate) @@ -482,11 +482,11 @@ trait WriteService { } private def compareField( - field: api.PartialArticleFields, + field: api.PartialArticleFieldsDTO, old: Draft, changed: Draft - ): Option[api.PartialArticleFields] = { - import api.PartialArticleFields.* + ): Option[api.PartialArticleFieldsDTO] = { + import api.PartialArticleFieldsDTO.* val shouldInclude = field match { case `availability` => old.availability != changed.availability case `grepCodes` => old.grepCodes != changed.grepCodes @@ -505,15 +505,15 @@ trait WriteService { private[service] def shouldPartialPublish( existingArticle: Option[Draft], changedArticle: Draft - ): Set[api.PartialArticleFields] = { + ): Set[api.PartialArticleFieldsDTO] = { val isPublished = changedArticle.status.current == PUBLISHED || changedArticle.status.other.contains(PUBLISHED) if (isPublished) { val changedFields = existingArticle - .map(e => api.PartialArticleFields.values.flatMap(field => compareField(field, e, changedArticle))) - .getOrElse(api.PartialArticleFields.values) + .map(e => api.PartialArticleFieldsDTO.values.flatMap(field => compareField(field, e, changedArticle))) + .getOrElse(api.PartialArticleFieldsDTO.values) changedFields.toSet } else { @@ -524,7 +524,7 @@ trait WriteService { private[service] def updateStatusIfNeeded( convertedArticle: Draft, existingArticle: Draft, - updatedApiArticle: api.UpdatedArticle, + updatedApiArticle: api.UpdatedArticleDTO, user: TokenUser, shouldNotAutoUpdateStatus: Boolean ): Try[Draft] = { @@ -541,14 +541,14 @@ trait WriteService { def updateArticle( articleId: Long, - updatedApiArticle: api.UpdatedArticle, + updatedApiArticle: api.UpdatedArticleDTO, externalIds: List[String], externalSubjectIds: Seq[String], user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], oldNdlaUpdatedDate: Option[NDLADate], importId: Option[String] - ): Try[api.Article] = { + ): Try[api.ArticleDTO] = { draftRepository.withId(articleId)(ReadOnlyAutoSession) match { case Some(existing) => updateExistingArticle( @@ -568,14 +568,14 @@ trait WriteService { private def updateExistingArticle( existing: Draft, - updatedApiArticle: api.UpdatedArticle, + updatedApiArticle: api.UpdatedArticleDTO, externalIds: List[String], externalSubjectIds: Seq[String], user: TokenUser, oldNdlaCreatedDate: Option[NDLADate], oldNdlaUpdatedDate: Option[NDLADate], importId: Option[String] - ): Try[api.Article] = for { + ): Try[api.ArticleDTO] = for { convertedArticle <- converterService.toDomainArticle( existing, updatedApiArticle, @@ -620,7 +620,7 @@ trait WriteService { ) } yield apiArticle - def deleteLanguage(id: Long, language: String, userInfo: TokenUser): Try[api.Article] = { + def deleteLanguage(id: Long, language: String, userInfo: TokenUser): Try[api.ArticleDTO] = { draftRepository.withId(id)(ReadOnlyAutoSession) match { case Some(article) => article.title.size match { @@ -640,16 +640,16 @@ trait WriteService { } - def deleteArticle(id: Long): Try[api.ContentId] = { + def deleteArticle(id: Long): Try[api.ContentIdDTO] = { draftRepository .deleteArticle(id)(AutoSession) .flatMap(articleIndexService.deleteDocument) - .map(id => api.ContentId(id)) + .map(id => api.ContentIdDTO(id)) } - def storeFile(file: UploadedFile): Try[api.UploadedFile] = + def storeFile(file: UploadedFile): Try[api.UploadedFileDTO] = uploadFile(file).map(f => - api.UploadedFile( + api.UploadedFileDTO( filename = f.fileName, mime = f.contentType, extension = f.fileExtension, @@ -715,7 +715,7 @@ trait WriteService { s"$randomString$extensionWithDot" } - def newUserData(userId: String): Try[api.UserData] = { + def newUserData(userId: String): Try[api.UserDataDTO] = { userDataRepository .insert( domain.UserData( @@ -730,7 +730,7 @@ trait WriteService { .map(converterService.toApiUserData) } - def updateUserData(updatedUserData: api.UpdatedUserData, user: TokenUser): Try[api.UserData] = { + def updateUserData(updatedUserData: api.UpdatedUserDataDTO, user: TokenUser): Try[api.UserDataDTO] = { val userId = user.id userDataRepository.withUserId(userId) match { case None => @@ -757,13 +757,13 @@ trait WriteService { private[service] def partialArticleFieldsUpdate( article: Draft, - articleFieldsToUpdate: Seq[api.PartialArticleFields], + articleFieldsToUpdate: Seq[api.PartialArticleFieldsDTO], language: String ): PartialPublishArticle = { val isAllLanguage = language == Language.AllLanguages val initialPartial = PartialPublishArticle.empty() - import api.PartialArticleFields.* + import api.PartialArticleFieldsDTO.* articleFieldsToUpdate.distinct.foldLeft(initialPartial)((partial, field) => { field match { case `availability` => partial.withAvailability(article.availability) @@ -782,18 +782,18 @@ trait WriteService { def partialPublishAndConvertToApiArticle( id: Long, - fieldsToPublish: Seq[api.PartialArticleFields], + fieldsToPublish: Seq[api.PartialArticleFieldsDTO], language: String, fallback: Boolean, user: TokenUser - ): Try[api.Article] = + ): Try[api.ArticleDTO] = partialPublish(id, fieldsToPublish, language, user)._2.flatMap(article => converterService.toApiArticle(article, language, fallback) ) def partialPublish( id: Long, - articleFieldsToUpdate: Seq[api.PartialArticleFields], + articleFieldsToUpdate: Seq[api.PartialArticleFieldsDTO], language: String, user: TokenUser ): (Long, Try[Draft]) = @@ -806,7 +806,7 @@ trait WriteService { private def partialPublishIfNeeded( article: Draft, - articleFieldsToUpdate: Seq[api.PartialArticleFields], + articleFieldsToUpdate: Seq[api.PartialArticleFieldsDTO], language: String, user: TokenUser ): Future[Try[Draft]] = { @@ -818,7 +818,7 @@ trait WriteService { private def partialPublish( article: Draft, - fieldsToPublish: Seq[api.PartialArticleFields], + fieldsToPublish: Seq[api.PartialArticleFieldsDTO], language: String, user: TokenUser ): Future[Try[Draft]] = { @@ -852,9 +852,9 @@ trait WriteService { def partialPublishMultiple( language: String, - partialBulk: api.PartialBulkArticles, + partialBulk: api.PartialBulkArticlesDTO, user: TokenUser - ): Try[api.MultiPartialPublishResult] = { + ): Try[api.MultiPartialPublishResultDTO] = { implicit val ec: ExecutionContextExecutorService = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(100)) val requestInfo = RequestInfo.fromThreadContext() @@ -878,11 +878,11 @@ trait WriteService { val successes = res.collect { case (id, Success(_)) => id } val failures = res.collect { case (id, Failure(ex)) => logger.error(s"Partial publishing $id failed with ${ex.getMessage}", ex) - api.PartialPublishFailure(id, ex.getMessage) + api.PartialPublishFailureDTO(id, ex.getMessage) } Success( - api.MultiPartialPublishResult( + api.MultiPartialPublishResultDTO( successes = successes, failures = failures ) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/service/search/ArticleSearchService.scala b/draft-api/src/main/scala/no/ndla/draftapi/service/search/ArticleSearchService.scala index de9e5137fe..7e5fb7936a 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/service/search/ArticleSearchService.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/service/search/ArticleSearchService.scala @@ -31,17 +31,17 @@ trait ArticleSearchService { with ErrorHandling => val articleSearchService: ArticleSearchService - class ArticleSearchService extends StrictLogging with SearchService[api.ArticleSummary] { + class ArticleSearchService extends StrictLogging with SearchService[api.ArticleSummaryDTO] { import props.{ElasticSearchIndexMaxResultWindow, ElasticSearchScrollKeepAlive} private val noCopyright = boolQuery().not(termQuery("license", "copyrighted")) override val searchIndex: String = props.DraftSearchIndex - override def hitToApiModel(hit: String, language: String): api.ArticleSummary = + override def hitToApiModel(hit: String, language: String): api.ArticleSummaryDTO = searchConverterService.hitAsArticleSummary(hit, language) - def matchingQuery(settings: SearchSettings): Try[SearchResult[api.ArticleSummary]] = { + def matchingQuery(settings: SearchSettings): Try[SearchResult[api.ArticleSummaryDTO]] = { val fullQuery = settings.query match { case Some(query) => @@ -72,7 +72,7 @@ trait ArticleSearchService { executeSearch(settings, fullQuery) } - def executeSearch(settings: SearchSettings, queryBuilder: BoolQuery): Try[SearchResult[api.ArticleSummary]] = { + def executeSearch(settings: SearchSettings, queryBuilder: BoolQuery): Try[SearchResult[api.ArticleSummaryDTO]] = { val articleTypesFilter = if (settings.articleTypes.nonEmpty) Some(constantScoreQuery(termsQuery("articleType", settings.articleTypes))) diff --git a/draft-api/src/main/scala/no/ndla/draftapi/service/search/SearchConverterService.scala b/draft-api/src/main/scala/no/ndla/draftapi/service/search/SearchConverterService.scala index e6f7fd46db..680847ecda 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/service/search/SearchConverterService.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/service/search/SearchConverterService.scala @@ -13,7 +13,7 @@ import no.ndla.common.CirceUtil import no.ndla.common.model.domain.draft.Draft import no.ndla.common.model.domain as common import no.ndla.draftapi.model.api -import no.ndla.draftapi.model.api.ArticleSearchResult +import no.ndla.draftapi.model.api.ArticleSearchResultDTO import no.ndla.draftapi.model.domain.SearchResult import no.ndla.draftapi.model.search.* import no.ndla.draftapi.service.ConverterService @@ -66,7 +66,7 @@ trait SearchConverterService { ) } - def hitAsArticleSummary(hitString: String, language: String): api.ArticleSummary = { + def hitAsArticleSummary(hitString: String, language: String): api.ArticleSummaryDTO = { val searchableArticle = CirceUtil.unsafeParseAs[SearchableArticle](hitString) val titles = searchableArticle.title.languageValues.map(lv => common.Title(lv.value, lv.language)) @@ -82,15 +82,15 @@ trait SearchConverterService { val title = findByLanguageOrBestEffort(titles, language) .map(converterService.toApiArticleTitle) - .getOrElse(api.ArticleTitle("", "", UnknownLanguage.toString)) + .getOrElse(api.ArticleTitleDTO("", "", UnknownLanguage.toString)) val visualElement = findByLanguageOrBestEffort(visualElements, language).map(converterService.toApiVisualElement) val introduction = findByLanguageOrBestEffort(introductions, language).map(converterService.toApiArticleIntroduction) val tag = findByLanguageOrBestEffort(tags, language).map(converterService.toApiArticleTag) val status = - api.Status(searchableArticle.status.current.toString, searchableArticle.status.other.map(_.toString).toSeq) + api.StatusDTO(searchableArticle.status.current.toString, searchableArticle.status.other.map(_.toString).toSeq) - api.ArticleSummary( + api.ArticleSummaryDTO( id = searchableArticle.id, title = title, visualElement = visualElement, @@ -142,16 +142,16 @@ trait SearchConverterService { } } - def asApiSearchResult(searchResult: SearchResult[api.ArticleSummary]): ArticleSearchResult = - api.ArticleSearchResult( + def asApiSearchResult(searchResult: SearchResult[api.ArticleSummaryDTO]): ArticleSearchResultDTO = + api.ArticleSearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, searchResult.results ) - def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResult = - api.TagsSearchResult( + def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResultDTO = + api.TagsSearchResultDTO( searchResult.totalCount, searchResult.page.getOrElse(1), searchResult.pageSize, diff --git a/draft-api/src/main/scala/no/ndla/draftapi/validation/ContentValidator.scala b/draft-api/src/main/scala/no/ndla/draftapi/validation/ContentValidator.scala index 60c5374b6a..d1bd62e048 100644 --- a/draft-api/src/main/scala/no/ndla/draftapi/validation/ContentValidator.scala +++ b/draft-api/src/main/scala/no/ndla/draftapi/validation/ContentValidator.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.domain.* import no.ndla.common.model.domain.draft.* import no.ndla.draftapi.Props import no.ndla.draftapi.integration.ArticleApiClient -import no.ndla.draftapi.model.api.{ContentId, NotFoundException, UpdatedArticle} +import no.ndla.draftapi.model.api.{ContentIdDTO, NotFoundException, UpdatedArticleDTO} import no.ndla.draftapi.repository.DraftRepository import no.ndla.draftapi.service.ConverterService import no.ndla.language.model.Iso639 @@ -130,23 +130,23 @@ trait ContentValidator { } } - def validateArticleApiArticle(id: Long, importValidate: Boolean, user: TokenUser): Try[ContentId] = { + def validateArticleApiArticle(id: Long, importValidate: Boolean, user: TokenUser): Try[ContentIdDTO] = { draftRepository.withId(id)(ReadOnlyAutoSession) match { case None => Failure(NotFoundException(s"Article with id $id does not exist")) case Some(draft) => converterService .toArticleApiArticle(draft) .flatMap(article => articleApiClient.validateArticle(article, importValidate, Some(user))) - .map(_ => ContentId(id)) + .map(_ => ContentIdDTO(id)) } } def validateArticleApiArticle( id: Long, - updatedArticle: UpdatedArticle, + updatedArticle: UpdatedArticleDTO, importValidate: Boolean, user: TokenUser - ): Try[ContentId] = { + ): Try[ContentIdDTO] = { draftRepository.withId(id)(ReadOnlyAutoSession) match { case None => Failure(NotFoundException(s"Article with id $id does not exist")) case Some(existing) => @@ -154,7 +154,7 @@ trait ContentValidator { .toDomainArticle(existing, updatedArticle, isImported = false, user, None, None) .flatMap(converterService.toArticleApiArticle) .flatMap(articleApiClient.validateArticle(_, importValidate, Some(user))) - .map(_ => ContentId(id)) + .map(_ => ContentIdDTO(id)) } } diff --git a/draft-api/src/test/scala/no/ndla/draftapi/TestData.scala b/draft-api/src/test/scala/no/ndla/draftapi/TestData.scala index 1a98586232..b7f480d935 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/TestData.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/TestData.scala @@ -9,7 +9,7 @@ package no.ndla.draftapi import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.model -import no.ndla.common.model.api.{DraftCopyright, Missing} +import no.ndla.common.model.api.{DraftCopyrightDTO, Missing} import no.ndla.common.model.domain.Priority import no.ndla.common.model.domain.draft.Draft import no.ndla.common.model.domain.draft.DraftStatus.* @@ -67,18 +67,18 @@ object TestData { val (articleId, externalId) = (1L, "751234") - val sampleArticleV2: api.Article = api.Article( + val sampleArticleV2: api.ArticleDTO = api.ArticleDTO( id = 1, oldNdlaUrl = None, revision = 1, - status = api.Status(PLANNED.toString, Seq.empty), - title = Some(api.ArticleTitle("title", "title", "nb")), - content = Some(api.ArticleContent("this is content", "nb")), + status = api.StatusDTO(PLANNED.toString, Seq.empty), + title = Some(api.ArticleTitleDTO("title", "title", "nb")), + content = Some(api.ArticleContentDTO("this is content", "nb")), copyright = Some( - DraftCopyright( - Some(commonApi.License("licence", None, None)), + DraftCopyrightDTO( + Some(commonApi.LicenseDTO("licence", None, None)), Some("origin"), - Seq(commonApi.Author("developer", "Per")), + Seq(commonApi.AuthorDTO("developer", "Per")), List(), List(), None, @@ -86,11 +86,11 @@ object TestData { false ) ), - tags = Some(api.ArticleTag(Seq("tag"), "nb")), - requiredLibraries = Seq(api.RequiredLibrary("JS", "JavaScript", "url")), + tags = Some(api.ArticleTagDTO(Seq("tag"), "nb")), + requiredLibraries = Seq(api.RequiredLibraryDTO("JS", "JavaScript", "url")), visualElement = None, introduction = None, - metaDescription = Some(api.ArticleMetaDescription("metaDesc", "nb")), + metaDescription = Some(api.ArticleMetaDescriptionDTO("metaDesc", "nb")), None, created = NDLADate.of(2017, 1, 1, 12, 15, 32), updated = NDLADate.of(2017, 4, 1, 12, 15, 32), @@ -114,7 +114,7 @@ object TestData { qualityEvaluation = None ) - val blankUpdatedArticle: UpdatedArticle = api.UpdatedArticle( + val blankUpdatedArticle: UpdatedArticleDTO = api.UpdatedArticleDTO( revision = 1, language = None, title = None, @@ -145,7 +145,7 @@ object TestData { qualityEvaluation = None ) - val sampleApiUpdateArticle: UpdatedArticle = blankUpdatedArticle.copy( + val sampleApiUpdateArticle: UpdatedArticleDTO = blankUpdatedArticle.copy( revision = 1, language = Some("nb"), title = Some("tittel") @@ -180,17 +180,17 @@ object TestData { |} """.stripMargin - val apiArticleV2: api.Article = api.Article( + val apiArticleV2: api.ArticleDTO = api.ArticleDTO( articleId, Some(s"//red.ndla.no/node/$externalId"), 2, - api.Status(PLANNED.toString, Seq.empty), - Some(api.ArticleTitle("title", "title", "nb")), - Some(api.ArticleContent("content", "nb")), + api.StatusDTO(PLANNED.toString, Seq.empty), + Some(api.ArticleTitleDTO("title", "title", "nb")), + Some(api.ArticleContentDTO("content", "nb")), Some( - model.api.DraftCopyright( + model.api.DraftCopyrightDTO( Some( - commonApi.License( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -209,7 +209,7 @@ object TestData { Seq.empty, None, None, - Some(api.ArticleMetaDescription("meta description", "nb")), + Some(api.ArticleMetaDescriptionDTO("meta description", "nb")), None, today, today, @@ -233,17 +233,17 @@ object TestData { None ) - val apiArticleUserTest: api.Article = api.Article( + val apiArticleUserTest: api.ArticleDTO = api.ArticleDTO( articleId, Some(s"//red.ndla.no/node/$externalId"), 2, - api.Status(EXTERNAL_REVIEW.toString, Seq.empty), - Some(api.ArticleTitle("title", "title", "nb")), - Some(api.ArticleContent("content", "nb")), + api.StatusDTO(EXTERNAL_REVIEW.toString, Seq.empty), + Some(api.ArticleTitleDTO("title", "title", "nb")), + Some(api.ArticleContentDTO("content", "nb")), Some( - model.api.DraftCopyright( + model.api.DraftCopyrightDTO( Some( - commonApi.License( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -262,7 +262,7 @@ object TestData { Seq.empty, None, None, - Some(api.ArticleMetaDescription("meta description", "nb")), + Some(api.ArticleMetaDescriptionDTO("meta description", "nb")), None, today, today, @@ -390,7 +390,7 @@ object TestData { None ) - val newArticle: NewArticle = api.NewArticle( + val newArticle: NewArticleDTO = api.NewArticleDTO( "en", "test", Some(today), @@ -401,8 +401,8 @@ object TestData { None, None, Some( - model.api.DraftCopyright( - Some(commonApi.License("publicdomain", None, None)), + model.api.DraftCopyrightDTO( + Some(commonApi.LicenseDTO("publicdomain", None, None)), Some(""), Seq.empty, Seq.empty, @@ -479,14 +479,14 @@ object TestData { qualityEvaluation = None ) - val apiArticleWithHtmlFaultV2: api.Article = api.Article( + val apiArticleWithHtmlFaultV2: api.ArticleDTO = api.ArticleDTO( id = 1, oldNdlaUrl = None, revision = 1, - status = api.Status(PLANNED.toString, Seq.empty), - title = Some(api.ArticleTitle("test", "title", "en")), + status = api.StatusDTO(PLANNED.toString, Seq.empty), + title = Some(api.ArticleTitleDTO("test", "title", "en")), content = Some( - api.ArticleContent( + api.ArticleContentDTO( """
  • Det er ikke lov Ã¥ gjøre dette.

    Tekst utenfor.
  • Dette er helt ok
|
  • Det er ikke lov Ã¥ gjøre dette.

  • Dette er helt ok
|
  1. Det er ikke lov å gjøre dette.

  2. Dette er helt ok
@@ -496,8 +496,8 @@ object TestData { ) ), copyright = Some( - model.api.DraftCopyright( - Some(commonApi.License("publicdomain", None, None)), + model.api.DraftCopyrightDTO( + Some(commonApi.LicenseDTO("publicdomain", None, None)), Some(""), Seq.empty, Seq.empty, @@ -507,11 +507,11 @@ object TestData { false ) ), - tags = Some(api.ArticleTag(Seq.empty, "en")), + tags = Some(api.ArticleTagDTO(Seq.empty, "en")), requiredLibraries = Seq.empty, visualElement = None, introduction = None, - metaDescription = Some(api.ArticleMetaDescription("so meta", "en")), + metaDescription = Some(api.ArticleMetaDescriptionDTO("so meta", "en")), metaImage = None, created = NDLADate.now().minusDays(4), updated = NDLADate.now().minusDays(2), @@ -553,8 +553,8 @@ object TestData { latestEditedConcepts = None ) - val emptyApiUserData: api.UserData = - api.UserData( + val emptyApiUserData: api.UserDataDTO = + api.UserDataDTO( userId = "", savedSearches = None, latestEditedArticles = None, @@ -571,8 +571,8 @@ object TestData { val sampleLearningPath: LearningPath = LearningPath(1, Title("Title", "nb")) - val sampleApiGrepCodesSearchResult: GrepCodesSearchResult = api.GrepCodesSearchResult(10, 1, 1, Seq("a", "b")) - val sampleApiTagsSearchResult: TagsSearchResult = api.TagsSearchResult(10, 1, 1, "nb", Seq("a", "b")) + val sampleApiGrepCodesSearchResult: GrepCodesSearchResultDTO = api.GrepCodesSearchResultDTO(10, 1, 1, Seq("a", "b")) + val sampleApiTagsSearchResult: TagsSearchResultDTO = api.TagsSearchResultDTO(10, 1, 1, "nb", Seq("a", "b")) val searchSettings: domain.SearchSettings = domain.SearchSettings( query = None, diff --git a/draft-api/src/test/scala/no/ndla/draftapi/controller/DraftControllerTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/controller/DraftControllerTest.scala index bc35915a7d..ec39c5e2c9 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/controller/DraftControllerTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/controller/DraftControllerTest.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.api.{Delete, Missing, UpdateWith} import no.ndla.common.model.domain.draft.DraftStatus.EXTERNAL_REVIEW import no.ndla.common.model.{NDLADate, api as commonApi, domain as common} import no.ndla.draftapi.TestData.authHeaderWithWriteRole -import no.ndla.draftapi.model.api.ArticleSearchResult +import no.ndla.draftapi.model.api.ArticleSearchResultDTO import no.ndla.draftapi.model.domain.{SearchSettings, Sort} import no.ndla.draftapi.model.{api, domain} import no.ndla.draftapi.{TestData, TestEnvironment, UnitSuite} @@ -74,34 +74,34 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr val creativeCommonlicenses = getLicenses .filter(_.license.toString.startsWith("by")) - .map(l => commonApi.License(l.license.toString, Option(l.description), l.url)) + .map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)) .toSet val resp = simpleHttpClient.send( quickRequest.get(uri"http://localhost:$serverPort/draft-api/v1/drafts/licenses?filter=by") ) resp.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.License]](resp.body) + val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.LicenseDTO]](resp.body) convertedBody should equal(creativeCommonlicenses) } test("That GET /licenses/ with filter not specified returns all licenses") { - val allLicenses = getLicenses.map(l => commonApi.License(l.license.toString, Option(l.description), l.url)).toSet + val allLicenses = getLicenses.map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)).toSet val resp = simpleHttpClient.send( quickRequest.get(uri"http://localhost:$serverPort/draft-api/v1/drafts/licenses") ) resp.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.License]](resp.body) + val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.LicenseDTO]](resp.body) convertedBody should equal(allLicenses) } test("GET / should use size of id-list as page-size if defined") { - val searchMock = mock[domain.SearchResult[api.ArticleSummary]] + val searchMock = mock[domain.SearchResult[api.ArticleSummaryDTO]] when(searchMock.scrollId).thenReturn(None) when(articleSearchService.matchingQuery(any[SearchSettings])) .thenReturn(Success(searchMock)) when(searchConverterService.asApiSearchResult(any)).thenReturn( - ArticleSearchResult( + ArticleSearchResultDTO( totalCount = 0, page = Some(1), pageSize = 100, @@ -141,7 +141,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr when( writeService .newArticle( - any[api.NewArticle], + any[api.NewArticleDTO], any[List[String]], any[Seq[String]], any[TokenUser], @@ -214,7 +214,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr resp.code.code should be(200) when(readService.withId(articleId, lang)).thenReturn( - Success(TestData.apiArticleUserTest.copy(status = api.Status(EXTERNAL_REVIEW.toString, Seq.empty))) + Success(TestData.apiArticleUserTest.copy(status = api.StatusDTO(EXTERNAL_REVIEW.toString, Seq.empty))) ) val resp2 = simpleHttpClient.send( @@ -237,7 +237,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr } when(readService.withId(articleId, lang)).thenReturn( - Success(TestData.apiArticleUserTest.copy(status = api.Status(EXTERNAL_REVIEW.toString, Seq.empty))) + Success(TestData.apiArticleUserTest.copy(status = api.StatusDTO(EXTERNAL_REVIEW.toString, Seq.empty))) ) { @@ -264,7 +264,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr when( writeService.updateArticle( any[Long], - any[api.UpdatedArticle], + any[api.UpdatedArticleDTO], any[List[String]], any[Seq[String]], any[TokenUser], @@ -287,7 +287,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr when( writeService.updateArticle( any[Long], - any[api.UpdatedArticle], + any[api.UpdatedArticleDTO], any[List[String]], any[Seq[String]], any[TokenUser], @@ -307,7 +307,8 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr } test("PUT /:id/validate/ should return 204 if user has required permissions") { - when(contentValidator.validateArticleApiArticle(any[Long], any[Boolean], any)).thenReturn(Success(api.ContentId(1))) + when(contentValidator.validateArticleApiArticle(any[Long], any[Boolean], any)) + .thenReturn(Success(api.ContentIdDTO(1))) val resp = simpleHttpClient.send( quickRequest .put(uri"http://localhost:$serverPort/draft-api/v1/drafts/1/validate") @@ -319,12 +320,12 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr test("That scrollId is in header, and not in body") { val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.ArticleSummary]( + val searchResponse = domain.SearchResult[api.ArticleSummaryDTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummary], + Seq.empty[api.ArticleSummaryDTO], Some(scrollId) ) when(articleSearchService.matchingQuery(any[SearchSettings])).thenReturn(Success(searchResponse)) @@ -345,12 +346,12 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" when(searchConverterService.asApiSearchResult(any)).thenCallRealMethod() - val searchResponse = domain.SearchResult[api.ArticleSummary]( + val searchResponse = domain.SearchResult[api.ArticleSummaryDTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummary], + Seq.empty[api.ArticleSummaryDTO], Some(scrollId) ) @@ -372,12 +373,12 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr reset(articleSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[api.ArticleSummary]( + val searchResponse = domain.SearchResult[api.ArticleSummaryDTO]( 0, Some(1), 10, "nb", - Seq.empty[api.ArticleSummary], + Seq.empty[api.ArticleSummaryDTO], Some(scrollId) ) @@ -451,7 +452,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr writeService .updateArticle( eqTo(1.toLong), - any[api.UpdatedArticle], + any[api.UpdatedArticleDTO], any[List[String]], any[Seq[String]], any[TokenUser], @@ -471,7 +472,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr val existingArtId = """{"revision": 1, "language":"nb","metaImage": {"id": "1", | "alt": "alt-text"}}""".stripMargin val existingExpected = TestData.blankUpdatedArticle - .copy(language = Some("nb"), metaImage = UpdateWith(api.NewArticleMetaImage("1", "alt-text"))) + .copy(language = Some("nb"), metaImage = UpdateWith(api.NewArticleMetaImageDTO("1", "alt-text"))) { val resp = simpleHttpClient.send( @@ -544,7 +545,7 @@ class DraftControllerTest extends UnitSuite with TestEnvironment with TapirContr sort = Sort.ByTitleAsc ) - val result = domain.SearchResult[api.ArticleSummary]( + val result = domain.SearchResult[api.ArticleSummaryDTO]( totalCount = 0, page = None, pageSize = 10, diff --git a/draft-api/src/test/scala/no/ndla/draftapi/controller/FileControllerTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/controller/FileControllerTest.scala index cb9f97aa81..8ad9e58542 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/controller/FileControllerTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/controller/FileControllerTest.scala @@ -9,7 +9,7 @@ package no.ndla.draftapi.controller import no.ndla.common.CirceUtil import no.ndla.common.model.domain -import no.ndla.draftapi.model.api.UploadedFile +import no.ndla.draftapi.model.api.UploadedFileDTO import no.ndla.draftapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.tapirtesting.TapirControllerTest import org.mockito.ArgumentMatchers.any @@ -29,7 +29,7 @@ class FileControllerTest extends UnitSuite with TestEnvironment with TapirContro val exampleFileBody: Array[Byte] = "Hello".getBytes test("That uploading a file returns 200 with body if successful") { - val uploaded = UploadedFile("pwqofkpowegjw.pdf", "application/pdf", ".pdf", "files/resources/pwqofkpowegjw.pdf") + val uploaded = UploadedFileDTO("pwqofkpowegjw.pdf", "application/pdf", ".pdf", "files/resources/pwqofkpowegjw.pdf") when(writeService.storeFile(any[domain.UploadedFile])).thenReturn(Success(uploaded)) val resp = simpleHttpClient.send( @@ -40,7 +40,7 @@ class FileControllerTest extends UnitSuite with TestEnvironment with TapirContro ) resp.code.code should be(200) - CirceUtil.unsafeParseAs[UploadedFile](resp.body) should be(uploaded) + CirceUtil.unsafeParseAs[UploadedFileDTO](resp.body) should be(uploaded) } // test("That uploading a file fails with 400 if no file is specified") { diff --git a/draft-api/src/test/scala/no/ndla/draftapi/controller/InternControllerTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/controller/InternControllerTest.scala index 59b3306c8a..8b2db15a5f 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/controller/InternControllerTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/controller/InternControllerTest.scala @@ -8,7 +8,7 @@ package no.ndla.draftapi.controller import no.ndla.draftapi.* -import no.ndla.draftapi.model.api.ContentId +import no.ndla.draftapi.model.api.ContentIdDTO import no.ndla.draftapi.model.domain.ImportId import no.ndla.tapirtesting.TapirControllerTest import org.mockito.ArgumentMatchers.{any, eq as eqTo} @@ -32,7 +32,7 @@ class InternControllerTest extends UnitSuite with TestEnvironment with TapirCont failedApiCall, failedApiCall, failedApiCall, - Success(ContentId(10)) + Success(ContentIdDTO(10)) ) simpleHttpClient.send( diff --git a/draft-api/src/test/scala/no/ndla/draftapi/controller/UserDataControllerTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/controller/UserDataControllerTest.scala index c800197c7b..f3b38b8488 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/controller/UserDataControllerTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/controller/UserDataControllerTest.scala @@ -7,7 +7,7 @@ package no.ndla.draftapi.controller -import no.ndla.draftapi.model.api.UpdatedUserData +import no.ndla.draftapi.model.api.UpdatedUserDataDTO import no.ndla.draftapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.network.tapir.auth.TokenUser import no.ndla.tapirtesting.TapirControllerTest @@ -59,7 +59,7 @@ class UserDataControllerTest extends UnitSuite with TestEnvironment with TapirCo } test("PATCH / should return 200 if user has access roles and data has been updated correctly") { - when(writeService.updateUserData(any[UpdatedUserData], any[TokenUser])) + when(writeService.updateUserData(any[UpdatedUserDataDTO], any[TokenUser])) .thenReturn(Success(TestData.emptyApiUserData)) val res = simpleHttpClient.send( diff --git a/draft-api/src/test/scala/no/ndla/draftapi/repository/UserDataRepositoryTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/repository/UserDataRepositoryTest.scala index 79bab6ddac..3162ebd081 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/repository/UserDataRepositoryTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/repository/UserDataRepositoryTest.scala @@ -8,7 +8,7 @@ package no.ndla.draftapi.repository import com.zaxxer.hikari.HikariDataSource -import no.ndla.draftapi.model.api.SavedSearch +import no.ndla.draftapi.model.api.SavedSearchDTO import java.net.Socket import no.ndla.draftapi.{TestData, TestEnvironment} @@ -82,7 +82,7 @@ class UserDataRepositoryTest extends IntegrationSuite(EnablePostgresContainer = this.resetIdSequence() val data1 = - TestData.emptyDomainUserData.copy(userId = "first", savedSearches = Some(Seq(SavedSearch("eple", "eple")))) + TestData.emptyDomainUserData.copy(userId = "first", savedSearches = Some(Seq(SavedSearchDTO("eple", "eple")))) val data2 = TestData.emptyDomainUserData.copy(userId = "second", latestEditedArticles = Some(Seq("kake"))) val data3 = TestData.emptyDomainUserData.copy(userId = "third", favoriteSubjects = Some(Seq("bok"))) @@ -100,7 +100,7 @@ class UserDataRepositoryTest extends IntegrationSuite(EnablePostgresContainer = val initialUserData2 = TestData.emptyDomainUserData.copy( userId = "second", - savedSearches = Some(Seq(SavedSearch("Seiddit", "Seiddit"), SavedSearch("Emina", "Emina"))), + savedSearches = Some(Seq(SavedSearchDTO("Seiddit", "Seiddit"), SavedSearchDTO("Emina", "Emina"))), latestEditedArticles = Some(Seq("article:6", "article:9")), favoriteSubjects = Some(Seq("methematics", "PEBCAK-studies")) ) @@ -109,13 +109,13 @@ class UserDataRepositoryTest extends IntegrationSuite(EnablePostgresContainer = val inserted2 = repository.insert(initialUserData2) val updatedUserData1 = inserted1.get.copy( - savedSearches = Some(Seq(SavedSearch("1", "1"), SavedSearch("2", "2"))), + savedSearches = Some(Seq(SavedSearchDTO("1", "1"), SavedSearchDTO("2", "2"))), latestEditedArticles = Some(Seq("3", "4")), favoriteSubjects = Some(Seq("5", "6")) ) val updatedUserData2 = inserted2.get.copy( - savedSearches = Some(Seq(SavedSearch("a", "a"), SavedSearch("b", "b"))), + savedSearches = Some(Seq(SavedSearchDTO("a", "a"), SavedSearchDTO("b", "b"))), latestEditedArticles = None, favoriteSubjects = Some(Seq.empty) ) diff --git a/draft-api/src/test/scala/no/ndla/draftapi/service/ConverterServiceTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/service/ConverterServiceTest.scala index e1c474d41d..b3afe298ef 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/service/ConverterServiceTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/service/ConverterServiceTest.scala @@ -16,7 +16,7 @@ import no.ndla.common.model.domain.draft.DraftStatus.* import no.ndla.common.model.domain.draft.{Comment, Draft, DraftCopyright, DraftStatus} import no.ndla.common.model.{NDLADate, api as commonApi} import no.ndla.draftapi.model.api -import no.ndla.draftapi.model.api.{NewComment, UpdatedComment} +import no.ndla.draftapi.model.api.{NewCommentDTO, UpdatedCommentDTO} import no.ndla.draftapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.mapping.License.CC_BY import no.ndla.network.tapir.auth.TokenUser @@ -34,12 +34,12 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val service = new ConverterService test("toApiLicense defaults to unknown if the license was not found") { - service.toApiLicense("invalid") should equal(commonApi.License("unknown", None, None)) + service.toApiLicense("invalid") should equal(commonApi.LicenseDTO("unknown", None, None)) } test("toApiLicense converts a short license string to a license object with description and url") { service.toApiLicense(CC_BY.toString) should equal( - commonApi.License( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -50,14 +50,18 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("toApiArticleTitle returns both title and plainTitle") { val title = Title("Title with ukrainian word", "en") service.toApiArticleTitle(title) should equal( - api.ArticleTitle("Title with ukrainian word", "Title with ukrainian word", "en") + api.ArticleTitleDTO( + "Title with ukrainian word", + "Title with ukrainian word", + "en" + ) ) } test("toApiArticleIntroduction returns both introduction and plainIntroduction") { val introduction = Introduction("

Introduction with emphasis

", "en") service.toApiArticleIntroduction(introduction) should equal( - api.ArticleIntroduction("Introduction with emphasis", "

Introduction with emphasis

", "en") + api.ArticleIntroductionDTO("Introduction with emphasis", "

Introduction with emphasis

", "en") ) } @@ -422,7 +426,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { tags = Some(Seq("1", "2", "3")), introduction = Some("NyIntro"), metaDescription = Some("NyMeta"), - metaImage = UpdateWith(api.NewArticleMetaImage("321", "NyAlt")), + metaImage = UpdateWith(api.NewArticleMetaImageDTO("321", "NyAlt")), visualElement = Some("NyVisualElement"), copyright = None, requiredLibraries = None, @@ -528,7 +532,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { tags = Some(Seq("1", "2", "3")), introduction = Some("NyIntro"), metaDescription = Some("NyMeta"), - metaImage = UpdateWith(api.NewArticleMetaImage("321", "NyAlt")), + metaImage = UpdateWith(api.NewArticleMetaImageDTO("321", "NyAlt")), visualElement = Some("NyVisualElement"), copyright = None, requiredLibraries = None, @@ -756,7 +760,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val Success(res2) = service.toDomainArticle( beforeUpdate, TestData.sampleApiUpdateArticle - .copy(language = Some("nb"), metaImage = UpdateWith(api.NewArticleMetaImage("1", "Hola"))), + .copy(language = Some("nb"), metaImage = UpdateWith(api.NewArticleMetaImageDTO("1", "Hola"))), isImported = false, TestData.userWithWriteAccess, None, @@ -790,7 +794,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val Success(res2) = service.toDomainArticle( 2, - TestData.sampleApiUpdateArticle.copy(metaImage = UpdateWith(api.NewArticleMetaImage("1", "Hola"))), + TestData.sampleApiUpdateArticle.copy(metaImage = UpdateWith(api.NewArticleMetaImageDTO("1", "Hola"))), isImported = false, TestData.userWithWriteAccess, None, @@ -1162,8 +1166,8 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val updatedComments = List( - UpdatedComment(id = None, content = "hei", isOpen = Some(true), solved = Some(false)), - UpdatedComment(id = Some(uuid.toString), content = "yoo", isOpen = Some(false), solved = Some(false)) + UpdatedCommentDTO(id = None, content = "hei", isOpen = Some(true), solved = Some(false)), + UpdatedCommentDTO(id = Some(uuid.toString), content = "yoo", isOpen = Some(false), solved = Some(false)) ) val existingComments = Seq(Comment(id = uuid, created = now, updated = now, content = "nja", isOpen = true, solved = false)) @@ -1182,7 +1186,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { when(clock.now()).thenReturn(now) val updatedComments = List( - UpdatedComment(id = Some(uuid.toString), content = "updated keep", isOpen = Some(true), solved = Some(false)) + UpdatedCommentDTO(id = Some(uuid.toString), content = "updated keep", isOpen = Some(true), solved = Some(false)) ) val existingComments = Seq( Comment(id = uuid, created = now, updated = now, content = "keep", isOpen = true, solved = false), @@ -1200,7 +1204,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val now = NDLADate.now() when(clock.now()).thenReturn(now) - val newComments = List(NewComment(content = "hei", isOpen = None)) + val newComments = List(NewCommentDTO(content = "hei", isOpen = None)) val expectedComment = Comment(id = uuid, created = now, updated = now, content = "hei", isOpen = true, solved = false) service.newCommentToDomain(newComments).head.copy(id = uuid) should be(expectedComment) @@ -1214,8 +1218,8 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { val updatedComments = List( - UpdatedComment(id = None, content = "hei", isOpen = Some(true), solved = Some(false)), - UpdatedComment(id = Some(uuid.toString), content = "yoo", isOpen = None, solved = Some(false)) + UpdatedCommentDTO(id = None, content = "hei", isOpen = Some(true), solved = Some(false)), + UpdatedCommentDTO(id = Some(uuid.toString), content = "yoo", isOpen = None, solved = Some(false)) ) val expectedComments = Success( Seq( @@ -1228,7 +1232,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { test("that updatedCommentToDomainNullDocument fails if UUID is malformed") { val updatedComments = - List(UpdatedComment(id = Some("malformed-UUID"), content = "yoo", isOpen = Some(true), solved = Some(false))) + List(UpdatedCommentDTO(id = Some("malformed-UUID"), content = "yoo", isOpen = Some(true), solved = Some(false))) service.updatedCommentToDomainNullDocument(updatedComments).isFailure should be(true) } diff --git a/draft-api/src/test/scala/no/ndla/draftapi/service/WriteServiceTest.scala b/draft-api/src/test/scala/no/ndla/draftapi/service/WriteServiceTest.scala index f740d28b3f..1cf40c20c1 100644 --- a/draft-api/src/test/scala/no/ndla/draftapi/service/WriteServiceTest.scala +++ b/draft-api/src/test/scala/no/ndla/draftapi/service/WriteServiceTest.scala @@ -16,7 +16,7 @@ import no.ndla.common.model.domain.draft.* import no.ndla.common.model.{NDLADate, RelatedContentLink, domain, api as commonApi} import no.ndla.draftapi.integration.Node import no.ndla.draftapi.model.api -import no.ndla.draftapi.model.api.PartialArticleFields +import no.ndla.draftapi.model.api.PartialArticleFieldsDTO import no.ndla.draftapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.network.tapir.auth.Permission.DRAFT_API_WRITE import no.ndla.network.tapir.auth.TokenUser @@ -198,19 +198,19 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val updatedIntro = "introintro" val updatedMetaId = "1234" val updatedMetaAlt = "HeheAlt" - val newImageMeta = api.NewArticleMetaImage(updatedMetaId, updatedMetaAlt) + val newImageMeta = api.NewArticleMetaImageDTO(updatedMetaId, updatedMetaAlt) val updatedVisualElement = s"<$EmbedTagName something />" - val updatedCopyright = model.api.DraftCopyright( - Some(commonApi.License("a", Some("b"), None)), + val updatedCopyright = model.api.DraftCopyrightDTO( + Some(commonApi.LicenseDTO("a", Some("b"), None)), Some("c"), - Seq(commonApi.Author("Opphavsmann", "Jonas")), + Seq(commonApi.AuthorDTO("Opphavsmann", "Jonas")), List(), List(), None, None, false ) - val updatedRequiredLib = api.RequiredLibrary("tjup", "tjap", "tjim") + val updatedRequiredLib = api.RequiredLibraryDTO("tjup", "tjap", "tjim") val updatedArticleType = "topic-article" val updatedApiArticle = TestData.blankUpdatedArticle.copy( @@ -277,7 +277,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("IN_PROGRESS", Seq.empty)) + result.status should equal(api.StatusDTO("IN_PROGRESS", Seq.empty)) } test( @@ -300,7 +300,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("IN_PROGRESS", Seq("PUBLISHED"))) + result.status should equal(api.StatusDTO("IN_PROGRESS", Seq("PUBLISHED"))) } test("updateArticle should use current status if user-defined status is not set") { @@ -322,7 +322,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("IN_PROGRESS", Seq.empty)) + result.status should equal(api.StatusDTO("IN_PROGRESS", Seq.empty)) } { @@ -341,7 +341,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("EXTERNAL_REVIEW", Seq.empty)) + result.status should equal(api.StatusDTO("EXTERNAL_REVIEW", Seq.empty)) } { @@ -360,7 +360,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("INTERNAL_REVIEW", Seq.empty)) + result.status should equal(api.StatusDTO("INTERNAL_REVIEW", Seq.empty)) } { @@ -385,7 +385,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { None, None ) - result.status should equal(api.Status("END_CONTROL", Seq.empty)) + result.status should equal(api.StatusDTO("END_CONTROL", Seq.empty)) } } @@ -663,8 +663,8 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { availability = Some(Availability.teacher.toString), grepCodes = Some(Seq("a", "b", "c")), copyright = Some( - model.api.DraftCopyright( - license = Some(commonApi.License("COPYRIGHTED", None, None)), + model.api.DraftCopyrightDTO( + license = Some(commonApi.LicenseDTO("COPYRIGHTED", None, None)), origin = None, creators = Seq.empty, processors = Seq.empty, @@ -675,7 +675,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) ), metaDescription = Some("newMeta"), - relatedContent = Some(Seq(Left(commonApi.RelatedContentLink("title1", "url2")), Right(12L))), + relatedContent = Some(Seq(Left(commonApi.RelatedContentLinkDTO("title1", "url2")), Right(12L))), tags = Some(Seq("new", "tag")) ) @@ -712,7 +712,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { result1.grepCodes should be(Seq("a", "b", "c")) result1.copyright.get.license.get.license should be("COPYRIGHTED") result1.metaDescription.get.metaDescription should be("newMeta") - result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLink("title1", "url2"))) + result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLinkDTO("title1", "url2"))) result1.relatedContent.reverse.head should be(Right(12L)) result1.tags.get.tags should be(Seq("new", "tag")) result1.notes.head.note should be("Artikkelen har blitt delpublisert") @@ -725,8 +725,8 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { language = Some("nb"), title = Some(existingTitle), copyright = Some( - model.api.DraftCopyright( - license = Some(commonApi.License("COPYRIGHTED", None, None)), + model.api.DraftCopyrightDTO( + license = Some(commonApi.LicenseDTO("COPYRIGHTED", None, None)), origin = Some("shouldCauseStatusChange"), creators = Seq.empty, processors = Seq.empty, @@ -780,8 +780,8 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { availability = Some(Availability.teacher.toString), grepCodes = Some(Seq("a", "b", "c")), copyright = Some( - model.api.DraftCopyright( - license = Some(commonApi.License("COPYRIGHTED", None, None)), + model.api.DraftCopyrightDTO( + license = Some(commonApi.LicenseDTO("COPYRIGHTED", None, None)), origin = None, creators = Seq.empty, processors = Seq.empty, @@ -792,7 +792,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) ), metaDescription = Some("newMeta"), - relatedContent = Some(Seq(Left(commonApi.RelatedContentLink("title1", "url2")), Right(12L))), + relatedContent = Some(Seq(Left(commonApi.RelatedContentLinkDTO("title1", "url2")), Right(12L))), tags = Some(Seq("new", "tag")), conceptIds = Some(Seq(1, 2, 3)) ) @@ -833,7 +833,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { result1.grepCodes should be(Seq("a", "b", "c")) result1.copyright.get.license.get.license should be("COPYRIGHTED") result1.metaDescription.get.metaDescription should be("newMeta") - result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLink("title1", "url2"))) + result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLinkDTO("title1", "url2"))) result1.relatedContent.reverse.head should be(Right(12L)) result1.tags.get.tags should be(Seq("new", "tag")) result1.conceptIds should be(Seq(1, 2, 3)) @@ -993,23 +993,23 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) val articleFieldsToUpdate = Seq( - api.PartialArticleFields.availability, - api.PartialArticleFields.grepCodes, - api.PartialArticleFields.license, - api.PartialArticleFields.metaDescription, - api.PartialArticleFields.relatedContent, - api.PartialArticleFields.tags, - api.PartialArticleFields.revisionDate, - api.PartialArticleFields.published + api.PartialArticleFieldsDTO.availability, + api.PartialArticleFieldsDTO.grepCodes, + api.PartialArticleFieldsDTO.license, + api.PartialArticleFieldsDTO.metaDescription, + api.PartialArticleFieldsDTO.relatedContent, + api.PartialArticleFieldsDTO.tags, + api.PartialArticleFieldsDTO.revisionDate, + api.PartialArticleFieldsDTO.published ) val expectedPartialPublishFields = PartialPublishArticle( availability = Some(Availability.everyone), grepCodes = Some(Seq("A", "B")), license = Some("CC-BY-4.0"), - metaDescription = Some(Seq(api.ArticleMetaDescription("oldDesc", "nb"))), + metaDescription = Some(Seq(api.ArticleMetaDescriptionDTO("oldDesc", "nb"))), relatedContent = Some(Seq(Left(RelatedContentLink("title1", "url2")), Right(12L))), - tags = Some(Seq(api.ArticleTag(Seq("old", "tag"), "nb"))), + tags = Some(Seq(api.ArticleTagDTO(Seq("old", "tag"), "nb"))), revisionDate = UpdateWith(tomorrow), published = Some(tomorrow) ) @@ -1029,18 +1029,18 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { license = Some("CC-BY-4.0"), metaDescription = Some( Seq( - api.ArticleMetaDescription("oldDesc", "nb"), - api.ArticleMetaDescription("oldDescc", "es"), - api.ArticleMetaDescription("oldDesccc", "ru"), - api.ArticleMetaDescription("oldDescccc", "nn") + api.ArticleMetaDescriptionDTO("oldDesc", "nb"), + api.ArticleMetaDescriptionDTO("oldDescc", "es"), + api.ArticleMetaDescriptionDTO("oldDesccc", "ru"), + api.ArticleMetaDescriptionDTO("oldDescccc", "nn") ) ), relatedContent = Some(Seq(Left(RelatedContentLink("title1", "url2")), Right(12L))), tags = Some( Seq( - api.ArticleTag(Seq("old", "tag"), "nb"), - api.ArticleTag(Seq("guten", "tag"), "de"), - api.ArticleTag(Seq("oldd", "tagg"), "es") + api.ArticleTagDTO(Seq("old", "tag"), "nb"), + api.ArticleTagDTO(Seq("guten", "tag"), "de"), + api.ArticleTagDTO(Seq("oldd", "tagg"), "es") ) ), revisionDate = UpdateWith(tomorrow), @@ -1059,7 +1059,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { } test("That updateArticle updates relatedContent") { - val apiRelatedContent1 = commonApi.RelatedContentLink("url1", "title1") + val apiRelatedContent1 = commonApi.RelatedContentLinkDTO("url1", "title1") val domainRelatedContent1 = RelatedContentLink("url1", "title1") val relatedContent2 = 2L @@ -1088,7 +1088,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { test("That updateArticle should get editor notes if RevisionMeta is added or updated") { when(uuidUtil.randomUUID()).thenCallRealMethod() - val revision = api.RevisionMeta(None, NDLADate.now(), "Ny revision", RevisionStatus.NeedsRevision.entryName) + val revision = api.RevisionMetaDTO(None, NDLADate.now(), "Ny revision", RevisionStatus.NeedsRevision.entryName) val updatedApiArticle = TestData.blankUpdatedArticle.copy( revision = 1, revisionMeta = Some(Seq(revision)) @@ -1148,8 +1148,8 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { availability = Some(Availability.teacher.toString), grepCodes = Some(Seq("a", "b", "c")), copyright = Some( - model.api.DraftCopyright( - license = Some(commonApi.License("COPYRIGHTED", None, None)), + model.api.DraftCopyrightDTO( + license = Some(commonApi.LicenseDTO("COPYRIGHTED", None, None)), origin = None, creators = Seq.empty, processors = Seq.empty, @@ -1160,7 +1160,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { ) ), metaDescription = Some("newMeta"), - relatedContent = Some(Seq(Left(commonApi.RelatedContentLink("title1", "url2")), Right(12L))), + relatedContent = Some(Seq(Left(commonApi.RelatedContentLinkDTO("title1", "url2")), Right(12L))), tags = Some(Seq("new", "tag")) ) @@ -1197,7 +1197,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { result1.grepCodes should be(Seq("a", "b", "c")) result1.copyright.get.license.get.license should be("COPYRIGHTED") result1.metaDescription.get.metaDescription should be("newMeta") - result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLink("title1", "url2"))) + result1.relatedContent.head.leftSide should be(Left(commonApi.RelatedContentLinkDTO("title1", "url2"))) result1.relatedContent.reverse.head should be(Right(12L)) result1.tags.get.tags should be(Seq("new", "tag")) result1.notes.head.note should be("Artikkelen har blitt delpublisert") @@ -1343,8 +1343,8 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { service.shouldPartialPublish(Some(article1), article2) should be( Set( - PartialArticleFields.metaDescription, - PartialArticleFields.grepCodes + PartialArticleFieldsDTO.metaDescription, + PartialArticleFieldsDTO.grepCodes ) ) } diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FilmPageController.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FilmPageController.scala index ae36f3482f..258e316851 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FilmPageController.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FilmPageController.scala @@ -30,7 +30,7 @@ trait FilmPageController { endpoint.get .summary("Get data to display on the film front page") .in(query[Option[String]]("language")) - .out(jsonBody[FilmFrontPageData]) + .out(jsonBody[FilmFrontPageDataDTO]) .errorOut(errorOutputsFor(404)) .serverLogicPure { language => readService.filmFrontPage(language) match { @@ -41,8 +41,8 @@ trait FilmPageController { endpoint.post .summary("Update film front page") .errorOut(errorOutputsFor(400, 401, 403, 404, 422)) - .in(jsonBody[NewOrUpdatedFilmFrontPageData]) - .out(jsonBody[FilmFrontPageData]) + .in(jsonBody[NewOrUpdatedFilmFrontPageDataDTO]) + .out(jsonBody[FilmFrontPageDataDTO]) .requirePermission(FRONTPAGE_API_WRITE) .serverLogicPure { _ => filmFrontPage => writeService.updateFilmFrontPage(filmFrontPage).partialOverride { case ex: ValidationException => diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FrontPageController.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FrontPageController.scala index afe53a78b1..dc8b9daa37 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FrontPageController.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/FrontPageController.scala @@ -8,7 +8,7 @@ package no.ndla.frontpageapi.controller import io.circe.generic.auto.* -import no.ndla.common.model.api.FrontPage +import no.ndla.common.model.api.FrontPageDTO import no.ndla.frontpageapi.model.api.* import no.ndla.frontpageapi.service.{ReadService, WriteService} import no.ndla.network.tapir.NoNullJsonPrinter.* @@ -29,7 +29,7 @@ trait FrontPageController { def getFrontPage: ServerEndpoint[Any, Eff] = endpoint.get .summary("Get data to display on the front page") - .out(jsonBody[FrontPage]) + .out(jsonBody[FrontPageDTO]) .errorOut(errorOutputsFor(404)) .serverLogicPure { _ => readService.getFrontPage @@ -37,9 +37,9 @@ trait FrontPageController { def newFrontPage: ServerEndpoint[Any, Eff] = endpoint.post .summary("Create front page") - .in(jsonBody[FrontPage]) + .in(jsonBody[FrontPageDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[FrontPage]) + .out(jsonBody[FrontPageDTO]) .requirePermission(FRONTPAGE_API_ADMIN) .serverLogicPure { _ => frontPage => writeService diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/InternController.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/InternController.scala index 356d5ee545..1770ca9118 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/InternController.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/InternController.scala @@ -33,7 +33,7 @@ trait InternController { endpoint.get .in("subjectpage" / "external" / path[String]("externalId").description("old NDLA node id")) .summary("Get subject page id from external id") - .out(jsonBody[SubjectPageId]) + .out(jsonBody[SubjectPageIdDTO]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { nid => readService.getIdFromExternalId(nid) match { @@ -45,9 +45,9 @@ trait InternController { endpoint.post .summary("Create new subject page") .in("subjectpage") - .in(jsonBody[NewSubjectFrontPageData]) + .in(jsonBody[NewSubjectFrontPageDataDTO]) .errorOut(errorOutputsFor()) - .out(jsonBody[SubjectPageData]) + .out(jsonBody[SubjectPageDataDTO]) .serverLogicPure { subjectPage => writeService .newSubjectPage(subjectPage) @@ -55,10 +55,10 @@ trait InternController { }, endpoint.put .in("subjectpage" / path[Long]("subject-id").description("The subject id")) - .in(jsonBody[NewSubjectFrontPageData]) + .in(jsonBody[NewSubjectFrontPageDataDTO]) .errorOut(errorOutputsFor(400, 404)) .summary("Update subject page") - .out(jsonBody[SubjectPageData]) + .out(jsonBody[SubjectPageDataDTO]) .serverLogicPure { case (id, subjectPage) => writeService .updateSubjectPage(id, subjectPage, props.DefaultLanguage) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/SubjectPageController.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/SubjectPageController.scala index 5570252964..e4e8a0b4bf 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/SubjectPageController.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/controller/SubjectPageController.scala @@ -12,9 +12,9 @@ import no.ndla.common.model.api.CommaSeparatedList.* import no.ndla.frontpageapi.Props import no.ndla.frontpageapi.model.api.{ ErrorHandling, - NewSubjectFrontPageData, - SubjectPageData, - UpdatedSubjectFrontPageData + NewSubjectFrontPageDataDTO, + SubjectPageDataDTO, + UpdatedSubjectFrontPageDataDTO } import no.ndla.frontpageapi.model.domain.Errors.ValidationException import no.ndla.frontpageapi.service.{ReadService, WriteService} @@ -41,7 +41,7 @@ trait SubjectPageController { .in(query[String]("language").default(props.DefaultLanguage)) .in(query[Boolean]("fallback").default(false)) .errorOut(errorOutputsFor(400, 404)) - .out(jsonBody[List[SubjectPageData]]) + .out(jsonBody[List[SubjectPageDataDTO]]) .serverLogicPure { case (page, pageSize, language, fallback) => readService.subjectPages(page, pageSize, language, fallback) } @@ -51,7 +51,7 @@ trait SubjectPageController { .in(path[Long]("subjectpage-id").description("The subjectpage id")) .in(query[String]("language").default(props.DefaultLanguage)) .in(query[Boolean]("fallback").default(false)) - .out(jsonBody[SubjectPageData]) + .out(jsonBody[SubjectPageDataDTO]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { case (id, language, fallback) => readService.subjectPage(id, language, fallback) @@ -65,7 +65,7 @@ trait SubjectPageController { .in(query[Boolean]("fallback").default(false)) .in(query[Int]("page-size").default(props.DefaultPageSize)) .in(query[Int]("page").default(1)) - .out(jsonBody[List[SubjectPageData]]) + .out(jsonBody[List[SubjectPageDataDTO]]) .errorOut(errorOutputsFor(400, 404)) .serverLogicPure { case (ids, language, fallback, pageSize, page) => val parsedPageSize = if (pageSize < 1) props.DefaultPageSize else pageSize @@ -76,8 +76,8 @@ trait SubjectPageController { def createNewSubjectPage: ServerEndpoint[Any, Eff] = endpoint.post .summary("Create new subject page") - .in(jsonBody[NewSubjectFrontPageData]) - .out(jsonBody[SubjectPageData]) + .in(jsonBody[NewSubjectFrontPageDataDTO]) + .out(jsonBody[SubjectPageDataDTO]) .errorOut(errorOutputsFor(400, 404)) .requirePermission(FRONTPAGE_API_WRITE) .serverLogicPure { _ => newSubjectFrontPageData => @@ -91,11 +91,11 @@ trait SubjectPageController { } def updateSubjectPage: ServerEndpoint[Any, Eff] = endpoint.patch .summary("Update subject page") - .in(jsonBody[UpdatedSubjectFrontPageData]) + .in(jsonBody[UpdatedSubjectFrontPageDataDTO]) .in(path[Long]("subjectpage-id").description("The subjectpage id")) .in(query[String]("language").default(props.DefaultLanguage)) .in(query[Boolean]("fallback").default(false)) - .out(jsonBody[SubjectPageData]) + .out(jsonBody[SubjectPageDataDTO]) .errorOut(errorOutputsFor(400, 404)) .requirePermission(FRONTPAGE_API_WRITE) .serverLogicPure { _ => diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubject.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubject.scala deleted file mode 100644 index c6804712eb..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubject.scala +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -case class AboutFilmSubject(title: String, description: String, visualElement: VisualElement, language: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubjectDTO.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubjectDTO.scala new file mode 100644 index 0000000000..217390e3bf --- /dev/null +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutFilmSubjectDTO.scala @@ -0,0 +1,15 @@ +/* + * Part of NDLA frontpage-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.frontpageapi.model.api + +case class AboutFilmSubjectDTO( + title: String, + description: String, + visualElement: VisualElementDTO, + language: String +) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescription.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubjectDTO.scala similarity index 52% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescription.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubjectDTO.scala index 3ae1e0ad15..3f167bfaaa 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescription.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubjectDTO.scala @@ -7,4 +7,8 @@ package no.ndla.frontpageapi.model.api -case class NewOrUpdatedMetaDescription(metaDescription: String, language: String) +case class AboutSubjectDTO( + title: String, + description: String, + visualElement: VisualElementDTO +) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImage.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImage.scala deleted file mode 100644 index d64ad991f5..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImage.scala +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -case class BannerImage(mobileUrl: Option[String], mobileId: Option[Long], desktopUrl: String, desktopId: Long) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImageDTO.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImageDTO.scala new file mode 100644 index 0000000000..5255087cc8 --- /dev/null +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/BannerImageDTO.scala @@ -0,0 +1,15 @@ +/* + * Part of NDLA frontpage-api + * Copyright (C) 2018 NDLA + * + * See LICENSE + */ + +package no.ndla.frontpageapi.model.api + +case class BannerImageDTO( + mobileUrl: Option[String], + mobileId: Option[Long], + desktopUrl: String, + desktopId: Long +) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageData.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageDataDTO.scala similarity index 65% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageData.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageDataDTO.scala index b02de0e86d..d8412ac5a2 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageData.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/FilmFrontPageDataDTO.scala @@ -7,10 +7,10 @@ package no.ndla.frontpageapi.model.api -case class FilmFrontPageData( +case class FilmFrontPageDataDTO( name: String, - about: Seq[AboutFilmSubject], - movieThemes: Seq[MovieTheme], + about: Seq[AboutFilmSubjectDTO], + movieThemes: Seq[MovieThemeDTO], slideShow: Seq[String], article: Option[String] ) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescription.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescriptionDTO.scala similarity index 67% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescription.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescriptionDTO.scala index dcf5bdff2f..30a85bef47 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescription.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MetaDescriptionDTO.scala @@ -7,4 +7,4 @@ package no.ndla.frontpageapi.model.api -case class MetaDescription(metaDescription: String) +case class MetaDescriptionDTO(metaDescription: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieTheme.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieTheme.scala deleted file mode 100644 index bc3e1961fe..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieTheme.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -case class MovieTheme(name: Seq[MovieThemeName], movies: Seq[String]) - -case class MovieThemeName(name: String, language: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieThemeDTO.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieThemeDTO.scala new file mode 100644 index 0000000000..c56733993b --- /dev/null +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/MovieThemeDTO.scala @@ -0,0 +1,12 @@ +/* + * Part of NDLA frontpage-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.frontpageapi.model.api + +case class MovieThemeDTO(name: Seq[MovieThemeNameDTO], movies: Seq[String]) + +case class MovieThemeNameDTO(name: String, language: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElement.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImageDTO.scala similarity index 58% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElement.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImageDTO.scala index 8830636960..73ae21ebec 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElement.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImageDTO.scala @@ -7,4 +7,4 @@ package no.ndla.frontpageapi.model.api -case class NewOrUpdatedVisualElement(`type`: String, id: String, alt: Option[String]) +case class NewOrUpdateBannerImageDTO(mobileImageId: Option[Long], desktopImageId: Long) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubject.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubjectDTO.scala similarity index 68% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubject.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubjectDTO.scala index fe6294396e..602d5f7782 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubject.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedAboutSubjectDTO.scala @@ -7,9 +7,9 @@ package no.ndla.frontpageapi.model.api -case class NewOrUpdatedAboutSubject( +case class NewOrUpdatedAboutSubjectDTO( title: String, description: String, language: String, - visualElement: NewOrUpdatedVisualElement + visualElement: NewOrUpdatedVisualElementDTO ) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageData.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageDataDTO.scala similarity index 58% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageData.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageDataDTO.scala index c38cf5bc2b..3bb4da007d 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageData.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedFilmFrontPageDataDTO.scala @@ -7,10 +7,10 @@ package no.ndla.frontpageapi.model.api -case class NewOrUpdatedFilmFrontPageData( +case class NewOrUpdatedFilmFrontPageDataDTO( name: String, - about: Seq[NewOrUpdatedAboutSubject], - movieThemes: Seq[NewOrUpdatedMovieTheme], + about: Seq[NewOrUpdatedAboutSubjectDTO], + movieThemes: Seq[NewOrUpdatedMovieThemeDTO], slideShow: Seq[String], article: Option[String] ) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubject.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescriptionDTO.scala similarity index 56% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubject.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescriptionDTO.scala index 98c7b95ce2..e5b0b21bed 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/AboutSubject.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMetaDescriptionDTO.scala @@ -7,4 +7,7 @@ package no.ndla.frontpageapi.model.api -case class AboutSubject(title: String, description: String, visualElement: VisualElement) +case class NewOrUpdatedMetaDescriptionDTO( + metaDescription: String, + language: String +) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieTheme.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieTheme.scala deleted file mode 100644 index ff520f95c9..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieTheme.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2019 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -case class NewOrUpdatedMovieTheme(name: Seq[NewOrUpdatedMovieName], movies: Seq[String]) - -case class NewOrUpdatedMovieName(name: String, language: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieThemeDTO.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieThemeDTO.scala new file mode 100644 index 0000000000..68366bd04d --- /dev/null +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedMovieThemeDTO.scala @@ -0,0 +1,12 @@ +/* + * Part of NDLA frontpage-api + * Copyright (C) 2019 NDLA + * + * See LICENSE + */ + +package no.ndla.frontpageapi.model.api + +case class NewOrUpdatedMovieThemeDTO(name: Seq[NewOrUpdatedMovieNameDTO], movies: Seq[String]) + +case class NewOrUpdatedMovieNameDTO(name: String, language: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImage.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElementDTO.scala similarity index 58% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImage.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElementDTO.scala index 830c13cfa2..23b8cdc388 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdateBannerImage.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewOrUpdatedVisualElementDTO.scala @@ -7,4 +7,4 @@ package no.ndla.frontpageapi.model.api -case class NewOrUpdateBannerImage(mobileImageId: Option[Long], desktopImageId: Long) +case class NewOrUpdatedVisualElementDTO(`type`: String, id: String, alt: Option[String]) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageData.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageDataDTO.scala similarity index 64% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageData.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageDataDTO.scala index 373884c26b..3aff4b5835 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageData.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/NewSubjectFrontPageDataDTO.scala @@ -7,12 +7,12 @@ package no.ndla.frontpageapi.model.api -case class NewSubjectFrontPageData( +case class NewSubjectFrontPageDataDTO( name: String, externalId: Option[String], - banner: NewOrUpdateBannerImage, - about: Seq[NewOrUpdatedAboutSubject], - metaDescription: Seq[NewOrUpdatedMetaDescription], + banner: NewOrUpdateBannerImageDTO, + about: Seq[NewOrUpdatedAboutSubjectDTO], + metaDescription: Seq[NewOrUpdatedMetaDescriptionDTO], editorsChoices: Option[List[String]], connectedTo: Option[List[String]], buildsOn: Option[List[String]], diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/Subject.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/Subject.scala deleted file mode 100644 index 9858e5dd12..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/Subject.scala +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -case class Subject(name: String, url: String) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectCollection.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectCollection.scala deleted file mode 100644 index 3e13ad82e4..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectCollection.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -import io.circe._, io.circe.generic.semiauto._ - -case class SubjectCollection(name: String, subjects: List[SubjectFilters]) -case class SubjectFilters(id: String, filters: List[String]) - -object SubjectCollection { - implicit val encoder: Encoder[SubjectCollection] = deriveEncoder - implicit val decoder: Decoder[SubjectCollection] = deriveDecoder -} - -object SubjectFilters { - implicit val encoder: Encoder[SubjectFilters] = deriveEncoder - implicit val decoder: Decoder[SubjectFilters] = deriveDecoder -} diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageData.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageDataDTO.scala similarity index 59% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageData.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageDataDTO.scala index 601eb21f4d..da93864be1 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageData.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageDataDTO.scala @@ -11,11 +11,11 @@ import io.circe.generic.semiauto._ import io.circe.generic.auto._ import io.circe._ -case class SubjectPageData( +case class SubjectPageDataDTO( id: Long, name: String, - banner: BannerImage, - about: Option[AboutSubject], + banner: BannerImageDTO, + about: Option[AboutSubjectDTO], metaDescription: Option[String], editorsChoices: List[String], supportedLanguages: Seq[String], @@ -24,8 +24,8 @@ case class SubjectPageData( leadsTo: List[String] ) -object SubjectPageData { - implicit def encoder: Encoder[SubjectPageData] = deriveEncoder[SubjectPageData] +object SubjectPageDataDTO { + implicit def encoder: Encoder[SubjectPageDataDTO] = deriveEncoder[SubjectPageDataDTO] - implicit def decoder: Decoder[SubjectPageData] = deriveDecoder[SubjectPageData] + implicit def decoder: Decoder[SubjectPageDataDTO] = deriveDecoder[SubjectPageDataDTO] } diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageId.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageId.scala deleted file mode 100644 index d232b603ea..0000000000 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageId.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Part of NDLA frontpage-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.frontpageapi.model.api - -import io.circe.generic.semiauto._ -import io.circe.{Decoder, Encoder} - -case class SubjectPageId(id: Long) - -object SubjectPageId { - implicit def encoder: Encoder.AsObject[SubjectPageId] = deriveEncoder[SubjectPageId] - - implicit def decoder: Decoder[SubjectPageId] = deriveDecoder[SubjectPageId] -} diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageIdDTO.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageIdDTO.scala new file mode 100644 index 0000000000..34209c8912 --- /dev/null +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/SubjectPageIdDTO.scala @@ -0,0 +1,19 @@ +/* + * Part of NDLA frontpage-api + * Copyright (C) 2018 NDLA + * + * See LICENSE + */ + +package no.ndla.frontpageapi.model.api + +import io.circe.generic.semiauto._ +import io.circe.{Decoder, Encoder} + +case class SubjectPageIdDTO(id: Long) + +object SubjectPageIdDTO { + implicit def encoder: Encoder.AsObject[SubjectPageIdDTO] = deriveEncoder[SubjectPageIdDTO] + + implicit def decoder: Decoder[SubjectPageIdDTO] = deriveDecoder[SubjectPageIdDTO] +} diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageData.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageDataDTO.scala similarity index 61% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageData.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageDataDTO.scala index 77cf08d929..2e666959cf 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageData.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/UpdatedSubjectFrontPageDataDTO.scala @@ -7,12 +7,12 @@ package no.ndla.frontpageapi.model.api -case class UpdatedSubjectFrontPageData( +case class UpdatedSubjectFrontPageDataDTO( name: Option[String], externalId: Option[String], - banner: Option[NewOrUpdateBannerImage], - about: Option[Seq[NewOrUpdatedAboutSubject]], - metaDescription: Option[Seq[NewOrUpdatedMetaDescription]], + banner: Option[NewOrUpdateBannerImageDTO], + about: Option[Seq[NewOrUpdatedAboutSubjectDTO]], + metaDescription: Option[Seq[NewOrUpdatedMetaDescriptionDTO]], editorsChoices: Option[List[String]], connectedTo: Option[List[String]], buildsOn: Option[List[String]], diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElement.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElementDTO.scala similarity index 61% rename from frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElement.scala rename to frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElementDTO.scala index 0598fb59ba..f28fb61288 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElement.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/model/api/VisualElementDTO.scala @@ -7,4 +7,4 @@ package no.ndla.frontpageapi.model.api -case class VisualElement(`type`: String, url: String, alt: Option[String]) +case class VisualElementDTO(`type`: String, url: String, alt: Option[String]) diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ConverterService.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ConverterService.scala index a4f8bd8f4f..4c3bdead83 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ConverterService.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ConverterService.scala @@ -23,22 +23,22 @@ trait ConverterService { object ConverterService { import props.{BrightcoveAccountId, BrightcovePlayer, RawImageApiUrl} - private def toApiMenu(menu: domain.Menu): model.api.Menu = - model.api.Menu(menu.articleId, menu.menu.map(toApiMenu), Some(menu.hideLevel)) + private def toApiMenu(menu: domain.Menu): model.api.MenuDTO = + model.api.MenuDTO(menu.articleId, menu.menu.map(toApiMenu), Some(menu.hideLevel)) - def toApiFrontPage(frontPage: domain.FrontPage): model.api.FrontPage = - model.api.FrontPage(articleId = frontPage.articleId, menu = frontPage.menu.map(toApiMenu)) + def toApiFrontPage(frontPage: domain.FrontPage): model.api.FrontPageDTO = + model.api.FrontPageDTO(articleId = frontPage.articleId, menu = frontPage.menu.map(toApiMenu)) - private def toApiBannerImage(banner: domain.BannerImage): api.BannerImage = - api.BannerImage( + private def toApiBannerImage(banner: domain.BannerImage): api.BannerImageDTO = + api.BannerImageDTO( banner.mobileImageId.map(createImageUrl), banner.mobileImageId, createImageUrl(banner.desktopImageId), banner.desktopImageId ) - def toApiFilmFrontPage(page: domain.FilmFrontPageData, language: Option[String]): api.FilmFrontPageData = { - api.FilmFrontPageData( + def toApiFilmFrontPage(page: domain.FilmFrontPageData, language: Option[String]): api.FilmFrontPageDataDTO = { + api.FilmFrontPageDataDTO( page.name, toApiAboutFilmSubject(page.about, language), toApiMovieThemes(page.movieThemes, language), @@ -50,40 +50,43 @@ trait ConverterService { private def toApiAboutFilmSubject( aboutSeq: Seq[domain.AboutSubject], language: Option[String] - ): Seq[api.AboutFilmSubject] = { + ): Seq[api.AboutFilmSubjectDTO] = { val filteredAboutSeq = language match { case Some(lang) => aboutSeq.filter(about => about.language == lang) case None => aboutSeq } filteredAboutSeq.map(about => - api.AboutFilmSubject(about.title, about.description, toApiVisualElement(about.visualElement), about.language) + api.AboutFilmSubjectDTO(about.title, about.description, toApiVisualElement(about.visualElement), about.language) ) } - private def toApiMovieThemes(themes: Seq[domain.MovieTheme], language: Option[String]): Seq[api.MovieTheme] = { - themes.map(theme => api.MovieTheme(toApiMovieName(theme.name, language), theme.movies)) + private def toApiMovieThemes(themes: Seq[domain.MovieTheme], language: Option[String]): Seq[api.MovieThemeDTO] = { + themes.map(theme => api.MovieThemeDTO(toApiMovieName(theme.name, language), theme.movies)) } - private def toApiMovieName(names: Seq[domain.MovieThemeName], language: Option[String]): Seq[api.MovieThemeName] = { + private def toApiMovieName( + names: Seq[domain.MovieThemeName], + language: Option[String] + ): Seq[api.MovieThemeNameDTO] = { val filteredNames = language match { case Some(lang) => names.filter(name => name.language == lang) case None => names } - filteredNames.map(name => api.MovieThemeName(name.name, name.language)) + filteredNames.map(name => api.MovieThemeNameDTO(name.name, name.language)) } def toApiSubjectPage( sub: domain.SubjectFrontPageData, language: String, fallback: Boolean = false - ): Try[api.SubjectPageData] = { + ): Try[api.SubjectPageDataDTO] = { if (sub.supportedLanguages.contains(language) || fallback) { sub.id match { case None => Failure(MissingIdException()) case Some(subjectPageId) => Success( - api.SubjectPageData( + api.SubjectPageDataDTO( subjectPageId, sub.name, toApiBannerImage(sub.bannerImage), @@ -107,9 +110,9 @@ trait ConverterService { } } - private def toApiAboutSubject(about: Option[domain.AboutSubject]): Option[api.AboutSubject] = { + private def toApiAboutSubject(about: Option[domain.AboutSubject]): Option[api.AboutSubjectDTO] = { about - .map(about => api.AboutSubject(about.title, about.description, toApiVisualElement(about.visualElement))) + .map(about => api.AboutSubjectDTO(about.title, about.description, toApiVisualElement(about.visualElement))) } private def toApiMetaDescription(meta: Option[domain.MetaDescription]): Option[String] = { @@ -117,22 +120,22 @@ trait ConverterService { .map(_.metaDescription) } - private def toApiVisualElement(visual: domain.VisualElement): api.VisualElement = { + private def toApiVisualElement(visual: domain.VisualElement): api.VisualElementDTO = { val url = visual.`type` match { case VisualElementType.Image => createImageUrl(visual.id.toLong) case VisualElementType.Brightcove => s"https://players.brightcove.net/$BrightcoveAccountId/${BrightcovePlayer}_default/index.html?videoId=${visual.id}" } - api.VisualElement(visual.`type`.entryName, url, visual.alt) + api.VisualElementDTO(visual.`type`.entryName, url, visual.alt) } - def toDomainSubjectPage(id: Long, subject: api.NewSubjectFrontPageData): Try[domain.SubjectFrontPageData] = + def toDomainSubjectPage(id: Long, subject: api.NewSubjectFrontPageDataDTO): Try[domain.SubjectFrontPageData] = toDomainSubjectPage(subject).map(_.copy(id = Some(id))) - private def toDomainBannerImage(banner: api.NewOrUpdateBannerImage): domain.BannerImage = + private def toDomainBannerImage(banner: api.NewOrUpdateBannerImageDTO): domain.BannerImage = domain.BannerImage(banner.mobileImageId, banner.desktopImageId) - def toDomainSubjectPage(subject: api.NewSubjectFrontPageData): Try[domain.SubjectFrontPageData] = { + def toDomainSubjectPage(subject: api.NewSubjectFrontPageDataDTO): Try[domain.SubjectFrontPageData] = { for { about <- toDomainAboutSubject(subject.about) newSubject = domain.SubjectFrontPageData( @@ -152,7 +155,7 @@ trait ConverterService { def toDomainSubjectPage( toMergeInto: domain.SubjectFrontPageData, - subject: api.UpdatedSubjectFrontPageData + subject: api.UpdatedSubjectFrontPageDataDTO ): Try[domain.SubjectFrontPageData] = { for { aboutSubject <- subject.about.traverse(toDomainAboutSubject) @@ -171,34 +174,36 @@ trait ConverterService { } yield merged } - private def toDomainAboutSubject(aboutSeq: Seq[api.NewOrUpdatedAboutSubject]): Try[Seq[domain.AboutSubject]] = { + private def toDomainAboutSubject(aboutSeq: Seq[api.NewOrUpdatedAboutSubjectDTO]): Try[Seq[domain.AboutSubject]] = { aboutSeq.traverse(about => toDomainVisualElement(about.visualElement) .map(domain.AboutSubject(about.title, about.description, about.language, _)) ) } - private def toDomainMetaDescription(metaSeq: Seq[api.NewOrUpdatedMetaDescription]): Seq[domain.MetaDescription] = { + private def toDomainMetaDescription( + metaSeq: Seq[api.NewOrUpdatedMetaDescriptionDTO] + ): Seq[domain.MetaDescription] = { metaSeq.map(meta => domain.MetaDescription(meta.metaDescription, meta.language)) } - private def toDomainVisualElement(visual: api.NewOrUpdatedVisualElement): Try[domain.VisualElement] = + private def toDomainVisualElement(visual: api.NewOrUpdatedVisualElementDTO): Try[domain.VisualElement] = for { t <- VisualElementType.fromString(visual.`type`) ve = domain.VisualElement(t, visual.id, visual.alt) validated <- VisualElementType.validateVisualElement(ve) } yield validated - private def toDomainMenu(menu: model.api.Menu): domain.Menu = { - val apiMenu = menu.menu.map { case x: model.api.Menu => toDomainMenu(x) } + private def toDomainMenu(menu: model.api.MenuDTO): domain.Menu = { + val apiMenu = menu.menu.map { case x: model.api.MenuDTO => toDomainMenu(x) } domain.Menu(articleId = menu.articleId, menu = apiMenu, hideLevel = menu.hideLevel.getOrElse(false)) } - def toDomainFrontPage(page: model.api.FrontPage): domain.FrontPage = { + def toDomainFrontPage(page: model.api.FrontPageDTO): domain.FrontPage = { domain.FrontPage(articleId = page.articleId, menu = page.menu.map(toDomainMenu)) } - def toDomainFilmFrontPage(page: api.NewOrUpdatedFilmFrontPageData): Try[domain.FilmFrontPageData] = { + def toDomainFilmFrontPage(page: api.NewOrUpdatedFilmFrontPageDataDTO): Try[domain.FilmFrontPageData] = { val withoutAboutSubject = domain.FilmFrontPageData(page.name, Seq(), toDomainMovieThemes(page.movieThemes), page.slideShow, page.article) @@ -208,11 +213,11 @@ trait ConverterService { } } - private def toDomainMovieThemes(themes: Seq[api.NewOrUpdatedMovieTheme]): Seq[domain.MovieTheme] = { + private def toDomainMovieThemes(themes: Seq[api.NewOrUpdatedMovieThemeDTO]): Seq[domain.MovieTheme] = { themes.map(theme => domain.MovieTheme(toDomainMovieNames(theme.name), theme.movies)) } - private def toDomainMovieNames(names: Seq[api.NewOrUpdatedMovieName]): Seq[domain.MovieThemeName] = { + private def toDomainMovieNames(names: Seq[api.NewOrUpdatedMovieNameDTO]): Seq[domain.MovieThemeName] = { names.map(name => domain.MovieThemeName(name.name, name.language)) } diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ReadService.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ReadService.scala index acd7d89bcc..dfa9e19ad5 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ReadService.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/ReadService.scala @@ -10,9 +10,9 @@ package no.ndla.frontpageapi.service import cats.implicits.* import no.ndla.common.errors as common import no.ndla.common.implicits.* -import no.ndla.common.model.api.FrontPage +import no.ndla.common.model.api.FrontPageDTO import no.ndla.frontpageapi.model.api -import no.ndla.frontpageapi.model.api.SubjectPageId +import no.ndla.frontpageapi.model.api.SubjectPageIdDTO import no.ndla.frontpageapi.model.domain.Errors.{LanguageNotFoundException, SubjectPageNotFoundException} import no.ndla.frontpageapi.repository.{FilmFrontPageRepository, FrontPageRepository, SubjectPageRepository} @@ -29,20 +29,25 @@ trait ReadService { else Success(subjectIds) } - def getIdFromExternalId(nid: String): Try[Option[SubjectPageId]] = + def getIdFromExternalId(nid: String): Try[Option[SubjectPageIdDTO]] = subjectPageRepository.getIdFromExternalId(nid) match { - case Success(Some(id)) => Success(Some(SubjectPageId(id))) + case Success(Some(id)) => Success(Some(SubjectPageIdDTO(id))) case Success(None) => Success(None) case Failure(ex) => Failure(ex) } - def subjectPage(id: Long, language: String, fallback: Boolean): Try[api.SubjectPageData] = { + def subjectPage(id: Long, language: String, fallback: Boolean): Try[api.SubjectPageDataDTO] = { val maybeSubject = subjectPageRepository.withId(id).? val converted = maybeSubject.traverse(ConverterService.toApiSubjectPage(_, language, fallback)).? converted.toTry(SubjectPageNotFoundException(id)) } - def subjectPages(page: Int, pageSize: Int, language: String, fallback: Boolean): Try[List[api.SubjectPageData]] = { + def subjectPages( + page: Int, + pageSize: Int, + language: String, + fallback: Boolean + ): Try[List[api.SubjectPageDataDTO]] = { val offset = pageSize * (page - 1) val data = subjectPageRepository.all(offset, pageSize).? val converted = data.map(ConverterService.toApiSubjectPage(_, language, fallback)) @@ -64,7 +69,7 @@ trait ReadService { fallback: Boolean, pageSize: Int, page: Int - ): Try[List[api.SubjectPageData]] = { + ): Try[List[api.SubjectPageDataDTO]] = { val offset = (page - 1) * pageSize for { ids <- validateSubjectPageIdsOrError(subjectIds) @@ -73,14 +78,14 @@ trait ReadService { } yield api } - def getFrontPage: Try[FrontPage] = { + def getFrontPage: Try[FrontPageDTO] = { frontPageRepository.getFrontPage.flatMap { case None => Failure(common.NotFoundException("Front page was not found")) case Some(value) => Success(ConverterService.toApiFrontPage(value)) } } - def filmFrontPage(language: Option[String]): Option[api.FilmFrontPageData] = { + def filmFrontPage(language: Option[String]): Option[api.FilmFrontPageDataDTO] = { filmFrontPageRepository.get.map(page => ConverterService.toApiFilmFrontPage(page, language)) } } diff --git a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/WriteService.scala b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/WriteService.scala index a2e7e9dbe6..290a995f75 100644 --- a/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/WriteService.scala +++ b/frontpage-api/src/main/scala/no/ndla/frontpageapi/service/WriteService.scala @@ -7,7 +7,7 @@ package no.ndla.frontpageapi.service -import no.ndla.common.model.api.FrontPage +import no.ndla.common.model.api.FrontPageDTO import no.ndla.frontpageapi.Props import no.ndla.frontpageapi.model.api import no.ndla.frontpageapi.model.domain.Errors.{SubjectPageNotFoundException, ValidationException} @@ -21,7 +21,7 @@ trait WriteService { class WriteService { - def newSubjectPage(subject: api.NewSubjectFrontPageData): Try[api.SubjectPageData] = { + def newSubjectPage(subject: api.NewSubjectFrontPageDataDTO): Try[api.SubjectPageDataDTO] = { for { convertedSubject <- ConverterService.toDomainSubjectPage(subject) subjectPage <- subjectPageRepository.newSubjectPage(convertedSubject, subject.externalId.getOrElse("")) @@ -31,9 +31,9 @@ trait WriteService { def updateSubjectPage( id: Long, - subject: api.NewSubjectFrontPageData, + subject: api.NewSubjectFrontPageDataDTO, language: String - ): Try[api.SubjectPageData] = { + ): Try[api.SubjectPageDataDTO] = { subjectPageRepository.exists(id) match { case Success(exists) if exists => for { @@ -49,10 +49,10 @@ trait WriteService { def updateSubjectPage( id: Long, - subject: api.UpdatedSubjectFrontPageData, + subject: api.UpdatedSubjectFrontPageDataDTO, language: String, fallback: Boolean - ): Try[api.SubjectPageData] = { + ): Try[api.SubjectPageDataDTO] = { subjectPageRepository.withId(id) match { case Failure(ex) => Failure(ex) case Success(Some(existingSubject)) => @@ -70,14 +70,14 @@ trait WriteService { } private def newFromUpdatedSubjectPage( - updatedSubjectPage: api.UpdatedSubjectFrontPageData - ): Option[api.NewSubjectFrontPageData] = { + updatedSubjectPage: api.UpdatedSubjectFrontPageDataDTO + ): Option[api.NewSubjectFrontPageDataDTO] = { for { name <- updatedSubjectPage.name banner <- updatedSubjectPage.banner about <- updatedSubjectPage.about metaDescription <- updatedSubjectPage.metaDescription - } yield api.NewSubjectFrontPageData( + } yield api.NewSubjectFrontPageDataDTO( name = name, externalId = updatedSubjectPage.externalId, banner = banner, @@ -90,7 +90,7 @@ trait WriteService { ) } - def createFrontPage(page: FrontPage): Try[FrontPage] = { + def createFrontPage(page: FrontPageDTO): Try[FrontPageDTO] = { for { domainFrontpage <- Try(ConverterService.toDomainFrontPage(page)) inserted <- frontPageRepository.newFrontPage(domainFrontpage) @@ -98,7 +98,7 @@ trait WriteService { } yield api } - def updateFilmFrontPage(page: api.NewOrUpdatedFilmFrontPageData): Try[api.FilmFrontPageData] = { + def updateFilmFrontPage(page: api.NewOrUpdatedFilmFrontPageDataDTO): Try[api.FilmFrontPageDataDTO] = { val domainFilmFrontPageT = ConverterService.toDomainFilmFrontPage(page) for { domainFilmFrontPage <- domainFilmFrontPageT diff --git a/frontpage-api/src/test/scala/no/ndla/frontpageapi/TestData.scala b/frontpage-api/src/test/scala/no/ndla/frontpageapi/TestData.scala index 5306f7a35f..2eef5fb10e 100644 --- a/frontpage-api/src/test/scala/no/ndla/frontpageapi/TestData.scala +++ b/frontpage-api/src/test/scala/no/ndla/frontpageapi/TestData.scala @@ -9,7 +9,7 @@ package no.ndla.frontpageapi import io.circe.generic.auto._ import io.circe.syntax._ -import no.ndla.frontpageapi.model.api.{NewSubjectFrontPageData, SubjectPageData, UpdatedSubjectFrontPageData} +import no.ndla.frontpageapi.model.api.{NewSubjectFrontPageDataDTO, SubjectPageDataDTO, UpdatedSubjectFrontPageDataDTO} import no.ndla.frontpageapi.model.domain.{FilmFrontPageData, SubjectFrontPageData, VisualElementType} import no.ndla.frontpageapi.model.{api, domain} @@ -56,20 +56,20 @@ object TestData { List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204") ) - val apiSubjectPage: SubjectPageData = api.SubjectPageData( + val apiSubjectPage: SubjectPageDataDTO = api.SubjectPageDataDTO( 1, "Samfunnsfag", - api.BannerImage( + api.BannerImageDTO( Some("http://api-gateway.ndla-local/image-api/raw/id/29668"), Some(29668), "http://api-gateway.ndla-local/image-api/raw/id/29668", 29668 ), Some( - api.AboutSubject( + api.AboutSubjectDTO( "Om Samfunnsfag", "Dette er samfunnsfag", - api.VisualElement("image", "http://api-gateway.ndla-local/image-api/raw/id/123", Some("alt text")) + api.VisualElementDTO("image", "http://api-gateway.ndla-local/image-api/raw/id/123", Some("alt text")) ) ), Some("meta"), @@ -80,40 +80,40 @@ object TestData { List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204") ) - val apiNewSubjectPage: NewSubjectFrontPageData = api.NewSubjectFrontPageData( + val apiNewSubjectPage: NewSubjectFrontPageDataDTO = api.NewSubjectFrontPageDataDTO( "Samfunnsfag", None, - api.NewOrUpdateBannerImage(Some(29668), 29668), + api.NewOrUpdateBannerImageDTO(Some(29668), 29668), Seq( - api.NewOrUpdatedAboutSubject( + api.NewOrUpdatedAboutSubjectDTO( "Om Samfunnsfag", "Dette er samfunnsfag", "nb", - api.NewOrUpdatedVisualElement("image", "123", Some("alt text")) + api.NewOrUpdatedVisualElementDTO("image", "123", Some("alt text")) ) ), - Seq(api.NewOrUpdatedMetaDescription("meta", "nb")), + Seq(api.NewOrUpdatedMetaDescriptionDTO("meta", "nb")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")) ) - val apiUpdatedSubjectPage: UpdatedSubjectFrontPageData = api.UpdatedSubjectFrontPageData( + val apiUpdatedSubjectPage: UpdatedSubjectFrontPageDataDTO = api.UpdatedSubjectFrontPageDataDTO( Some("Samfunnsfag"), None, - Some(api.NewOrUpdateBannerImage(Some(29668), 29668)), + Some(api.NewOrUpdateBannerImageDTO(Some(29668), 29668)), Some( List( - api.NewOrUpdatedAboutSubject( + api.NewOrUpdatedAboutSubjectDTO( "Om Samfunnsfag", "Dette er oppdatert om samfunnsfag", "nb", - api.NewOrUpdatedVisualElement("image", "123", Some("alt text")) + api.NewOrUpdatedVisualElementDTO("image", "123", Some("alt text")) ) ) ), - Some(List(api.NewOrUpdatedMetaDescription("meta", "nb"))), + Some(List(api.NewOrUpdatedMetaDescriptionDTO("meta", "nb"))), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), Some(List("urn:resource:1:161411", "urn:resource:1:182176", "urn:resource:1:183636", "urn:resource:1:170204")), @@ -149,5 +149,5 @@ object TestData { None ) - val apiFilmFrontPage: api.FilmFrontPageData = api.FilmFrontPageData("", Seq(), Seq(), Seq(), None) + val apiFilmFrontPage: api.FilmFrontPageDataDTO = api.FilmFrontPageDataDTO("", Seq(), Seq(), Seq(), None) } diff --git a/frontpage-api/src/test/scala/no/ndla/frontpageapi/controller/FrontPageControllerTest.scala b/frontpage-api/src/test/scala/no/ndla/frontpageapi/controller/FrontPageControllerTest.scala index 422ecd3006..4e4a667d4b 100644 --- a/frontpage-api/src/test/scala/no/ndla/frontpageapi/controller/FrontPageControllerTest.scala +++ b/frontpage-api/src/test/scala/no/ndla/frontpageapi/controller/FrontPageControllerTest.scala @@ -8,7 +8,7 @@ package no.ndla.frontpageapi.controller import no.ndla.common.{model, errors as common} -import no.ndla.common.model.api.FrontPage +import no.ndla.common.model.api.FrontPageDTO import no.ndla.frontpageapi.{TestEnvironment, UnitSuite} import no.ndla.tapirtesting.TapirControllerTest import org.mockito.ArgumentMatchers.any @@ -96,7 +96,7 @@ class FrontPageControllerTest extends UnitSuite with TestEnvironment with TapirC } test("That POST / returns 200 if auth header does have correct role") { - when(writeService.createFrontPage(any)).thenReturn(Success(FrontPage(1, List()))) + when(writeService.createFrontPage(any)).thenReturn(Success(FrontPageDTO(1, List()))) val request = quickRequest @@ -110,7 +110,7 @@ class FrontPageControllerTest extends UnitSuite with TestEnvironment with TapirC } test("That POST / returns 400 if auth header does have correct role but the json body is malformed") { - when(writeService.createFrontPage(any)).thenReturn(Success(model.api.FrontPage(1, List()))) + when(writeService.createFrontPage(any)).thenReturn(Success(model.api.FrontPageDTO(1, List()))) val request = quickRequest @@ -124,7 +124,7 @@ class FrontPageControllerTest extends UnitSuite with TestEnvironment with TapirC } test("That GET / returns 200 when the frontpage is available") { - val frontPage = model.api.FrontPage(articleId = 1, menu = List.empty) + val frontPage = model.api.FrontPageDTO(articleId = 1, menu = List.empty) when(readService.getFrontPage).thenReturn(Success(frontPage)) val request = quickRequest.get(uri"http://localhost:$serverPort/frontpage-api/v1/frontpage") diff --git a/frontpage-api/src/test/scala/no/ndla/frontpageapi/model/api/FrontPageTest/FrontPageTest.scala b/frontpage-api/src/test/scala/no/ndla/frontpageapi/model/api/FrontPageTest/FrontPageTest.scala index 8f4be6d872..9df16c0e1b 100644 --- a/frontpage-api/src/test/scala/no/ndla/frontpageapi/model/api/FrontPageTest/FrontPageTest.scala +++ b/frontpage-api/src/test/scala/no/ndla/frontpageapi/model/api/FrontPageTest/FrontPageTest.scala @@ -11,15 +11,18 @@ import no.ndla.frontpageapi.{TestEnvironment, UnitSuite} import io.circe.generic.auto._ import io.circe.syntax._ import io.circe.parser._ -import no.ndla.common.model.api.{FrontPage, Menu} +import no.ndla.common.model.api.{FrontPageDTO, MenuDTO} class FrontPageTest extends UnitSuite with TestEnvironment { test("test that circe encoding and decoding works for recursive types") { val before = - FrontPage(1, List(Menu(2, List(Menu(3, List(Menu(4, List(), Some(false))), Some(false))), Some(false)))) + FrontPageDTO( + 1, + List(MenuDTO(2, List(MenuDTO(3, List(MenuDTO(4, List(), Some(false))), Some(false))), Some(false))) + ) val jsonString = before.asJson.noSpaces val parsed = parse(jsonString).toTry.get - val converted = parsed.as[FrontPage].toTry.get + val converted = parsed.as[FrontPageDTO].toTry.get converted should be(before) } } diff --git a/frontpage-api/src/test/scala/no/ndla/frontpageapi/service/ConverterServiceTest.scala b/frontpage-api/src/test/scala/no/ndla/frontpageapi/service/ConverterServiceTest.scala index 6f4d948353..9a572de9cd 100644 --- a/frontpage-api/src/test/scala/no/ndla/frontpageapi/service/ConverterServiceTest.scala +++ b/frontpage-api/src/test/scala/no/ndla/frontpageapi/service/ConverterServiceTest.scala @@ -62,7 +62,7 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("toDomainSubjectPage updates subject links correctly") { - val updateWith = UpdatedSubjectFrontPageData( + val updateWith = UpdatedSubjectFrontPageDataDTO( None, None, None, @@ -86,12 +86,12 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("toDomainSubjectPage updates meta description correctly") { - val updateWith = UpdatedSubjectFrontPageData( + val updateWith = UpdatedSubjectFrontPageDataDTO( None, None, None, None, - Some(List(NewOrUpdatedMetaDescription("oppdatert meta", "nb"))), + Some(List(NewOrUpdatedMetaDescriptionDTO("oppdatert meta", "nb"))), None, None, None, @@ -104,17 +104,17 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("toDomainSubjectPage updates aboutSubject correctly") { - val updateWith = UpdatedSubjectFrontPageData( + val updateWith = UpdatedSubjectFrontPageDataDTO( None, None, None, Some( List( - NewOrUpdatedAboutSubject( + NewOrUpdatedAboutSubjectDTO( "oppdatert tittel", "oppdatert beskrivelse", "nb", - NewOrUpdatedVisualElement("image", "1", None) + NewOrUpdatedVisualElementDTO("image", "1", None) ) ) ), @@ -138,23 +138,23 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { } test("toDomainSubjectPage adds new language correctly") { - val updateWith = UpdatedSubjectFrontPageData( + val updateWith = UpdatedSubjectFrontPageDataDTO( None, None, None, Some( List( - NewOrUpdatedAboutSubject( + NewOrUpdatedAboutSubjectDTO( "About Social studies", "This is social studies", "en", - NewOrUpdatedVisualElement("image", "123", None) + NewOrUpdatedVisualElementDTO("image", "123", None) ) ) ), Some( List( - NewOrUpdatedMetaDescription("meta description", "en") + NewOrUpdatedMetaDescriptionDTO("meta description", "en") ) ), None, diff --git a/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV2.scala b/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV2.scala index 1780d5198c..2a851a4dab 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV2.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV2.scala @@ -61,8 +61,8 @@ trait ImageControllerV2 { * A Try with scroll result, or the return of the orFunction (Usually a try with a search result). */ protected def scrollSearchOr(scrollId: Option[String], language: String, user: Option[TokenUser])( - orFunction: => Try[(SearchResult, DynamicHeaders)] - ): Try[(SearchResult, DynamicHeaders)] = + orFunction: => Try[(SearchResultDTO, DynamicHeaders)] + ): Try[(SearchResultDTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => imageSearchService.scrollV2(scroll, language, user) match { @@ -148,7 +148,7 @@ trait ImageControllerV2 { .in(scrollId) .in(modelReleased) .errorOut(errorOutputsFor(400)) - .out(jsonBody[SearchResult]) + .out(jsonBody[SearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .withOptionalUser .serverLogicPure { user => @@ -195,9 +195,9 @@ trait ImageControllerV2 { .summary("Find images.") .description("Search for images in the ndla.no database.") .in("search") - .in(jsonBody[SearchParams]) + .in(jsonBody[SearchParamsDTO]) .errorOut(errorOutputsFor(400)) - .out(jsonBody[SearchResult]) + .out(jsonBody[SearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .withOptionalUser .serverLogicPure(user => { searchParams => @@ -239,7 +239,7 @@ trait ImageControllerV2 { .description("Shows info of the image with submitted id.") .in(pathImageId) .in(languageOpt) - .out(jsonBody[ImageMetaInformationV2]) + .out(jsonBody[ImageMetaInformationV2DTO]) .errorOut(errorOutputsFor(404)) .withOptionalUser .serverLogicPure { user => @@ -258,7 +258,7 @@ trait ImageControllerV2 { .description("Shows info of the image with submitted external id.") .in("external_id" / pathExternalId) .in(languageOpt) - .out(jsonBody[ImageMetaInformationV2]) + .out(jsonBody[ImageMetaInformationV2DTO]) .errorOut(errorOutputsFor(404)) .withOptionalUser .serverLogicPure { user => @@ -276,7 +276,7 @@ trait ImageControllerV2 { .description("Upload a new image file with meta data.") .in(multipartBody[MetaDataAndFileForm](implicitly)) .errorOut(errorOutputsFor(400, 401, 403, 413)) - .out(jsonBody[ImageMetaInformationV2]) + .out(jsonBody[ImageMetaInformationV2DTO]) .requirePermission(IMAGE_API_WRITE) .serverLogicPure { user => formData => doWithStream(formData.file) { uploadedFile => @@ -308,7 +308,7 @@ trait ImageControllerV2 { .summary("Delete language version of image metadata.") .description("Delete language version of image metadata.") .in(pathImageId / "language" / pathLanguage) - .out(noContentOrBodyOutput[ImageMetaInformationV2]) + .out(noContentOrBodyOutput[ImageMetaInformationV2DTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(IMAGE_API_WRITE) .serverLogicPure { user => @@ -323,7 +323,7 @@ trait ImageControllerV2 { .in(pathImageId) .in(multipartBody[UpdateMetaDataAndFileForm]) .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[ImageMetaInformationV2]) + .out(jsonBody[ImageMetaInformationV2DTO]) .requirePermission(IMAGE_API_WRITE) .serverLogicPure { user => input => val (imageId, formData) = input @@ -341,7 +341,7 @@ trait ImageControllerV2 { .in(pageNo) .in(language) .in(sort) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .serverLogicPure { case (q, pageSizeParam, pageNoParam, language, sortStr) => val query = q.getOrElse("") diff --git a/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV3.scala b/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV3.scala index 7c13282f31..aabec590aa 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV3.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/controller/ImageControllerV3.scala @@ -61,7 +61,7 @@ trait ImageControllerV3 { scrollId: Option[String], language: String, user: Option[TokenUser] - )(orFunction: => Try[(SearchResultV3, DynamicHeaders)]): Try[(SearchResultV3, DynamicHeaders)] = + )(orFunction: => Try[(SearchResultV3DTO, DynamicHeaders)]): Try[(SearchResultV3DTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => for { @@ -142,7 +142,7 @@ trait ImageControllerV3 { .in(scrollId) .in(modelReleased) .errorOut(errorOutputsFor(400)) - .out(jsonBody[SearchResultV3]) + .out(jsonBody[SearchResultV3DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .withOptionalUser .serverLogicPure { user => @@ -189,9 +189,9 @@ trait ImageControllerV3 { .summary("Find images.") .description("Search for images in the ndla.no database.") .in("search") - .in(jsonBody[SearchParams]) + .in(jsonBody[SearchParamsDTO]) .errorOut(errorOutputsFor(400)) - .out(jsonBody[SearchResultV3]) + .out(jsonBody[SearchResultV3DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .withOptionalUser .serverLogicPure { @@ -238,7 +238,7 @@ trait ImageControllerV3 { .in(pathImageId) .in(languageOpt) .errorOut(errorOutputsFor(400)) - .out(jsonBody[ImageMetaInformationV3]) + .out(jsonBody[ImageMetaInformationV3DTO]) .withOptionalUser .serverLogicPure { user => { case (imageId, language) => @@ -256,7 +256,7 @@ trait ImageControllerV3 { .in("ids") .in(imageIds) .in(languageOpt) - .out(jsonBody[List[ImageMetaInformationV3]]) + .out(jsonBody[List[ImageMetaInformationV3DTO]]) .errorOut(errorOutputsFor(400)) .withOptionalUser .serverLogicPure { user => @@ -270,7 +270,7 @@ trait ImageControllerV3 { .description("Shows info of the image with submitted external id.") .in("external_id" / pathExternalId) .in(languageOpt) - .out(jsonBody[ImageMetaInformationV3]) + .out(jsonBody[ImageMetaInformationV3DTO]) .errorOut(errorOutputsFor(400)) .withOptionalUser .serverLogicPure { user => @@ -285,7 +285,7 @@ trait ImageControllerV3 { def newImageV3: ServerEndpoint[Any, Eff] = endpoint.post .summary("Upload a new image with meta information.") .description("Upload a new image file with meta data.") - .out(jsonBody[ImageMetaInformationV3]) + .out(jsonBody[ImageMetaInformationV3DTO]) .in(multipartBody[MetaDataAndFileForm]) .errorOut(errorOutputsFor(400)) .requirePermission(IMAGE_API_WRITE) @@ -321,7 +321,7 @@ trait ImageControllerV3 { .summary("Delete language version of image metadata.") .description("Delete language version of image metadata.") .in(pathImageId / "language" / pathLanguage) - .out(noContentOrBodyOutput[ImageMetaInformationV3]) + .out(noContentOrBodyOutput[ImageMetaInformationV3DTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(IMAGE_API_WRITE) .serverLogicPure(user => { case (imageId, language) => @@ -336,7 +336,7 @@ trait ImageControllerV3 { .summary("Update an existing image with meta information.") .description("Updates an existing image with meta data.") .in(pathImageId) - .out(jsonBody[ImageMetaInformationV3]) + .out(jsonBody[ImageMetaInformationV3DTO]) .in(multipartBody[UpdateMetaDataAndFileForm]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(IMAGE_API_WRITE) @@ -356,7 +356,7 @@ trait ImageControllerV3 { .in(pageNo) .in(language) .in(sort) - .out(jsonBody[TagsSearchResult]) + .out(jsonBody[TagsSearchResultDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .serverLogicPure { case (q, pageSizeParam, pageNoParam, language, sortStr) => val query = q.getOrElse("") diff --git a/image-api/src/main/scala/no/ndla/imageapi/controller/InternController.scala b/image-api/src/main/scala/no/ndla/imageapi/controller/InternController.scala index 65f9d24d7b..b4f6085ede 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/controller/InternController.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/controller/InternController.scala @@ -10,7 +10,7 @@ package no.ndla.imageapi.controller import cats.implicits.* import com.typesafe.scalalogging.StrictLogging -import no.ndla.imageapi.model.api.{ErrorHandling, ImageMetaDomainDump, ImageMetaInformationV2} +import no.ndla.imageapi.model.api.{ErrorHandling, ImageMetaDomainDumpDTO, ImageMetaInformationV2DTO} import no.ndla.imageapi.model.domain.ImageMetaInformation import no.ndla.imageapi.repository.ImageRepository import no.ndla.imageapi.service.search.{ImageIndexService, TagIndexService} @@ -114,7 +114,7 @@ trait InternController { def getExternImageId: ServerEndpoint[Any, Eff] = endpoint.get .in("extern" / path[String]("image_id")) .in(query[Option[String]]("language")) - .out(jsonBody[ImageMetaInformationV2]) + .out(jsonBody[ImageMetaInformationV2DTO]) .errorOut(errorOutputsFor(404)) .withOptionalUser .serverLogicPure { user => @@ -142,7 +142,7 @@ trait InternController { .in("dump" / "image") .in(query[Int]("page").default(1)) .in(query[Int]("page-size").default(250)) - .out(jsonBody[ImageMetaDomainDump]) + .out(jsonBody[ImageMetaDomainDumpDTO]) .serverLogicPure { case (page, pageSize) => readService.getMetaImageDomainDump(page, pageSize).asRight } diff --git a/image-api/src/main/scala/no/ndla/imageapi/controller/multipart/MultipartInput.scala b/image-api/src/main/scala/no/ndla/imageapi/controller/multipart/MultipartInput.scala index 514f046470..491613ef7c 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/controller/multipart/MultipartInput.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/controller/multipart/MultipartInput.scala @@ -7,17 +7,17 @@ package no.ndla.imageapi.controller.multipart -import no.ndla.imageapi.model.api.{NewImageMetaInformationV2, UpdateImageMetaInformation} +import no.ndla.imageapi.model.api.{NewImageMetaInformationV2DTO, UpdateImageMetaInformationDTO} import sttp.model.Part import java.io.File case class MetaDataAndFileForm( - metadata: Part[NewImageMetaInformationV2], + metadata: Part[NewImageMetaInformationV2DTO], file: Part[File] ) case class UpdateMetaDataAndFileForm( - metadata: Part[UpdateImageMetaInformation], + metadata: Part[UpdateImageMetaInformationDTO], file: Option[Part[File]] ) diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNote.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNoteDTO.scala similarity index 72% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNote.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNoteDTO.scala index 96655da3eb..851fc834c5 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNote.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/EditorNoteDTO.scala @@ -13,13 +13,13 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Note about a change that happened to the image") -case class EditorNote( +case class EditorNoteDTO( @description("Timestamp of the change") timestamp: NDLADate, @description("Who triggered the change") updatedBy: String, @description("Editorial note") note: String ) -object EditorNote { - implicit val encoder: Encoder[EditorNote] = deriveEncoder[EditorNote] - implicit val decoder: Decoder[EditorNote] = deriveDecoder[EditorNote] +object EditorNoteDTO { + implicit val encoder: Encoder[EditorNoteDTO] = deriveEncoder[EditorNoteDTO] + implicit val decoder: Decoder[EditorNoteDTO] = deriveDecoder[EditorNoteDTO] } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltText.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltTextDTO.scala similarity index 72% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltText.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltTextDTO.scala index 61866ce704..7133111101 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltText.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageAltTextDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Alt-text of an image") -case class ImageAltText( +case class ImageAltTextDTO( @description("The alternative text for the image") alttext: String, @description("ISO 639-1 code that represents the language used in the alternative text") language: String ) -object ImageAltText { - implicit val encoder: Encoder[ImageAltText] = deriveEncoder - implicit val decoder: Decoder[ImageAltText] = deriveDecoder +object ImageAltTextDTO { + implicit val encoder: Encoder[ImageAltTextDTO] = deriveEncoder + implicit val decoder: Decoder[ImageAltTextDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaption.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaptionDTO.scala similarity index 68% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaption.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaptionDTO.scala index e41d302210..e6ccfa529c 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaption.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageCaptionDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("An image caption") -case class ImageCaption( +case class ImageCaptionDTO( @description("The caption for the image") caption: String, @description("ISO 639-1 code that represents the language used in the caption") language: String ) -object ImageCaption { - implicit def encoder: Encoder[ImageCaption] = deriveEncoder[ImageCaption] - implicit def decoder: Decoder[ImageCaption] = deriveDecoder[ImageCaption] +object ImageCaptionDTO { + implicit def encoder: Encoder[ImageCaptionDTO] = deriveEncoder[ImageCaptionDTO] + implicit def decoder: Decoder[ImageCaptionDTO] = deriveDecoder[ImageCaptionDTO] } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/Image.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDTO.scala similarity index 95% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/Image.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDTO.scala index 067668026d..f1cbae6f1e 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/Image.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDTO.scala @@ -10,7 +10,7 @@ package no.ndla.imageapi.model.api import sttp.tapir.Schema.annotations.description @description("Url and size information about the image") -case class Image( +case class ImageDTO( @description("The full url to where the image can be downloaded") url: String, @description("The size of the image in bytes") size: Long, @description("The mimetype of the image") contentType: String diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensions.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensionsDTO.scala similarity index 65% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensions.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensionsDTO.scala index b0974e5010..e913db9385 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensions.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageDimensionsDTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Dimensions of an image") -case class ImageDimensions( +case class ImageDimensionsDTO( @description("The width of the image in pixels") width: Int, @description("The height of the image in pixels") height: Int ) -object ImageDimensions { - implicit val encoder: Encoder[ImageDimensions] = deriveEncoder[ImageDimensions] - implicit val decoder: Decoder[ImageDimensions] = deriveDecoder[ImageDimensions] +object ImageDimensionsDTO { + implicit val encoder: Encoder[ImageDimensionsDTO] = deriveEncoder[ImageDimensionsDTO] + implicit val decoder: Decoder[ImageDimensionsDTO] = deriveDecoder[ImageDimensionsDTO] } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFile.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFileDTO.scala similarity index 80% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFile.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFileDTO.scala index 38f3aa569f..0040c49cb0 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFile.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageFileDTO.scala @@ -14,16 +14,16 @@ import no.ndla.language.Language.LanguageDocString import sttp.tapir.Schema.annotations.description @description("Meta information for a image file") -case class ImageFile( +case class ImageFileDTO( @description("File name pointing to image file") fileName: String, @description("The size of the image in bytes") size: Long, @description("The mimetype of the image") contentType: String, @description("The full url to where the image can be downloaded") imageUrl: String, - @description("Dimensions of the image") dimensions: Option[ImageDimensions], + @description("Dimensions of the image") dimensions: Option[ImageDimensionsDTO], @description(LanguageDocString) language: String ) -object ImageFile { - implicit val encoder: Encoder[ImageFile] = deriveEncoder - implicit val decoder: Decoder[ImageFile] = deriveDecoder +object ImageFileDTO { + implicit val encoder: Encoder[ImageFileDTO] = deriveEncoder + implicit val decoder: Decoder[ImageFileDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDump.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDumpDTO.scala similarity index 75% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDump.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDumpDTO.scala index 5b23f20a85..b8f7d3b508 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDump.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaDomainDumpDTO.scala @@ -13,14 +13,14 @@ import no.ndla.imageapi.model.domain.ImageMetaInformation import sttp.tapir.Schema.annotations.description @description("Information about image meta dump") -case class ImageMetaDomainDump( +case class ImageMetaDomainDumpDTO( @description("The total number of images in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The search results") results: Seq[ImageMetaInformation] ) -object ImageMetaDomainDump { - implicit val encoder: Encoder[ImageMetaDomainDump] = deriveEncoder - implicit val decoder: Decoder[ImageMetaDomainDump] = deriveDecoder +object ImageMetaDomainDumpDTO { + implicit val encoder: Encoder[ImageMetaDomainDumpDTO] = deriveEncoder + implicit val decoder: Decoder[ImageMetaDomainDumpDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2.scala deleted file mode 100644 index 4677dc2450..0000000000 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Part of NDLA image-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.imageapi.model.api - -import io.circe.{Decoder, Encoder} -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.Copyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Meta information for the image") -case class ImageMetaInformationV2( - @description("The unique id of the image") id: String, - @description("The url to where this information can be found") metaUrl: String, - @description("The title for the image") title: ImageTitle, - @description("Alternative text for the image") alttext: ImageAltText, - @description("The full url to where the image can be downloaded") imageUrl: String, - @description("The size of the image in bytes") size: Long, - @description("The mimetype of the image") contentType: String, - @description("Describes the copyright information for the image") copyright: Copyright, - @description("Searchable tags for the image") tags: ImageTag, - @description("Searchable caption for the image") caption: ImageCaption, - @description("Supported languages for the image title, alt-text, tags and caption.") supportedLanguages: Seq[String], - @description("Describes when the image was created") created: NDLADate, - @description("Describes who created the image") createdBy: String, - @description("Describes if the model has released use of the image") modelRelease: String, - @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[EditorNote]], - @description("Dimensions of the image") imageDimensions: Option[ImageDimensions] -) - -object ImageMetaInformationV2 { - implicit val encoder: Encoder[ImageMetaInformationV2] = deriveEncoder[ImageMetaInformationV2] - implicit val decoder: Decoder[ImageMetaInformationV2] = deriveDecoder[ImageMetaInformationV2] -} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2DTO.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2DTO.scala new file mode 100644 index 0000000000..8dd2d933ff --- /dev/null +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV2DTO.scala @@ -0,0 +1,40 @@ +/* + * Part of NDLA image-api + * Copyright (C) 2017 NDLA + * + * See LICENSE + */ + +package no.ndla.imageapi.model.api + +import io.circe.{Decoder, Encoder} +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.CopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Meta information for the image") +case class ImageMetaInformationV2DTO( + @description("The unique id of the image") id: String, + @description("The url to where this information can be found") metaUrl: String, + @description("The title for the image") title: ImageTitleDTO, + @description("Alternative text for the image") alttext: ImageAltTextDTO, + @description("The full url to where the image can be downloaded") imageUrl: String, + @description("The size of the image in bytes") size: Long, + @description("The mimetype of the image") contentType: String, + @description("Describes the copyright information for the image") copyright: CopyrightDTO, + @description("Searchable tags for the image") tags: ImageTagDTO, + @description("Searchable caption for the image") caption: ImageCaptionDTO, + @description("Supported languages for the image title, alt-text, tags and caption.") supportedLanguages: Seq[String], + @description("Describes when the image was created") created: NDLADate, + @description("Describes who created the image") createdBy: String, + @description("Describes if the model has released use of the image") modelRelease: String, + @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[EditorNoteDTO]], + @description("Dimensions of the image") imageDimensions: Option[ImageDimensionsDTO] +) + +object ImageMetaInformationV2DTO { + implicit val encoder: Encoder[ImageMetaInformationV2DTO] = deriveEncoder[ImageMetaInformationV2DTO] + implicit val decoder: Decoder[ImageMetaInformationV2DTO] = deriveDecoder[ImageMetaInformationV2DTO] +} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3.scala deleted file mode 100644 index f5c1dd2d00..0000000000 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Part of NDLA image-api - * Copyright (C) 2022 NDLA - * - * See LICENSE - */ - -package no.ndla.imageapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.Copyright -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Meta information for the image") -case class ImageMetaInformationV3( - @description("The unique id of the image") id: String, - @description("The url to where this information can be found") metaUrl: String, - @description("The title for the image") title: ImageTitle, - @description("Alternative text for the image") alttext: ImageAltText, - @description("Describes the copyright information for the image") copyright: Copyright, - @description("Searchable tags for the image") tags: ImageTag, - @description("Searchable caption for the image") caption: ImageCaption, - @description("Supported languages for the image title, alt-text, tags and caption.") supportedLanguages: Seq[String], - @description("Describes when the image was created") created: NDLADate, - @description("Describes who created the image") createdBy: String, - @description("Describes if the model has released use of the image") modelRelease: String, - @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[EditorNote]], - @description("Describes the image file") image: ImageFile -) - -object ImageMetaInformationV3{ - implicit val encoder: Encoder[ImageMetaInformationV3] = deriveEncoder - implicit val decoder: Decoder[ImageMetaInformationV3] = deriveDecoder -} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3DTO.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3DTO.scala new file mode 100644 index 0000000000..a94402391b --- /dev/null +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaInformationV3DTO.scala @@ -0,0 +1,37 @@ +/* + * Part of NDLA image-api + * Copyright (C) 2022 NDLA + * + * See LICENSE + */ + +package no.ndla.imageapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.CopyrightDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Meta information for the image") +case class ImageMetaInformationV3DTO( + @description("The unique id of the image") id: String, + @description("The url to where this information can be found") metaUrl: String, + @description("The title for the image") title: ImageTitleDTO, + @description("Alternative text for the image") alttext: ImageAltTextDTO, + @description("Describes the copyright information for the image") copyright: CopyrightDTO, + @description("Searchable tags for the image") tags: ImageTagDTO, + @description("Searchable caption for the image") caption: ImageCaptionDTO, + @description("Supported languages for the image title, alt-text, tags and caption.") supportedLanguages: Seq[String], + @description("Describes when the image was created") created: NDLADate, + @description("Describes who created the image") createdBy: String, + @description("Describes if the model has released use of the image") modelRelease: String, + @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[EditorNoteDTO]], + @description("Describes the image file") image: ImageFileDTO +) + +object ImageMetaInformationV3DTO{ + implicit val encoder: Encoder[ImageMetaInformationV3DTO] = deriveEncoder + implicit val decoder: Decoder[ImageMetaInformationV3DTO] = deriveDecoder +} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummary.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummary.scala deleted file mode 100644 index 97fc977351..0000000000 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummary.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Part of NDLA image-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.imageapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Summary of meta information for an image") -case class ImageMetaSummary( - @description("The unique id of the image") id: String, - @description("The title for this image") title: ImageTitle, - @description("The copyright authors for this image") contributors: Seq[String], - @description("The alt text for this image") altText: ImageAltText, - @description("The caption for this image") caption: ImageCaption, - @description("The full url to where a preview of the image can be downloaded") previewUrl: String, - @description("The full url to where the complete metainformation about the image can be found") metaUrl: String, - @description("Describes the license of the image") license: String, - @description("List of supported languages in priority") supportedLanguages: Seq[String], - @description("Describes if the model has released use of the image") modelRelease: Option[String], - @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[String]], - @description("The time and date of last update") lastUpdated: NDLADate, - @description("The size of the image in bytes") fileSize: Long, - @description("The mimetype of the image") contentType: String, - @description("Dimensions of the image") imageDimensions: Option[ImageDimensions] -) - -object ImageMetaSummary { - implicit val encoder: Encoder[ImageMetaSummary] = deriveEncoder - implicit val decoder: Decoder[ImageMetaSummary] = deriveDecoder -} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummaryDTO.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummaryDTO.scala new file mode 100644 index 0000000000..76d051498d --- /dev/null +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageMetaSummaryDTO.scala @@ -0,0 +1,38 @@ +/* + * Part of NDLA image-api + * Copyright (C) 2017 NDLA + * + * See LICENSE + */ + +package no.ndla.imageapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Summary of meta information for an image") +case class ImageMetaSummaryDTO( + @description("The unique id of the image") id: String, + @description("The title for this image") title: ImageTitleDTO, + @description("The copyright authors for this image") contributors: Seq[String], + @description("The alt text for this image") altText: ImageAltTextDTO, + @description("The caption for this image") caption: ImageCaptionDTO, + @description("The full url to where a preview of the image can be downloaded") previewUrl: String, + @description("The full url to where the complete metainformation about the image can be found") metaUrl: String, + @description("Describes the license of the image") license: String, + @description("List of supported languages in priority") supportedLanguages: Seq[String], + @description("Describes if the model has released use of the image") modelRelease: Option[String], + @description("Describes the changes made to the image, only visible to editors") editorNotes: Option[Seq[String]], + @description("The time and date of last update") lastUpdated: NDLADate, + @description("The size of the image in bytes") fileSize: Long, + @description("The mimetype of the image") contentType: String, + @description("Dimensions of the image") imageDimensions: Option[ImageDimensionsDTO] +) + +object ImageMetaSummaryDTO { + implicit val encoder: Encoder[ImageMetaSummaryDTO] = deriveEncoder + implicit val decoder: Decoder[ImageMetaSummaryDTO] = deriveDecoder +} diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTag.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTagDTO.scala similarity index 70% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTag.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTagDTO.scala index 71c79561a8..33aedd4308 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTag.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTagDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("An tag for an image") -case class ImageTag( +case class ImageTagDTO( @description("The searchable tag.") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) -object ImageTag { - implicit def encoder: Encoder[ImageTag] = deriveEncoder[ImageTag] - implicit def decoder: Decoder[ImageTag] = deriveDecoder[ImageTag] +object ImageTagDTO { + implicit def encoder: Encoder[ImageTagDTO] = deriveEncoder[ImageTagDTO] + implicit def decoder: Decoder[ImageTagDTO] = deriveDecoder[ImageTagDTO] } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitle.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitleDTO.scala similarity index 69% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitle.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitleDTO.scala index 374aa0933b..1b235d610e 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitle.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/ImageTitleDTO.scala @@ -13,12 +13,12 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import sttp.tapir.Schema.annotations.description @description("Title of the image") -case class ImageTitle( +case class ImageTitleDTO( @description("The freetext title of the image") title: String, @description("ISO 639-1 code that represents the language used in title") language: String ) -object ImageTitle { - implicit val encoder: Encoder[ImageTitle] = deriveEncoder[ImageTitle] - implicit val decoder: Decoder[ImageTitle] = deriveDecoder[ImageTitle] +object ImageTitleDTO { + implicit val encoder: Encoder[ImageTitleDTO] = deriveEncoder[ImageTitleDTO] + implicit val decoder: Decoder[ImageTitleDTO] = deriveDecoder[ImageTitleDTO] } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageFile.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageFile.scala deleted file mode 100644 index a120398d80..0000000000 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageFile.scala +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Part of NDLA image-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - */ - -package no.ndla.imageapi.model.api - -import sttp.tapir.Schema.annotations.description - -@description("Url and size information about the image") -case class NewImageFile( - @description("The name of the file") fileName: String, - @description("ISO 639-1 code that represents the language used in the audio") language: Option[String] -) diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2DTO.scala similarity index 75% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2DTO.scala index c721718dcc..d74d62847c 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/NewImageMetaInformationV2DTO.scala @@ -9,22 +9,22 @@ package no.ndla.imageapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.Copyright +import no.ndla.common.model.api.CopyrightDTO import sttp.tapir.Schema.annotations.description // format: off @description("Meta information for the image") -case class NewImageMetaInformationV2( +case class NewImageMetaInformationV2DTO( @description("Title for the image") title: String, @description("Alternative text for the image") alttext: Option[String], - @description("Describes the copyright information for the image") copyright: Copyright, + @description("Describes the copyright information for the image") copyright: CopyrightDTO, @description("Searchable tags for the image") tags: Seq[String], @description("Caption for the image") caption: String, @description("ISO 639-1 code that represents the language used in the caption") language: String, @description("Describes if the model has released use of the image, allowed values are 'not-set', 'yes', 'no', and 'not-applicable', defaults to 'no'") modelReleased: Option[String] ) -object NewImageMetaInformationV2{ - implicit val encoder: Encoder[NewImageMetaInformationV2] = deriveEncoder - implicit val decoder: Decoder[NewImageMetaInformationV2] = deriveDecoder +object NewImageMetaInformationV2DTO{ + implicit val encoder: Encoder[NewImageMetaInformationV2DTO] = deriveEncoder + implicit val decoder: Decoder[NewImageMetaInformationV2DTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParams.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParamsDTO.scala similarity index 90% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParams.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParamsDTO.scala index 681ecf6f5e..b8e268a845 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParams.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchParamsDTO.scala @@ -14,7 +14,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("The search parameters") -case class SearchParams( +case class SearchParamsDTO( @description("Return only images with titles, alt-texts or tags matching the specified query.") query: Option[String], @description("Return only images with provided license.") license: Option[String], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], @@ -29,7 +29,7 @@ case class SearchParams( @description("Return only images with one of the provided values for modelReleased.") modelReleased: Option[Seq[String]] ) -object SearchParams { - implicit val encoder: Encoder[SearchParams] = deriveEncoder - implicit val decoder: Decoder[SearchParams] = deriveDecoder +object SearchParamsDTO { + implicit val encoder: Encoder[SearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[SearchParamsDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResult.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResultDTO.scala similarity index 71% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResult.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResultDTO.scala index 2331d68851..1b8b8e44c9 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResult.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/SearchResultDTO.scala @@ -12,35 +12,35 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class SearchResult( +case class SearchResultDTO( @description("The total number of images matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ImageMetaSummary] + @description("The search results") results: Seq[ImageMetaSummaryDTO] ) -object SearchResult { - implicit val encoder: Encoder[SearchResult] = deriveEncoder - implicit val decoder: Decoder[SearchResult] = deriveDecoder +object SearchResultDTO { + implicit val encoder: Encoder[SearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[SearchResultDTO] = deriveDecoder } @description("Information about search-results") -case class SearchResultV3( +case class SearchResultV3DTO( @description("The total number of images matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[ImageMetaInformationV3] + @description("The search results") results: Seq[ImageMetaInformationV3DTO] ) -object SearchResultV3 { - implicit val encoder: Encoder[SearchResultV3] = deriveEncoder - implicit val decoder: Decoder[SearchResultV3] = deriveDecoder +object SearchResultV3DTO { + implicit val encoder: Encoder[SearchResultV3DTO] = deriveEncoder + implicit val decoder: Decoder[SearchResultV3DTO] = deriveDecoder } @description("Information about tags-search-results") -case class TagsSearchResult( +case class TagsSearchResultDTO( @description("The total number of tags matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @@ -48,7 +48,7 @@ case class TagsSearchResult( @description("The search results") results: Seq[String] ) -object TagsSearchResult { - implicit val encoder: Encoder[TagsSearchResult] = deriveEncoder - implicit val decoder: Decoder[TagsSearchResult] = deriveDecoder +object TagsSearchResultDTO { + implicit val encoder: Encoder[TagsSearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[TagsSearchResultDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformation.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformationDTO.scala similarity index 72% rename from image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformation.scala rename to image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformationDTO.scala index 8e8537629c..6a0d060f67 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformation.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/model/api/UpdateImageMetaInformationDTO.scala @@ -9,22 +9,22 @@ package no.ndla.imageapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.{Copyright, UpdateOrDelete} +import no.ndla.common.model.api.{CopyrightDTO, UpdateOrDelete} import sttp.tapir.Schema.annotations.description @description("Meta information for the image") -case class UpdateImageMetaInformation( +case class UpdateImageMetaInformationDTO( @description("ISO 639-1 code that represents the language") language: String, @description("Title for the image") title: Option[String], @description("Alternative text for the image") alttext: UpdateOrDelete[String], - @description("Describes the copyright information for the image") copyright: Option[Copyright], + @description("Describes the copyright information for the image") copyright: Option[CopyrightDTO], @description("Searchable tags for the image") tags: Option[Seq[String]], @description("Caption for the image") caption: Option[String], @description("Describes if the model has released use of the image") modelReleased: Option[String] ) -object UpdateImageMetaInformation { - implicit val encoder: Encoder[UpdateImageMetaInformation] = - UpdateOrDelete.filterMarkers(deriveEncoder[UpdateImageMetaInformation]) - implicit val decoder: Decoder[UpdateImageMetaInformation] = deriveDecoder +object UpdateImageMetaInformationDTO { + implicit val encoder: Encoder[UpdateImageMetaInformationDTO] = + UpdateOrDelete.filterMarkers(deriveEncoder[UpdateImageMetaInformationDTO]) + implicit val decoder: Decoder[UpdateImageMetaInformationDTO] = deriveDecoder } diff --git a/image-api/src/main/scala/no/ndla/imageapi/model/api/ValidationError.scala b/image-api/src/main/scala/no/ndla/imageapi/model/api/ValidationError.scala deleted file mode 100644 index 8909fad835..0000000000 --- a/image-api/src/main/scala/no/ndla/imageapi/model/api/ValidationError.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Part of NDLA article_api - * Copyright (C) 2017 NDLA - * - * See LICENSE - * - */ - -package no.ndla.imageapi.model.api - -import no.ndla.common.errors.ValidationMessage -import sttp.tapir.Schema.annotations.description - -import java.time.LocalDateTime - -@description("Information about validation errors") -case class ValidationError( - @description("Code stating the type of error") code: String, - @description("Description of the error") description: String = "Validation error", - @description("List of validation messages") messages: Seq[ValidationMessage], - @description("When the error occurred") occurredAt: LocalDateTime = LocalDateTime.now() -) diff --git a/image-api/src/main/scala/no/ndla/imageapi/service/ConverterService.scala b/image-api/src/main/scala/no/ndla/imageapi/service/ConverterService.scala index 8b159dccda..8083b20b57 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/service/ConverterService.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/service/ConverterService.scala @@ -38,12 +38,12 @@ trait ConverterService { class ConverterService extends StrictLogging { import props.DefaultLanguage - def asApiAuthor(domainAuthor: commonDomain.Author): commonApi.Author = { - commonApi.Author(domainAuthor.`type`, domainAuthor.name) + def asApiAuthor(domainAuthor: commonDomain.Author): commonApi.AuthorDTO = { + commonApi.AuthorDTO(domainAuthor.`type`, domainAuthor.name) } - def asApiCopyright(domainCopyright: commonDomain.article.Copyright): commonApi.Copyright = { - commonApi.Copyright( + def asApiCopyright(domainCopyright: commonDomain.article.Copyright): commonApi.CopyrightDTO = { + commonApi.CopyrightDTO( asApiLicense(domainCopyright.license), domainCopyright.origin, domainCopyright.creators.map(asApiAuthor), @@ -55,19 +55,19 @@ trait ConverterService { ) } - def asApiImage(domainImage: ImageFileData, baseUrl: Option[String] = None): api.Image = { - api.Image(baseUrl.getOrElse("") + domainImage.fileName, domainImage.size, domainImage.contentType) + def asApiImage(domainImage: ImageFileData, baseUrl: Option[String] = None): api.ImageDTO = { + api.ImageDTO(baseUrl.getOrElse("") + domainImage.fileName, domainImage.size, domainImage.contentType) } - def asApiImageAltText(domainImageAltText: domain.ImageAltText): api.ImageAltText = { - api.ImageAltText(domainImageAltText.alttext, domainImageAltText.language) + def asApiImageAltText(domainImageAltText: domain.ImageAltText): api.ImageAltTextDTO = { + api.ImageAltTextDTO(domainImageAltText.alttext, domainImageAltText.language) } def asApiImageMetaInformationWithApplicationUrlV2( domainImageMetaInformation: ImageMetaInformation, language: Option[String], user: Option[TokenUser] - ): Try[api.ImageMetaInformationV2] = { + ): Try[api.ImageMetaInformationV2DTO] = { asImageMetaInformationV2( domainImageMetaInformation, language, @@ -81,7 +81,7 @@ trait ConverterService { domainImageMetaInformation: ImageMetaInformation, language: Option[String], user: Option[TokenUser] - ): Try[api.ImageMetaInformationV2] = { + ): Try[api.ImageMetaInformationV2DTO] = { asImageMetaInformationV2( domainImageMetaInformation, language, @@ -95,21 +95,21 @@ trait ConverterService { imageMeta: ImageMetaInformation, language: Option[String], user: Option[TokenUser] - ): Try[api.ImageMetaInformationV3] = { + ): Try[api.ImageMetaInformationV3DTO] = { val metaUrl = props.ImageApiV3UrlBase + imageMeta.id.get val rawPath = props.RawImageUrlBase val title = findByLanguageOrBestEffort(imageMeta.titles, language) .map(asApiImageTitle) - .getOrElse(api.ImageTitle("", DefaultLanguage)) + .getOrElse(api.ImageTitleDTO("", DefaultLanguage)) val alttext = findByLanguageOrBestEffort(imageMeta.alttexts, language) .map(asApiImageAltText) - .getOrElse(api.ImageAltText("", DefaultLanguage)) + .getOrElse(api.ImageAltTextDTO("", DefaultLanguage)) val tags = findByLanguageOrBestEffort(imageMeta.tags, language) .map(asApiImageTag) - .getOrElse(api.ImageTag(Seq(), DefaultLanguage)) + .getOrElse(api.ImageTagDTO(Seq(), DefaultLanguage)) val caption = findByLanguageOrBestEffort(imageMeta.captions, language) .map(asApiCaption) - .getOrElse(api.ImageCaption("", DefaultLanguage)) + .getOrElse(api.ImageCaptionDTO("", DefaultLanguage)) getImageFromMeta(imageMeta, language).flatMap(image => { val apiUrl = asApiUrl(image.fileName, rawPath.some) @@ -119,7 +119,7 @@ trait ConverterService { Success( api - .ImageMetaInformationV3( + .ImageMetaInformationV3DTO( id = imageMeta.id.get.toString, metaUrl = metaUrl, title = title, @@ -138,12 +138,12 @@ trait ConverterService { }) } - private def asApiImageFile(image: ImageFileData, url: String): api.ImageFile = { + private def asApiImageFile(image: ImageFileData, url: String): api.ImageFileDTO = { val dimensions = image.dimensions.map { case domain.ImageDimensions(width, height) => - api.ImageDimensions(width, height) + api.ImageDimensionsDTO(width, height) } - api.ImageFile( + api.ImageFileDTO( fileName = image.fileName, size = image.size, contentType = image.contentType, @@ -153,8 +153,8 @@ trait ConverterService { ) } - private def asApiEditorNotes(notes: Seq[domain.EditorNote]): Seq[api.EditorNote] = { - notes.map(n => api.EditorNote(n.timeStamp, n.updatedBy, n.note)) + private def asApiEditorNotes(notes: Seq[domain.EditorNote]): Seq[api.EditorNoteDTO] = { + notes.map(n => api.EditorNoteDTO(n.timeStamp, n.updatedBy, n.note)) } private def getImageFromMeta(meta: ImageMetaInformation, language: Option[String]): Try[ImageFileData] = { @@ -170,29 +170,29 @@ trait ConverterService { baseUrl: String, rawBaseUrl: Option[String], user: Option[TokenUser] - ): Try[api.ImageMetaInformationV2] = { + ): Try[api.ImageMetaInformationV2DTO] = { val title = findByLanguageOrBestEffort(imageMeta.titles, language) .map(asApiImageTitle) - .getOrElse(api.ImageTitle("", DefaultLanguage)) + .getOrElse(api.ImageTitleDTO("", DefaultLanguage)) val alttext = findByLanguageOrBestEffort(imageMeta.alttexts, language) .map(asApiImageAltText) - .getOrElse(api.ImageAltText("", DefaultLanguage)) + .getOrElse(api.ImageAltTextDTO("", DefaultLanguage)) val tags = findByLanguageOrBestEffort(imageMeta.tags, language) .map(asApiImageTag) - .getOrElse(api.ImageTag(Seq(), DefaultLanguage)) + .getOrElse(api.ImageTagDTO(Seq(), DefaultLanguage)) val caption = findByLanguageOrBestEffort(imageMeta.captions, language) .map(asApiCaption) - .getOrElse(api.ImageCaption("", DefaultLanguage)) + .getOrElse(api.ImageCaptionDTO("", DefaultLanguage)) getImageFromMeta(imageMeta, language).flatMap(image => { val apiUrl = asApiUrl(image.fileName, rawBaseUrl) val editorNotes = Option.when(user.hasPermission(IMAGE_API_WRITE))(asApiEditorNotes(imageMeta.editorNotes)) - val imageDimensions = image.dimensions.map(d => api.ImageDimensions(d.width, d.height)) + val imageDimensions = image.dimensions.map(d => api.ImageDimensionsDTO(d.width, d.height)) val supportedLanguages = getSupportedLanguages(imageMeta) Success( api - .ImageMetaInformationV2( + .ImageMetaInformationV2DTO( id = imageMeta.id.get.toString, metaUrl = baseUrl + imageMeta.id.get, title = title, @@ -214,21 +214,21 @@ trait ConverterService { }) } - def asApiImageTag(domainImageTag: commonDomain.Tag): api.ImageTag = { - api.ImageTag(domainImageTag.tags, domainImageTag.language) + def asApiImageTag(domainImageTag: commonDomain.Tag): api.ImageTagDTO = { + api.ImageTagDTO(domainImageTag.tags, domainImageTag.language) } - def asApiCaption(domainImageCaption: domain.ImageCaption): api.ImageCaption = - api.ImageCaption(domainImageCaption.caption, domainImageCaption.language) + def asApiCaption(domainImageCaption: domain.ImageCaption): api.ImageCaptionDTO = + api.ImageCaptionDTO(domainImageCaption.caption, domainImageCaption.language) - def asApiImageTitle(domainImageTitle: domain.ImageTitle): api.ImageTitle = { - api.ImageTitle(domainImageTitle.title, domainImageTitle.language) + def asApiImageTitle(domainImageTitle: domain.ImageTitle): api.ImageTitleDTO = { + api.ImageTitleDTO(domainImageTitle.title, domainImageTitle.language) } - def asApiLicense(license: String): commonApi.License = { + def asApiLicense(license: String): commonApi.LicenseDTO = { getLicense(license) - .map(l => commonApi.License(l.license.toString, Some(l.description), l.url)) - .getOrElse(commonApi.License("unknown", None, None)) + .map(l => commonApi.LicenseDTO(l.license.toString, Some(l.description), l.url)) + .getOrElse(commonApi.LicenseDTO("unknown", None, None)) } def asApiUrl(url: String, baseUrl: Option[String] = None): String = { @@ -254,7 +254,7 @@ trait ConverterService { } def asDomainImageMetaInformationV2( - imageMeta: api.NewImageMetaInformationV2, + imageMeta: api.NewImageMetaInformationV2DTO, user: TokenUser ): Try[ImageMetaInformation] = { val modelReleasedStatus = imageMeta.modelReleased match { @@ -291,7 +291,7 @@ trait ConverterService { domain.ImageAltText(alt, language) } - def toDomainCopyright(copyright: commonApi.Copyright): commonDomain.article.Copyright = { + def toDomainCopyright(copyright: commonApi.CopyrightDTO): commonDomain.article.Copyright = { commonDomain.article.Copyright( copyright.license.license, copyright.origin, diff --git a/image-api/src/main/scala/no/ndla/imageapi/service/ReadService.scala b/image-api/src/main/scala/no/ndla/imageapi/service/ReadService.scala index dc4e8e34c0..4b9135c14a 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/service/ReadService.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/service/ReadService.scala @@ -11,7 +11,7 @@ package no.ndla.imageapi.service import com.typesafe.scalalogging.StrictLogging import io.lemonlabs.uri.UrlPath import io.lemonlabs.uri.typesafe.dsl._ -import no.ndla.imageapi.model.api.{ImageMetaDomainDump, ImageMetaInformationV2, ImageMetaInformationV3} +import no.ndla.imageapi.model.api.{ImageMetaDomainDumpDTO, ImageMetaInformationV2DTO, ImageMetaInformationV3DTO} import no.ndla.imageapi.model.domain.{ImageFileData, ImageMetaInformation, Sort} import no.ndla.imageapi.model.{ImageConversionException, ImageNotFoundException, InvalidUrlException, api} import no.ndla.imageapi.repository.ImageRepository @@ -39,13 +39,19 @@ trait ReadService { imageId: Long, language: Option[String], user: Option[TokenUser] - ): Try[Option[ImageMetaInformationV3]] = { + ): Try[Option[ImageMetaInformationV3DTO]] = { imageRepository .withId(imageId) .traverse(image => converterService.asApiImageMetaInformationV3(image, language, user)) } - def getAllTags(input: String, pageSize: Int, page: Int, language: String, sort: Sort): Try[api.TagsSearchResult] = { + def getAllTags( + input: String, + pageSize: Int, + page: Int, + language: String, + sort: Sort + ): Try[api.TagsSearchResultDTO] = { val result = tagSearchService.matchingQuery( query = input, searchLanguage = language, @@ -57,7 +63,11 @@ trait ReadService { result.map(searchConverterService.tagSearchResultAsApiResult) } - def withId(imageId: Long, language: Option[String], user: Option[TokenUser]): Try[Option[ImageMetaInformationV2]] = + def withId( + imageId: Long, + language: Option[String], + user: Option[TokenUser] + ): Try[Option[ImageMetaInformationV2DTO]] = imageRepository .withId(imageId) .traverse(image => converterService.asApiImageMetaInformationWithApplicationUrlV2(image, language, user)) @@ -66,7 +76,7 @@ trait ReadService { ids: List[Long], language: Option[String], user: Option[TokenUser] - ): Try[List[ImageMetaInformationV3]] = { + ): Try[List[ImageMetaInformationV3DTO]] = { if (ids.isEmpty) Failure(ValidationException("ids", "Query parameter 'ids' is missing")) else imageRepository @@ -132,11 +142,11 @@ trait ReadService { else Failure(new InvalidUrlException("Could not extract id or path from url.")) } - def getMetaImageDomainDump(pageNo: Int, pageSize: Int): ImageMetaDomainDump = { + def getMetaImageDomainDump(pageNo: Int, pageSize: Int): ImageMetaDomainDumpDTO = { val (safePageNo, safePageSize) = (math.max(pageNo, 1), math.max(pageSize, 0)) val results = imageRepository.getByPage(safePageSize, (safePageNo - 1) * safePageSize) - ImageMetaDomainDump(imageRepository.imageCount, pageNo, pageSize, results) + ImageMetaDomainDumpDTO(imageRepository.imageCount, pageNo, pageSize, results) } def getImageFileName(imageId: Long, language: Option[String]): Try[Option[String]] = { diff --git a/image-api/src/main/scala/no/ndla/imageapi/service/WriteService.scala b/image-api/src/main/scala/no/ndla/imageapi/service/WriteService.scala index 1434c089bc..624ed19da6 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/service/WriteService.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/service/WriteService.scala @@ -19,10 +19,10 @@ import no.ndla.common.model.{NDLADate, domain => common} import no.ndla.imageapi.Props import no.ndla.imageapi.model._ import no.ndla.imageapi.model.api.{ - ImageMetaInformationV2, - ImageMetaInformationV3, - NewImageMetaInformationV2, - UpdateImageMetaInformation + ImageMetaInformationV2DTO, + ImageMetaInformationV3DTO, + NewImageMetaInformationV2DTO, + UpdateImageMetaInformationDTO } import no.ndla.imageapi.model.domain._ import no.ndla.imageapi.repository.ImageRepository @@ -54,7 +54,7 @@ trait WriteService { imageId: Long, language: String, user: TokenUser - ): Try[Option[ImageMetaInformationV2]] = { + ): Try[Option[ImageMetaInformationV2DTO]] = { deleteImageLanguageVersion(imageId, language, user).flatMap { case Some(updated) => converterService.asApiImageMetaInformationWithDomainUrlV2(updated, None, user.some).map(_.some) @@ -66,7 +66,7 @@ trait WriteService { imageId: Long, language: String, user: TokenUser - ): Try[Option[ImageMetaInformationV3]] = { + ): Try[Option[ImageMetaInformationV3DTO]] = { deleteImageLanguageVersion(imageId, language, user).flatMap { case Some(updated) => converterService.asApiImageMetaInformationV3(updated, None, user.some).map(_.some) case None => Success(None) @@ -143,7 +143,7 @@ trait WriteService { } def storeNewImage( - newImage: NewImageMetaInformationV2, + newImage: NewImageMetaInformationV2DTO, file: UploadedFile, user: TokenUser ): Try[ImageMetaInformation] = { @@ -212,7 +212,7 @@ trait WriteService { private[service] def mergeImages( existing: ImageMetaInformation, - toMerge: UpdateImageMetaInformation, + toMerge: UpdateImageMetaInformationDTO, user: TokenUser ): Try[ImageMetaInformation] = { val now = clock.now() @@ -341,7 +341,7 @@ trait WriteService { private[service] def updateImageAndFile( imageId: Long, - updateMeta: UpdateImageMetaInformation, + updateMeta: UpdateImageMetaInformationDTO, newFile: Option[UploadedFile], user: TokenUser ): Try[domain.ImageMetaInformation] = { @@ -367,10 +367,10 @@ trait WriteService { def updateImage( imageId: Long, - updateMeta: UpdateImageMetaInformation, + updateMeta: UpdateImageMetaInformationDTO, newFile: Option[UploadedFile], user: TokenUser - ): Try[ImageMetaInformationV2] = + ): Try[ImageMetaInformationV2DTO] = for { updated <- updateImageAndFile(imageId, updateMeta, newFile, user) converted <- converterService.asApiImageMetaInformationWithDomainUrlV2( @@ -382,10 +382,10 @@ trait WriteService { def updateImageV3( imageId: Long, - updateMeta: UpdateImageMetaInformation, + updateMeta: UpdateImageMetaInformationDTO, newFile: Option[UploadedFile], user: TokenUser - ): Try[ImageMetaInformationV3] = + ): Try[ImageMetaInformationV3DTO] = for { updated <- updateImageAndFile(imageId, updateMeta, newFile, user) converted <- converterService.asApiImageMetaInformationV3(updated, updateMeta.language.some, user.some) diff --git a/image-api/src/main/scala/no/ndla/imageapi/service/search/ImageSearchService.scala b/image-api/src/main/scala/no/ndla/imageapi/service/search/ImageSearchService.scala index d73a820ac8..0a3fcf2df3 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/service/search/ImageSearchService.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/service/search/ImageSearchService.scala @@ -16,7 +16,7 @@ import com.typesafe.scalalogging.StrictLogging import no.ndla.common.CirceUtil import no.ndla.imageapi.Props import no.ndla.imageapi.model.ResultWindowTooLargeException -import no.ndla.imageapi.model.api.{ErrorHandling, ImageMetaSummary} +import no.ndla.imageapi.model.api.{ErrorHandling, ImageMetaSummaryDTO} import no.ndla.imageapi.model.domain.{SearchResult, SearchSettings, Sort} import no.ndla.imageapi.model.search.SearchableImage import no.ndla.common.implicits.* @@ -78,7 +78,7 @@ trait ImageSearchService { private def convertToV2( result: Try[SearchResult[(SearchableImage, MatchedLanguage)]], user: Option[TokenUser] - ): Try[SearchResult[ImageMetaSummary]] = + ): Try[SearchResult[ImageMetaSummaryDTO]] = for { searchResult <- result summaries <- searchResult.results.traverse { case (image, language) => @@ -87,13 +87,13 @@ trait ImageSearchService { convertedResult = searchResult.copy(results = summaries) } yield convertedResult - def scrollV2(scrollId: String, language: String, user: Option[TokenUser]): Try[SearchResult[ImageMetaSummary]] = + def scrollV2(scrollId: String, language: String, user: Option[TokenUser]): Try[SearchResult[ImageMetaSummaryDTO]] = convertToV2( scroll(scrollId, language), user ) - def matchingQuery(settings: SearchSettings, user: Option[TokenUser]): Try[SearchResult[ImageMetaSummary]] = + def matchingQuery(settings: SearchSettings, user: Option[TokenUser]): Try[SearchResult[ImageMetaSummaryDTO]] = convertToV2( matchingQueryV3(settings, user), user diff --git a/image-api/src/main/scala/no/ndla/imageapi/service/search/SearchConverterService.scala b/image-api/src/main/scala/no/ndla/imageapi/service/search/SearchConverterService.scala index 943a913789..0b88159016 100644 --- a/image-api/src/main/scala/no/ndla/imageapi/service/search/SearchConverterService.scala +++ b/image-api/src/main/scala/no/ndla/imageapi/service/search/SearchConverterService.scala @@ -11,7 +11,7 @@ import io.lemonlabs.uri.Uri.parse import com.sksamuel.elastic4s.requests.searches.SearchHit import com.typesafe.scalalogging.StrictLogging import no.ndla.imageapi.Props -import no.ndla.imageapi.model.api.{ImageAltText, ImageCaption, ImageMetaSummary, ImageTitle} +import no.ndla.imageapi.model.api.{ImageAltTextDTO, ImageCaptionDTO, ImageMetaSummaryDTO, ImageTitleDTO} import no.ndla.imageapi.model.domain.{ImageFileData, ImageMetaInformation, SearchResult} import no.ndla.imageapi.model.{ImageConversionException, api, domain} import no.ndla.imageapi.model.search.{SearchableImage, SearchableImageFile, SearchableTag} @@ -104,20 +104,20 @@ trait SearchConverterService { searchableImage: SearchableImage, language: String, user: Option[TokenUser] - ): Try[ImageMetaSummary] = { + ): Try[ImageMetaSummaryDTO] = { val apiToRawRegex = "/v\\d+/images/".r val title = Language .findByLanguageOrBestEffort(searchableImage.titles.languageValues, Some(language)) - .map(res => ImageTitle(res.value, res.language)) - .getOrElse(ImageTitle("", props.DefaultLanguage)) + .map(res => ImageTitleDTO(res.value, res.language)) + .getOrElse(ImageTitleDTO("", props.DefaultLanguage)) val altText = Language .findByLanguageOrBestEffort(searchableImage.alttexts.languageValues, Some(language)) - .map(res => ImageAltText(res.value, res.language)) - .getOrElse(ImageAltText("", props.DefaultLanguage)) + .map(res => ImageAltTextDTO(res.value, res.language)) + .getOrElse(ImageAltTextDTO("", props.DefaultLanguage)) val caption = Language .findByLanguageOrBestEffort(searchableImage.captions.languageValues, Some(language)) - .map(res => ImageCaption(res.value, res.language)) - .getOrElse(ImageCaption("", props.DefaultLanguage)) + .map(res => ImageCaptionDTO(res.value, res.language)) + .getOrElse(ImageCaptionDTO("", props.DefaultLanguage)) val supportedLanguages = Language.getSupportedLanguages( searchableImage.titles.languageValues, @@ -129,7 +129,7 @@ trait SearchConverterService { val editorNotes = Option.when(user.hasPermission(IMAGE_API_WRITE))(searchableImage.editorNotes) getSearchableImageFileFromSearchableImage(searchableImage, language.some).map(imageFile => { - ImageMetaSummary( + ImageMetaSummaryDTO( id = searchableImage.id.toString, title = title, contributors = searchableImage.contributors, @@ -145,7 +145,7 @@ trait SearchConverterService { fileSize = imageFile.fileSize, contentType = imageFile.contentType, imageDimensions = imageFile.dimensions.map { case domain.ImageDimensions(width, height) => - api.ImageDimensions(width, height) + api.ImageDimensionsDTO(width, height) } ) }) @@ -178,8 +178,8 @@ trait SearchConverterService { } } - def asApiSearchResult(searchResult: domain.SearchResult[ImageMetaSummary]): api.SearchResult = - api.SearchResult( + def asApiSearchResult(searchResult: domain.SearchResult[ImageMetaSummaryDTO]): api.SearchResultDTO = + api.SearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, @@ -187,8 +187,8 @@ trait SearchConverterService { searchResult.results ) - def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResult = - api.TagsSearchResult( + def tagSearchResultAsApiResult(searchResult: SearchResult[String]): api.TagsSearchResultDTO = + api.TagsSearchResultDTO( searchResult.totalCount, searchResult.page.getOrElse(1), searchResult.pageSize, @@ -200,11 +200,11 @@ trait SearchConverterService { searchResult: domain.SearchResult[(SearchableImage, MatchedLanguage)], language: String, user: Option[TokenUser] - ): Try[api.SearchResultV3] = { + ): Try[api.SearchResultV3DTO] = { searchResult.results .traverse(r => converterService.asApiImageMetaInformationV3(r._1.domainObject, language.some, user)) .map(results => - api.SearchResultV3( + api.SearchResultV3DTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, diff --git a/image-api/src/test/scala/no/ndla/imageapi/TestData.scala b/image-api/src/test/scala/no/ndla/imageapi/TestData.scala index 23f063b181..0b4bf9f6a3 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/TestData.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/TestData.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.domain.article.Copyright import no.ndla.common.model.domain.{Author, Tag} import no.ndla.common.model.{api => commonApi} import no.ndla.imageapi.model.api -import no.ndla.imageapi.model.api.ImageMetaInformationV2 +import no.ndla.imageapi.model.api.ImageMetaInformationV2DTO import no.ndla.imageapi.model.domain._ import no.ndla.mapping @@ -66,30 +66,30 @@ trait TestData { editorNotes = Seq.empty ) - val apiElg: ImageMetaInformationV2 = api.ImageMetaInformationV2( + val apiElg: ImageMetaInformationV2DTO = api.ImageMetaInformationV2DTO( "1", "Elg.jpg", - api.ImageTitle("Elg i busk", "nb"), - api.ImageAltText("Elg i busk", "nb"), + api.ImageTitleDTO("Elg i busk", "nb"), + api.ImageAltTextDTO("Elg i busk", "nb"), "Elg.jpg", 2865539, "image/jpeg", - commonApi.Copyright( - commonApi.License( + commonApi.CopyrightDTO( + commonApi.LicenseDTO( "by-nc-sa", Some("Creative Commons Attribution-NonCommercial-ShareAlike 2.0 Generic"), Some("https://creativecommons.org/licenses/by-nc-sa/2.0/") ), Some("http://www.scanpix.no"), - List(commonApi.Author("Fotograf", "Test Testesen")), + List(commonApi.AuthorDTO("Fotograf", "Test Testesen")), List(), List(), None, None, false ), - api.ImageTag(List("rovdyr", "elg"), "nb"), - api.ImageCaption("Elg i busk", "nb"), + api.ImageTagDTO(List("rovdyr", "elg"), "nb"), + api.ImageCaptionDTO("Elg i busk", "nb"), List("nb"), updated(), "ndla123", @@ -98,30 +98,30 @@ trait TestData { None ) - val apiBjorn: ImageMetaInformationV2 = ImageMetaInformationV2( + val apiBjorn: ImageMetaInformationV2DTO = ImageMetaInformationV2DTO( id = "2", metaUrl = "", - title = api.ImageTitle("Bjørn i busk", "nb"), - alttext = api.ImageAltText("Elg i busk", "nb"), + title = api.ImageTitleDTO("Bjørn i busk", "nb"), + alttext = api.ImageAltTextDTO("Elg i busk", "nb"), imageUrl = "", size = 141134, contentType = "image/jpeg", - copyright = commonApi.Copyright( - commonApi.License( + copyright = commonApi.CopyrightDTO( + commonApi.LicenseDTO( "by-nc-sa", Some("Creative Commons Attribution-NonCommercial-ShareAlike 2.0 Generic"), Some("https://creativecommons.org/licenses/by-nc-sa/2.0/") ), Some("http://www.scanpix.no"), - List(commonApi.Author("Fotograf", "Test Testesen")), + List(commonApi.AuthorDTO("Fotograf", "Test Testesen")), List(), List(), None, None, false ), - tags = api.ImageTag(List("rovdyr", "bjørn"), "nb"), - caption = api.ImageCaption("Bjørn i busk", "nb"), + tags = api.ImageTagDTO(List("rovdyr", "bjørn"), "nb"), + caption = api.ImageCaptionDTO("Bjørn i busk", "nb"), supportedLanguages = Seq("nb"), created = updated(), createdBy = "ndla124", diff --git a/image-api/src/test/scala/no/ndla/imageapi/controller/ImageControllerV2Test.scala b/image-api/src/test/scala/no/ndla/imageapi/controller/ImageControllerV2Test.scala index 22382080ef..efcfc7aa16 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/controller/ImageControllerV2Test.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/controller/ImageControllerV2Test.scala @@ -13,10 +13,10 @@ import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.Tag import no.ndla.common.model.domain.article.Copyright import no.ndla.imageapi.model.api.{ - ImageMetaSummary, - NewImageMetaInformationV2, - SearchResult, - UpdateImageMetaInformation + ImageMetaSummaryDTO, + NewImageMetaInformationV2DTO, + SearchResultDTO, + UpdateImageMetaInformationDTO } import no.ndla.imageapi.model.domain.* import no.ndla.imageapi.model.{ImageNotFoundException, api, domain} @@ -93,8 +93,8 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon test("That GET / returns body and 200") { val expectedBody = """{"totalCount":0,"page":1,"pageSize":10,"language":"nb","results":[]}""" - val domainSearchResult = domain.SearchResult[ImageMetaSummary](0, Some(1), 10, "nb", List(), None) - val apiSearchResult = SearchResult(0, Some(1), 10, "nb", List()) + val domainSearchResult = domain.SearchResult[ImageMetaSummaryDTO](0, Some(1), 10, "nb", List(), None) + val apiSearchResult = SearchResultDTO(0, Some(1), 10, "nb", List()) when(imageSearchService.matchingQuery(any[SearchSettings], any)).thenReturn(Success(domainSearchResult)) when(searchConverterService.asApiSearchResult(domainSearchResult)).thenReturn(apiSearchResult) val res = simpleHttpClient.send( @@ -116,12 +116,12 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon .withSecond(56) .withNano(0) - val imageSummary = api.ImageMetaSummary( + val imageSummary = api.ImageMetaSummaryDTO( "4", - api.ImageTitle("Tittel", "nb"), + api.ImageTitleDTO("Tittel", "nb"), Seq("Jason Bourne", "Ben Affleck"), - api.ImageAltText("AltText", "nb"), - api.ImageCaption("Caption", "nb"), + api.ImageAltTextDTO("AltText", "nb"), + api.ImageCaptionDTO("Caption", "nb"), "http://image-api.ndla-local/image-api/raw/4", "http://image-api.ndla-local/image-api/v2/images/4", "by-sa", @@ -136,7 +136,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon val expectedBody = s"""{"totalCount":1,"page":1,"pageSize":10,"language":"nb","results":[{"id":"4","title":{"title":"Tittel","language":"nb"},"contributors":["Jason Bourne","Ben Affleck"],"altText":{"alttext":"AltText","language":"nb"},"caption":{"caption":"Caption","language":"nb"},"previewUrl":"http://image-api.ndla-local/image-api/raw/4","metaUrl":"http://image-api.ndla-local/image-api/v2/images/4","license":"by-sa","supportedLanguages":["nb"],"modelRelease":"yes","lastUpdated":"${date.asString}","fileSize":123,"contentType":"image/jpg"}]}""" val domainSearchResult = domain.SearchResult(1, Some(1), 10, "nb", List(imageSummary), None) - val apiSearchResult = api.SearchResult(1, Some(1), 10, "nb", List(imageSummary)) + val apiSearchResult = api.SearchResultDTO(1, Some(1), 10, "nb", List(imageSummary)) when(imageSearchService.matchingQuery(any[SearchSettings], any)).thenReturn(Success(domainSearchResult)) when(searchConverterService.asApiSearchResult(domainSearchResult)).thenReturn(apiSearchResult) val res = simpleHttpClient.send( @@ -158,14 +158,14 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon val testUrl = "http://test.test/1" val expectedBody = s"""{"id":"1","metaUrl":"$testUrl","title":{"title":"Elg i busk","language":"nb"},"created":"2017-04-01T12:15:32Z","createdBy":"ndla124","modelRelease":"yes","alttext":{"alttext":"Elg i busk","language":"nb"},"imageUrl":"$testUrl","size":2865539,"contentType":"image/jpeg","copyright":{"license":{"license":"CC-BY-NC-SA-4.0","description":"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"origin":"http://www.scanpix.no","creators":[{"type":"Fotograf","name":"Test Testesen"}],"processors":[{"type":"Redaksjonelt","name":"Kåre Knegg"}],"rightsholders":[{"type":"Leverandør","name":"Leverans Leveransensen"}],"processed":false},"tags":{"tags":["rovdyr","elg"],"language":"nb"},"caption":{"caption":"Elg i busk","language":"nb"},"supportedLanguages":["nb"]}""" - val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](expectedBody) + val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](expectedBody) when(readService.withId(1, None, None)).thenReturn(Success(Option(expectedObject))) val res = simpleHttpClient.send( quickRequest.get(uri"http://localhost:$serverPort/image-api/v2/images/1") ) res.code.code should be(200) - val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](res.body) + val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](res.body) result.copy(imageUrl = testUrl, metaUrl = testUrl) should equal(expectedObject) } @@ -173,7 +173,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon val testUrl = "http://test.test/1" val expectedBody = s"""{"id":"1","metaUrl":"$testUrl","title":{"title":"Elg i busk","language":"nb"},"created":"2017-04-01T12:15:32Z","createdBy":"ndla124","modelRelease":"yes","alttext":{"alttext":"Elg i busk","language":"nb"},"imageUrl":"$testUrl","size":2865539,"contentType":"image/jpeg","copyright":{"license":{"license":"gnu","description":"gnuggert","url":"https://gnuli/"},"agreementId": 1,"origin":"http://www.scanpix.no","creators":[{"type":"Forfatter","name":"Knutulf Knagsen"}],"processors":[{"type":"Redaksjonelt","name":"Kåre Knegg"}],"rightsholders":[],"processed":false},"tags":{"tags":["rovdyr","elg"],"language":"nb"},"caption":{"caption":"Elg i busk","language":"nb"},"supportedLanguages":["nb"]}""" - val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](expectedBody) + val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](expectedBody) when(readService.withId(1, None, None)).thenReturn(Success(Option(expectedObject))) @@ -181,7 +181,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon quickRequest.get(uri"http://localhost:$serverPort/image-api/v2/images/1") ) res.code.code should be(200) - val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](res.body) + val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](res.body) result.copy(imageUrl = testUrl, metaUrl = testUrl) should equal(expectedObject) } @@ -189,7 +189,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon val testUrl = "http://test.test/1" val expectedBody = s"""{"id":"1","metaUrl":"$testUrl","title":{"title":"Elg i busk","language":"nb"},"created":"2017-04-01T12:15:32Z","createdBy":"ndla124","modelRelease":"yes","alttext":{"alttext":"Elg i busk","language":"nb"},"imageUrl":"$testUrl","size":2865539,"contentType":"image/jpeg","copyright":{"license":{"license":"CC-BY-NC-SA-4.0","description":"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"}, "agreementId":1, "origin":"http://www.scanpix.no","creators":[{"type":"Fotograf","name":"Test Testesen"}],"processors":[{"type":"Redaksjonelt","name":"Kåre Knegg"}],"rightsholders":[{"type":"Leverandør","name":"Leverans Leveransensen"}],"processed":false},"tags":{"tags":["rovdyr","elg"],"language":"nb"},"caption":{"caption":"Elg i busk","language":"nb"},"supportedLanguages":["nb"]}""" - val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](expectedBody) + val expectedObject = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](expectedBody) when(readService.withId(1, None, None)).thenReturn(Success(Option(expectedObject))) @@ -197,7 +197,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon quickRequest.get(uri"http://localhost:$serverPort/image-api/v2/images/1") ) res.code.code should equal(200) - val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](res.body) + val result = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](res.body) result.copy(imageUrl = testUrl, metaUrl = testUrl) should equal(expectedObject) } @@ -256,7 +256,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon editorNotes = Seq.empty ) - when(writeService.storeNewImage(any[NewImageMetaInformationV2], any, any)) + when(writeService.storeNewImage(any[NewImageMetaInformationV2DTO], any, any)) .thenReturn(Success(sampleImageMeta)) val res = simpleHttpClient.send( @@ -315,7 +315,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon test("That POST / returns 500 if an unexpected error occurs") { reset(writeService) val exceptionMock = mock[RuntimeException](withSettings.strictness(Strictness.LENIENT)) - when(writeService.storeNewImage(any[NewImageMetaInformationV2], any, any)) + when(writeService.storeNewImage(any[NewImageMetaInformationV2DTO], any, any)) .thenReturn(Failure(exceptionMock)) val res = simpleHttpClient.send( @@ -332,7 +332,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon test("That PATCH / returns 200 when everything went well") { reset(writeService) - when(writeService.updateImage(any[Long], any[UpdateImageMetaInformation], any, any)) + when(writeService.updateImage(any[Long], any[UpdateImageMetaInformationDTO], any, any)) .thenReturn(Try(TestData.apiElg)) val res = simpleHttpClient.send( quickRequest @@ -347,7 +347,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon test("That PATCH / returns 404 when image doesn't exist") { reset(writeService) - when(writeService.updateImage(any[Long], any[UpdateImageMetaInformation], any, any)) + when(writeService.updateImage(any[Long], any[UpdateImageMetaInformationDTO], any, any)) .thenThrow(new ImageNotFoundException(s"Image with id 1 not found")) val res = simpleHttpClient.send( quickRequest @@ -375,7 +375,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon test("That scrollId is in header, and not in body") { val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[ImageMetaSummary]( + val searchResponse = domain.SearchResult[ImageMetaSummaryDTO]( 0, Some(1), 10, @@ -396,7 +396,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon reset(imageSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[ImageMetaSummary]( + val searchResponse = domain.SearchResult[ImageMetaSummaryDTO]( 0, Some(1), 10, @@ -420,7 +420,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon reset(imageSearchService) val scrollId = "DnF1ZXJ5VGhlbkZldGNoCgAAAAAAAAC1Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAthYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALcWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC4Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuRYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAALsWLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC9Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFEAAAAAAAAAuhYtY2VPYWFvRFQ5aWNSbzRFYVZSTEhRAAAAAAAAAL4WLWNlT2Fhb0RUOWljUm80RWFWUkxIUQAAAAAAAAC8Fi1jZU9hYW9EVDlpY1JvNEVhVlJMSFE=" - val searchResponse = domain.SearchResult[ImageMetaSummary]( + val searchResponse = domain.SearchResult[ImageMetaSummaryDTO]( 0, Some(1), 10, @@ -451,7 +451,7 @@ class ImageControllerV2Test extends UnitSuite with TestEnvironment with TapirCon sort = Sort.ByTitleAsc ) - val result = domain.SearchResult[api.ImageMetaSummary]( + val result = domain.SearchResult[api.ImageMetaSummaryDTO]( totalCount = 0, page = None, pageSize = 10, diff --git a/image-api/src/test/scala/no/ndla/imageapi/controller/InternControllerTest.scala b/image-api/src/test/scala/no/ndla/imageapi/controller/InternControllerTest.scala index 71b0b7350e..c88919946d 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/controller/InternControllerTest.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/controller/InternControllerTest.scala @@ -12,7 +12,7 @@ import no.ndla.common.CirceUtil import no.ndla.common.model.domain.article.Copyright import no.ndla.common.model.{NDLADate, api as commonApi} import no.ndla.imageapi.model.api -import no.ndla.imageapi.model.api.{ImageAltText, ImageCaption, ImageTag, ImageTitle} +import no.ndla.imageapi.model.api.{ImageAltTextDTO, ImageCaptionDTO, ImageTagDTO, ImageTitleDTO} import no.ndla.imageapi.model.domain.{ImageFileData, ImageMetaInformation, ModelReleasedStatus} import no.ndla.imageapi.{TestEnvironment, UnitSuite} import no.ndla.mapping.License.{CC_BY, getLicense} @@ -31,16 +31,16 @@ class InternControllerTest extends UnitSuite with TestEnvironment with TapirCont val updated: NDLADate = NDLADate.of(2017, 4, 1, 12, 15, 32) val BySa: LicenseDefinition = getLicense(CC_BY.toString).get - val DefaultApiImageMetaInformation: api.ImageMetaInformationV2 = api.ImageMetaInformationV2( + val DefaultApiImageMetaInformation: api.ImageMetaInformationV2DTO = api.ImageMetaInformationV2DTO( "1", s"${props.ImageApiV2UrlBase}1", - ImageTitle("", "nb"), - ImageAltText("", "nb"), + ImageTitleDTO("", "nb"), + ImageAltTextDTO("", "nb"), s"${props.RawImageUrlBase}/test.jpg", 0, "", - commonApi.Copyright( - commonApi.License(BySa.license.toString, Some(BySa.description), BySa.url), + commonApi.CopyrightDTO( + commonApi.LicenseDTO(BySa.license.toString, Some(BySa.description), BySa.url), None, List(), List(), @@ -49,8 +49,8 @@ class InternControllerTest extends UnitSuite with TestEnvironment with TapirCont None, false ), - ImageTag(Seq.empty, "nb"), - ImageCaption("", "nb"), + ImageTagDTO(Seq.empty, "nb"), + ImageCaptionDTO("", "nb"), Seq("und"), updated, "ndla124", @@ -119,7 +119,7 @@ class InternControllerTest extends UnitSuite with TestEnvironment with TapirCont val res = simpleHttpClient .send(quickRequest.get(uri"http://localhost:$serverPort/intern/extern/123")) res.code.code should be(200) - CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](res.body) should equal(DefaultApiImageMetaInformation) + CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](res.body) should equal(DefaultApiImageMetaInformation) } test("That DELETE /index removes all indexes") { diff --git a/image-api/src/test/scala/no/ndla/imageapi/service/ReadServiceTest.scala b/image-api/src/test/scala/no/ndla/imageapi/service/ReadServiceTest.scala index d53c1d7a8b..164c841970 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/service/ReadServiceTest.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/service/ReadServiceTest.scala @@ -11,7 +11,7 @@ package no.ndla.imageapi.service import no.ndla.common.CirceUtil import no.ndla.common.model.domain.article.Copyright import no.ndla.common.model.domain as common -import no.ndla.imageapi.model.api.ImageMetaInformationV2 +import no.ndla.imageapi.model.api.ImageMetaInformationV2DTO import no.ndla.imageapi.model.domain.{ImageFileData, ImageMetaInformation, ModelReleasedStatus} import no.ndla.imageapi.model.{InvalidUrlException, api, domain} import no.ndla.imageapi.{TestEnvironment, UnitSuite} @@ -52,7 +52,7 @@ class ReadServiceTest extends UnitSuite with TestEnvironment { val expectedBody = s"""{"id":"1","metaUrl":"$testUrl","title":{"title":"Elg i busk","language":"nb"},"created":"$dateString","createdBy":"ndla124","modelRelease":"yes","alttext":{"alttext":"Elg i busk","language":"nb"},"imageUrl":"$testRawUrl","size":2865539,"contentType":"image/jpeg","copyright":{"license":{"license":"CC-BY-NC-SA-4.0","description":"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"}, "agreementId":1, "origin":"http://www.scanpix.no","creators":[{"type":"Fotograf","name":"Test Testesen"}],"processors":[{"type":"Redaksjonelt","name":"Kåre Knegg"}],"rightsholders":[{"type":"Leverandør","name":"Leverans Leveransensen"}],"processed":false},"tags":{"tags":["rovdyr","elg"],"language":"nb"},"caption":{"caption":"Elg i busk","language":"nb"},"supportedLanguages":["nb"]}""" - val expectedObject: ImageMetaInformationV2 = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2](expectedBody) + val expectedObject: ImageMetaInformationV2DTO = CirceUtil.unsafeParseAs[api.ImageMetaInformationV2DTO](expectedBody) val agreementElg = new ImageMetaInformation( id = Some(1), titles = List(domain.ImageTitle("Elg i busk", "nb")), diff --git a/image-api/src/test/scala/no/ndla/imageapi/service/WriteServiceTest.scala b/image-api/src/test/scala/no/ndla/imageapi/service/WriteServiceTest.scala index 72cb2cdb31..fc752e0f72 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/service/WriteServiceTest.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/service/WriteServiceTest.scala @@ -9,7 +9,7 @@ package no.ndla.imageapi.service import no.ndla.common.errors.ValidationException -import no.ndla.common.model.api.{Copyright, License, Missing, UpdateWith} +import no.ndla.common.model.api.{CopyrightDTO, LicenseDTO, Missing, UpdateWith} import no.ndla.common.model.domain.UploadedFile import no.ndla.common.model.{NDLADate, api as commonApi, domain as common} import no.ndla.common.model.domain.article.Copyright as DomainCopyright @@ -33,10 +33,10 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val newFileName = "AbCdeF.mp3" val fileMock1: UploadedFile = mock[UploadedFile] - val newImageMeta: NewImageMetaInformationV2 = NewImageMetaInformationV2( + val newImageMeta: NewImageMetaInformationV2DTO = NewImageMetaInformationV2DTO( "title", Some("alt text"), - Copyright(License("by", None, None), None, Seq.empty, Seq.empty, Seq.empty, None, None, false), + CopyrightDTO(LicenseDTO("by", None, None), None, Seq.empty, Seq.empty, Seq.empty, None, None, false), Seq.empty, "", "en", @@ -291,7 +291,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { 1 ) - val toUpdate = UpdateImageMetaInformation( + val toUpdate = UpdateImageMetaInformationDTO( "en", Some("Title"), UpdateWith("AltText"), @@ -317,7 +317,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val date = NDLADate.now() val user = "ndla124" val existing = TestData.elg.copy(updated = date, updatedBy = user) - val toUpdate = UpdateImageMetaInformation( + val toUpdate = UpdateImageMetaInformationDTO( "nb", Some("Title"), UpdateWith("AltText"), @@ -342,15 +342,15 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { val date = NDLADate.now() val user = "ndla124" val existing = TestData.elg.copy(updated = date, updatedBy = user) - val toUpdate = UpdateImageMetaInformation( + val toUpdate = UpdateImageMetaInformationDTO( "nb", Some("Title"), UpdateWith("AltText"), Some( - Copyright( - License("testLic", Some("License for testing"), None), + CopyrightDTO( + LicenseDTO("testLic", Some("License for testing"), None), Some("test"), - List(commonApi.Author("Opphavsmann", "Testerud")), + List(commonApi.AuthorDTO("Opphavsmann", "Testerud")), List(), List(), None, @@ -415,7 +415,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { updatedBy = user, images = Some(Seq(image)) ) - val toUpdate = UpdateImageMetaInformation( + val toUpdate = UpdateImageMetaInformationDTO( "nn", None, Missing, @@ -544,7 +544,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { reset(imageStorage) val imageId = 100L val coolDate = NDLADate.now() - val upd = UpdateImageMetaInformation( + val upd = UpdateImageMetaInformationDTO( language = "nb", title = Some("new title"), alttext = Missing, @@ -638,7 +638,7 @@ class WriteServiceTest extends UnitSuite with TestEnvironment { reset(imageStorage) val imageId = 100L val coolDate = NDLADate.now() - val upd = UpdateImageMetaInformation( + val upd = UpdateImageMetaInformationDTO( language = "nb", title = Some("new title"), alttext = Missing, diff --git a/image-api/src/test/scala/no/ndla/imageapi/service/search/ImageSearchServiceTest.scala b/image-api/src/test/scala/no/ndla/imageapi/service/search/ImageSearchServiceTest.scala index e3c7171bda..5ff3fd4630 100644 --- a/image-api/src/test/scala/no/ndla/imageapi/service/search/ImageSearchServiceTest.scala +++ b/image-api/src/test/scala/no/ndla/imageapi/service/search/ImageSearchServiceTest.scala @@ -72,8 +72,8 @@ class ImageSearchServiceTest ) val updated: NDLADate = NDLADate.of(2017, 4, 1, 12, 15, 32) - val agreement1Copyright: commonApi.Copyright = commonApi.Copyright( - commonApi.License("gnu", Some("gnustuff"), Some("http://gnugnusen")), + val agreement1Copyright: commonApi.CopyrightDTO = commonApi.CopyrightDTO( + commonApi.LicenseDTO("gnu", Some("gnustuff"), Some("http://gnugnusen")), Some("Simsalabim"), List(), List(), diff --git a/integration-tests/src/test/scala/no/ndla/integrationtests/draftapi/articleapi/ArticleApiClientTest.scala b/integration-tests/src/test/scala/no/ndla/integrationtests/draftapi/articleapi/ArticleApiClientTest.scala index cfa72c9a5f..c24045fcc8 100644 --- a/integration-tests/src/test/scala/no/ndla/integrationtests/draftapi/articleapi/ArticleApiClientTest.scala +++ b/integration-tests/src/test/scala/no/ndla/integrationtests/draftapi/articleapi/ArticleApiClientTest.scala @@ -11,7 +11,7 @@ import no.ndla.articleapi.ArticleApiProperties import no.ndla.common.model.domain.Priority import no.ndla.common.model.domain.draft.Draft import no.ndla.common.model.{NDLADate, domain as common} -import no.ndla.draftapi.model.api.ContentId +import no.ndla.draftapi.model.api.ContentIdDTO import no.ndla.integrationtests.UnitSuite import no.ndla.network.AuthUser import no.ndla.network.tapir.auth.TokenUser @@ -73,7 +73,7 @@ class ArticleApiClientTest super.afterAll() } - val idResponse: ContentId = ContentId(1) + val idResponse: ContentIdDTO = ContentIdDTO(1) override val converterService = new ConverterService val testCopyright: common.draft.DraftCopyright = common.draft.DraftCopyright( @@ -175,7 +175,7 @@ class ArticleApiClientTest test("that deleting an article should return 200") { dataFixer.setupArticles() - val contentId = ContentId(1) + val contentId = ContentIdDTO(1) AuthUser.setHeader(s"Bearer $exampleToken") val articleApiClient = new ArticleApiClient(articleApiBaseUrl) articleApiClient.deleteArticle(1, authUser).get should be(contentId) diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/InternController.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/InternController.scala index c776d09d19..f6340ea1dc 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/InternController.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/InternController.scala @@ -12,7 +12,7 @@ import cats.implicits.catsSyntaxEitherId import no.ndla.common.model.api.CommaSeparatedList.* import no.ndla.common.model.domain.learningpath as commonDomain import no.ndla.learningpathapi.Props -import no.ndla.learningpathapi.model.api.{ErrorHandling, LearningPathDomainDump, LearningPathSummaryV2} +import no.ndla.learningpathapi.model.api.{ErrorHandling, LearningPathDomainDumpDTO, LearningPathSummaryV2DTO} import no.ndla.learningpathapi.repository.LearningPathRepositoryComponent import no.ndla.learningpathapi.service.search.{SearchIndexService, SearchService} import no.ndla.learningpathapi.service.{ReadService, UpdateService} @@ -110,7 +110,7 @@ trait InternController { .in(query[Int]("page").default(1)) .in(query[Int]("page-size").default(250)) .in(query[Boolean]("only-published").default(true)) - .out(jsonBody[LearningPathDomainDump]) + .out(jsonBody[LearningPathDomainDumpDTO]) .serverLogicPure { case (pageNo, pageSize, onlyIncludePublished) => readService.getLearningPathDomainDump(pageNo, pageSize, onlyIncludePublished).asRight } @@ -138,7 +138,7 @@ trait InternController { def containsArticle: ServerEndpoint[Any, Eff] = endpoint.get .in("containsArticle") .in(listQuery[String]("paths")) - .out(jsonBody[Seq[LearningPathSummaryV2]]) + .out(jsonBody[Seq[LearningPathSummaryV2DTO]]) .errorOut(errorOutputsFor(404)) .serverLogicPure { paths => searchService.containsPath(paths.values) match { diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2.scala index f3e13f62d3..8b70f6ad79 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2.scala @@ -10,7 +10,7 @@ package no.ndla.learningpathapi.controller import cats.implicits.catsSyntaxEitherId import no.ndla.common.model.api.CommaSeparatedList.* -import no.ndla.common.model.api.{Author, License} +import no.ndla.common.model.api.{AuthorDTO, LicenseDTO} import no.ndla.common.model.domain.learningpath import no.ndla.common.model.domain.learningpath.{StepStatus, LearningPathStatus as _} import no.ndla.language.Language @@ -116,8 +116,8 @@ trait LearningpathControllerV2 { * A Try with scroll result, or the return of the orFunction (Usually a try with a search result). */ private def scrollSearchOr(scrollId: Option[String], language: String)( - orFunction: => Try[(SearchResultV2, DynamicHeaders)] - ): Try[(SearchResultV2, DynamicHeaders)] = + orFunction: => Try[(SearchResultV2DTO, DynamicHeaders)] + ): Try[(SearchResultV2DTO, DynamicHeaders)] = scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => searchService.scroll(scroll, language) match { @@ -226,7 +226,7 @@ trait LearningpathControllerV2 { .in(fallback) .in(scrollId) .in(verificationStatus) - .out(jsonBody[SearchResultV2]) + .out(jsonBody[SearchResultV2DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400)) .serverLogicPure { @@ -252,9 +252,9 @@ trait LearningpathControllerV2 { .summary("Find public learningpaths") .description("Show public learningpaths") .in("search") - .in(jsonBody[SearchParams]) + .in(jsonBody[SearchParamsDTO]) .errorOut(errorOutputsFor(400)) - .out(jsonBody[SearchResultV2]) + .out(jsonBody[SearchResultV2DTO]) .out(EndpointOutput.derived[DynamicHeaders]) .serverLogicPure { searchParams => scrollSearchOr(searchParams.scrollId, searchParams.language.getOrElse(AllLanguages)) { @@ -284,7 +284,7 @@ trait LearningpathControllerV2 { .in(pageSize) .in(pageNo) .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[Seq[LearningPathV2]]) + .out(jsonBody[Seq[LearningPathV2DTO]]) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { user => { case (idList, fallback, language, pageSizeQ, pageNoQ) => @@ -313,7 +313,7 @@ trait LearningpathControllerV2 { .in(pathLearningpathId) .in(language) .in(fallback) - .out(jsonBody[LearningPathV2]) + .out(jsonBody[LearningPathV2DTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { combinedUser => @@ -326,7 +326,7 @@ trait LearningpathControllerV2 { .summary("Show status information for the learningpath") .description("Shows publishingstatus for the learningpath") .in(pathLearningpathId / "status") - .out(jsonBody[LearningPathStatus]) + .out(jsonBody[LearningPathStatusDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { maybeUser => id => readService.statusFor(id, maybeUser).handleErrorsOrOk } @@ -337,7 +337,7 @@ trait LearningpathControllerV2 { .in(pathLearningpathId / "learningsteps") .in(fallback) .in(language) - .out(jsonBody[LearningStepContainerSummary]) + .out(jsonBody[LearningStepContainerSummaryDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { maybeUser => @@ -360,7 +360,7 @@ trait LearningpathControllerV2 { .in(pathLearningpathId / "learningsteps" / pathLearningstepId) .in(language) .in(fallback) - .out(jsonBody[LearningStepV2]) + .out(jsonBody[LearningStepV2DTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { maybeUser => @@ -377,7 +377,7 @@ trait LearningpathControllerV2 { .in(pathLearningpathId / "learningsteps" / "trash") .in(language) .in(fallback) - .out(jsonBody[LearningStepContainerSummary]) + .out(jsonBody[LearningStepContainerSummaryDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -391,7 +391,7 @@ trait LearningpathControllerV2 { .description("Shows status for the learningstep") .in(pathLearningpathId / "learningsteps" / pathLearningstepId / "status") .in(fallback) - .out(jsonBody[LearningStepStatus]) + .out(jsonBody[LearningStepStatusDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -412,7 +412,7 @@ trait LearningpathControllerV2 { .summary("Fetch all learningspaths you have created") .description("Shows your learningpaths.") .in("mine") - .out(jsonBody[List[LearningPathV2]]) + .out(jsonBody[List[LearningPathV2DTO]]) .errorOut(errorOutputsFor(401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => _ => readService.withOwnerV2(user, DefaultLanguage, true).asRight } @@ -422,7 +422,7 @@ trait LearningpathControllerV2 { .description("Shows all valid licenses") .in("licenses") .in(licenseFilter) - .out(jsonBody[Seq[License]]) + .out(jsonBody[Seq[LicenseDTO]]) .errorOut(errorOutputsFor(401, 403, 404)) .serverLogicPure { license => val licenses: Seq[LicenseDefinition] = @@ -432,14 +432,14 @@ trait LearningpathControllerV2 { mapping.License.getLicenses .filter(_.license.toString.contains(filter)) } - licenses.map(x => License(x.license.toString, Option(x.description), x.url)).asRight + licenses.map(x => LicenseDTO(x.license.toString, Option(x.description), x.url)).asRight } def addLearningpath: ServerEndpoint[Any, Eff] = endpoint.post .summary("Store new learningpath") .description("Adds the given learningpath") - .in(jsonBody[NewLearningPathV2]) - .out(statusCode(StatusCode.Created).and(jsonBody[LearningPathV2])) + .in(jsonBody[NewLearningPathV2DTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[LearningPathV2DTO])) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser @@ -457,8 +457,8 @@ trait LearningpathControllerV2 { .summary("Copy given learningpath and store it as a new learningpath") .description("Copies the given learningpath, with the option to override some fields") .in(pathLearningpathId / "copy") - .in(jsonBody[NewCopyLearningPathV2]) - .out(statusCode(StatusCode.Created).and(jsonBody[LearningPathV2])) + .in(jsonBody[NewCopyLearningPathV2DTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[LearningPathV2DTO])) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser @@ -483,8 +483,8 @@ trait LearningpathControllerV2 { .summary("Update given learningpath") .description("Updates the given learningPath") .in(pathLearningpathId) - .in(jsonBody[UpdatedLearningPathV2]) - .out(jsonBody[LearningPathV2]) + .in(jsonBody[UpdatedLearningPathV2DTO]) + .out(jsonBody[LearningPathV2DTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -503,8 +503,8 @@ trait LearningpathControllerV2 { .summary("Add new learningstep to learningpath") .description("Adds the given LearningStep") .in(pathLearningpathId / "learningsteps") - .in(jsonBody[NewLearningStepV2]) - .out(statusCode(StatusCode.Created).and(jsonBody[LearningStepV2])) + .in(jsonBody[NewLearningStepV2DTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[LearningStepV2DTO])) .out(EndpointOutput.derived[DynamicHeaders]) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .withRequiredMyNDLAUserOrTokenUser @@ -525,8 +525,8 @@ trait LearningpathControllerV2 { .summary("Update given learningstep") .description("Update the given learningStep") .in(pathLearningpathId / "learningsteps" / pathLearningstepId) - .in(jsonBody[UpdatedLearningStepV2]) - .out(jsonBody[LearningStepV2]) + .in(jsonBody[UpdatedLearningStepV2DTO]) + .out(jsonBody[LearningStepV2DTO]) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -547,8 +547,8 @@ trait LearningpathControllerV2 { "Updates the sequence number for the given learningstep. The sequence number of other learningsteps will be affected by this." ) .in(pathLearningpathId / "learningsteps" / pathLearningstepId / "seqNo") - .in(jsonBody[LearningStepSeqNo]) - .out(jsonBody[LearningStepSeqNo]) + .in(jsonBody[LearningStepSeqNoDTO]) + .out(jsonBody[LearningStepSeqNoDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -561,8 +561,8 @@ trait LearningpathControllerV2 { .summary("Update status of given learningstep") .description("Updates the status of the given learningstep") .in(pathLearningpathId / "learningsteps" / pathLearningstepId / "status") - .in(jsonBody[LearningStepStatus]) - .out(jsonBody[LearningStepV2]) + .in(jsonBody[LearningStepStatusDTO]) + .out(jsonBody[LearningStepV2DTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -584,8 +584,8 @@ trait LearningpathControllerV2 { .summary("Update status of given learningpath") .description("Updates the status of the given learningPath") .in(pathLearningpathId / "status") - .in(jsonBody[UpdateLearningPathStatus]) - .out(jsonBody[LearningPathV2]) + .in(jsonBody[UpdateLearningPathStatusDTO]) + .out(jsonBody[LearningPathV2DTO]) .errorOut(errorOutputsFor(400, 403, 404, 500)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { user => @@ -613,7 +613,7 @@ trait LearningpathControllerV2 { .summary("Fetch all learningpaths with specified status") .description("Fetch all learningpaths with specified status") .in("status" / learningPathStatus) - .out(jsonBody[List[LearningPathV2]]) + .out(jsonBody[List[LearningPathV2DTO]]) .errorOut(errorOutputsFor(400, 401, 403, 500)) .withOptionalMyNDLAUserOrTokenUser .serverLogicPure { user => status => readService.learningPathWithStatus(status, user).handleErrorsOrOk } @@ -663,7 +663,7 @@ trait LearningpathControllerV2 { .in("tags") .in(language) .in(fallback) - .out(jsonBody[LearningPathTagsSummary]) + .out(jsonBody[LearningPathTagsSummaryDTO]) .errorOut(errorOutputsFor(500)) .serverLogicPure { case (language, fallback) => val allTags = readService.tags @@ -677,7 +677,7 @@ trait LearningpathControllerV2 { .summary("Fetch all previously used contributors in learningpaths") .description("Retrieves a list of all previously used contributors in learningpaths") .in("contributors") - .out(jsonBody[List[Author]]) + .out(jsonBody[List[AuthorDTO]]) .errorOut(errorOutputsFor()) .serverLogicPure { _ => readService.contributors.asRight @@ -690,7 +690,7 @@ trait LearningpathControllerV2 { .in(language) .in(fallback) .in(createResourceIfMissing) - .out(jsonBody[LearningPathV2]) + .out(jsonBody[LearningPathV2DTO]) .errorOut(errorOutputsFor(403, 404, 500)) .withRequiredMyNDLAUserOrTokenUser .serverLogicPure { userInfo => @@ -711,7 +711,7 @@ trait LearningpathControllerV2 { .summary("Fetch learningpaths containing specified article") .description("Fetch learningpaths containing specified article") .in("contains-article" / pathArticleId) - .out(jsonBody[Seq[LearningPathSummaryV2]]) + .out(jsonBody[Seq[LearningPathSummaryV2DTO]]) .errorOut(errorOutputsFor(400, 500)) .serverLogicPure { articleId => val nodes = taxonomyApiClient.queryNodes(articleId).getOrElse(List.empty).flatMap(_.paths) diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Copyright.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CopyrightDTO.scala similarity index 56% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Copyright.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CopyrightDTO.scala index e2b7d251a1..405be4a880 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Copyright.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CopyrightDTO.scala @@ -10,16 +10,16 @@ package no.ndla.learningpathapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.{Author, License} +import no.ndla.common.model.api.{AuthorDTO, LicenseDTO} import sttp.tapir.Schema.annotations.description @description("Description of copyright information") -case class Copyright( - @description("Describes the license of the learningpath") license: License, - @description("List of authors") contributors: Seq[Author] +case class CopyrightDTO( + @description("Describes the license of the learningpath") license: LicenseDTO, + @description("List of authors") contributors: Seq[AuthorDTO] ) -object Copyright { - implicit val encoder: Encoder[Copyright] = deriveEncoder - implicit val decoder: Decoder[Copyright] = deriveDecoder +object CopyrightDTO { + implicit val encoder: Encoder[CopyrightDTO] = deriveEncoder + implicit val decoder: Decoder[CopyrightDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhoto.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhotoDTO.scala similarity index 53% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhoto.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhotoDTO.scala index 5c7bdd89c7..aa0dfbb28f 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhoto.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/CoverPhotoDTO.scala @@ -11,9 +11,9 @@ package no.ndla.learningpathapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -case class CoverPhoto(url: String, metaUrl: String) +case class CoverPhotoDTO(url: String, metaUrl: String) -object CoverPhoto { - implicit val encoder: Encoder[CoverPhoto] = deriveEncoder - implicit val decoder: Decoder[CoverPhoto] = deriveDecoder +object CoverPhotoDTO { + implicit val encoder: Encoder[CoverPhotoDTO] = deriveEncoder + implicit val decoder: Decoder[CoverPhotoDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Description.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/DescriptionDTO.scala similarity index 79% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Description.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/DescriptionDTO.scala index 18e9d7b04e..85ef89d2e0 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Description.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/DescriptionDTO.scala @@ -14,7 +14,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("The description of the learningpath") -case class Description( +case class DescriptionDTO( @description("The learningpath description. Basic HTML allowed") description: String, @description("ISO 639-1 code that represents the language used in description") language: String ) extends LanguageField[String] { @@ -22,7 +22,7 @@ case class Description( override def isEmpty: Boolean = description.isEmpty } -object Description { - implicit val encoder: Encoder[Description] = deriveEncoder - implicit val decoder: Decoder[Description] = deriveDecoder +object DescriptionDTO { + implicit val encoder: Encoder[DescriptionDTO] = deriveEncoder + implicit val decoder: Decoder[DescriptionDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2DTO.scala similarity index 71% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2DTO.scala index 6cc2525d9a..65c955c0ec 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/EmbedUrlV2DTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Representation of an embeddable url") -case class EmbedUrlV2( +case class EmbedUrlV2DTO( @description("The url") url: String, @description("Type of embed content") embedType: String ) -object EmbedUrlV2 { - implicit val encoder: Encoder[EmbedUrlV2] = deriveEncoder - implicit val decoder: Decoder[EmbedUrlV2] = deriveDecoder +object EmbedUrlV2DTO { + implicit val encoder: Encoder[EmbedUrlV2DTO] = deriveEncoder + implicit val decoder: Decoder[EmbedUrlV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Introduction.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/IntroductionDTO.scala similarity index 79% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Introduction.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/IntroductionDTO.scala index 072db4e415..ae4c208384 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Introduction.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/IntroductionDTO.scala @@ -14,7 +14,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("The introduction of the learningpath") -case class Introduction( +case class IntroductionDTO( @description("The introduction to the learningpath. Basic HTML allowed") introduction: String, @description("ISO 639-1 code that represents the language used in introduction") language: String ) extends LanguageField[String] { @@ -22,7 +22,7 @@ case class Introduction( override def isEmpty: Boolean = introduction.isEmpty } -object Introduction { - implicit val encoder: Encoder[Introduction] = deriveEncoder - implicit val decoder: Decoder[Introduction] = deriveDecoder +object IntroductionDTO { + implicit val encoder: Encoder[IntroductionDTO] = deriveEncoder + implicit val decoder: Decoder[IntroductionDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDump.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDumpDTO.scala similarity index 69% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDump.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDumpDTO.scala index 62bba59ba0..7c22a2b623 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDump.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathDomainDumpDTO.scala @@ -13,27 +13,27 @@ import no.ndla.common.model.domain.learningpath.{LearningPath, LearningStep} import sttp.tapir.Schema.annotations.description @description("Information about learningpaths") -case class LearningPathDomainDump( +case class LearningPathDomainDumpDTO( @description("The total number of learningpaths in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The search results") results: Seq[LearningPath] ) -object LearningPathDomainDump { - implicit val encoder: Encoder[LearningPathDomainDump] = deriveEncoder - implicit val decoder: Decoder[LearningPathDomainDump] = deriveDecoder +object LearningPathDomainDumpDTO { + implicit val encoder: Encoder[LearningPathDomainDumpDTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathDomainDumpDTO] = deriveDecoder } @description("Information about learningsteps") -case class LearningStepDomainDump( +case class LearningStepDomainDumpDTO( @description("The total number of learningsteps in the database") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The search results") results: Seq[LearningStep] ) -object LearningStepDomainDump { - implicit val encoder: Encoder[LearningStepDomainDump] = deriveEncoder - implicit val decoder: Decoder[LearningStepDomainDump] = deriveDecoder +object LearningStepDomainDumpDTO { + implicit val encoder: Encoder[LearningStepDomainDumpDTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepDomainDumpDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatus.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatusDTO.scala similarity index 66% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatus.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatusDTO.scala index 49501fd272..57b27a54d0 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatus.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathStatusDTO.scala @@ -13,11 +13,11 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Status information about a learningpath") -case class LearningPathStatus( +case class LearningPathStatusDTO( @description("The publishing status of the learningpath") status: String ) -object LearningPathStatus { - implicit val encoder: Encoder[LearningPathStatus] = deriveEncoder - implicit val decoder: Decoder[LearningPathStatus] = deriveDecoder +object LearningPathStatusDTO { + implicit val encoder: Encoder[LearningPathStatusDTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathStatusDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2.scala deleted file mode 100644 index 75b622dfa5..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Summary of meta information for a learningpath") -case class LearningPathSummaryV2( - @description("The unique id of the learningpath") id: Long, - @description("The revision number for this learningpath") revision: Option[Int], - @description("The titles of the learningpath") title: Title, - @description("The descriptions of the learningpath") description: Description, - @description("The introductions of the learningpath") introduction: Introduction, - @description("The full url to where the complete metainformation about the learningpath can be found") metaUrl: String, - @description("Url to where a cover photo can be found") coverPhotoUrl: Option[String], - @description("The duration of the learningpath in minutes") duration: Option[Int], - @description("The publishing status of the learningpath.") status: String, - @description("The date when this learningpath was created.") created: NDLADate, - @description("The date when this learningpath was last updated.") lastUpdated: NDLADate, - @description("Searchable tags for the learningpath") tags: LearningPathTags, - @description("The contributors of this learningpath") copyright: Copyright, - @description("A list of available languages for this audio") supportedLanguages: Seq[String], - @description("The id this learningpath is based on, if any") isBasedOn: Option[Long], - @description("Message that admins can place on a LearningPath for notifying a owner of issues with the LearningPath") message: Option[String] -) - -object LearningPathSummaryV2 { - implicit val encoder: Encoder[LearningPathSummaryV2] = deriveEncoder - implicit val decoder: Decoder[LearningPathSummaryV2] = deriveDecoder -} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2DTO.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2DTO.scala new file mode 100644 index 0000000000..c00fe2a913 --- /dev/null +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathSummaryV2DTO.scala @@ -0,0 +1,40 @@ +/* + * Part of NDLA learningpath-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.learningpathapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Summary of meta information for a learningpath") +case class LearningPathSummaryV2DTO( + @description("The unique id of the learningpath") id: Long, + @description("The revision number for this learningpath") revision: Option[Int], + @description("The titles of the learningpath") title: TitleDTO, + @description("The descriptions of the learningpath") description: DescriptionDTO, + @description("The introductions of the learningpath") introduction: IntroductionDTO, + @description("The full url to where the complete metainformation about the learningpath can be found") metaUrl: String, + @description("Url to where a cover photo can be found") coverPhotoUrl: Option[String], + @description("The duration of the learningpath in minutes") duration: Option[Int], + @description("The publishing status of the learningpath.") status: String, + @description("The date when this learningpath was created.") created: NDLADate, + @description("The date when this learningpath was last updated.") lastUpdated: NDLADate, + @description("Searchable tags for the learningpath") tags: LearningPathTagsDTO, + @description("The contributors of this learningpath") copyright: CopyrightDTO, + @description("A list of available languages for this audio") supportedLanguages: Seq[String], + @description("The id this learningpath is based on, if any") isBasedOn: Option[Long], + @description("Message that admins can place on a LearningPath for notifying a owner of issues with the LearningPath") message: Option[String] +) + +object LearningPathSummaryV2DTO { + implicit val encoder: Encoder[LearningPathSummaryV2DTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathSummaryV2DTO] = deriveDecoder +} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTags.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsDTO.scala similarity index 72% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTags.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsDTO.scala index e7edd3ebf8..6498d6ef66 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTags.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsDTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description -case class LearningPathTags( +case class LearningPathTagsDTO( @description("The searchable tags. Must be plain text") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) extends WithLanguage -object LearningPathTags { - implicit val encoder: Encoder[LearningPathTags] = deriveEncoder - implicit val decoder: Decoder[LearningPathTags] = deriveDecoder +object LearningPathTagsDTO { + implicit val encoder: Encoder[LearningPathTagsDTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathTagsDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummary.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummaryDTO.scala similarity index 69% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummary.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummaryDTO.scala index 9c495112f6..f87c543870 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummary.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathTagsSummaryDTO.scala @@ -11,13 +11,13 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description -case class LearningPathTagsSummary( +case class LearningPathTagsSummaryDTO( @description("The chosen language. Default is 'nb'") language: String, @description("The supported languages for these tags") supportedLanguages: Seq[String], @description("The searchable tags. Must be plain text") tags: Seq[String] ) -object LearningPathTagsSummary { - implicit val encoder: Encoder[LearningPathTagsSummary] = deriveEncoder - implicit val decoder: Decoder[LearningPathTagsSummary] = deriveDecoder +object LearningPathTagsSummaryDTO { + implicit val encoder: Encoder[LearningPathTagsSummaryDTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathTagsSummaryDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2.scala deleted file mode 100644 index 456d8a5ff2..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Meta information for a learningpath") -case class LearningPathV2( - @description("The unique id of the learningpath") id: Long, - @description("The revision number for this learningpath") revision: Int, - @description("The id this learningpath is based on, if any") isBasedOn: Option[Long], - @description("The title of the learningpath") title: Title, - @description("The description of the learningpath") description: Description, - @description("The full url to where the complete metainformation about the learningpath can be found") metaUrl: String, - @description("The learningsteps-summaries for this learningpath") learningsteps: Seq[LearningStepV2], - @description("The full url to where the learningsteps can be found") learningstepUrl: String, - @description("Information about where the cover photo can be found") coverPhoto: Option[CoverPhoto], - @description("The duration of the learningpath in minutes") duration: Option[Int], - @description("The publishing status of the learningpath") status: String, - @description("Verification status") verificationStatus: String, - @description("The date when this learningpath was created.") created: NDLADate, - @description("The date when this learningpath was last updated.") lastUpdated: NDLADate, - @description("Searchable tags for the learningpath") tags: LearningPathTags, - @description("Describes the copyright information for the learningpath") copyright: Copyright, - @description("True if authenticated user may edit this learningpath") canEdit: Boolean, - @description("The supported languages for this learningpath") supportedLanguages: Seq[String], - @description("Visible if administrator or owner of LearningPath") ownerId: Option[String], - @description("Message set by administrator. Visible if administrator or owner of LearningPath") message: Option[Message], - @description("The date when this learningpath was made available to the public.") madeAvailable: Option[NDLADate] -) - -object LearningPathV2 { - implicit val encoder: Encoder[LearningPathV2] = deriveEncoder - implicit val decoder: Decoder[LearningPathV2] = deriveDecoder -} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2DTO.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2DTO.scala new file mode 100644 index 0000000000..a57b930696 --- /dev/null +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningPathV2DTO.scala @@ -0,0 +1,45 @@ +/* + * Part of NDLA learningpath-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.learningpathapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Meta information for a learningpath") +case class LearningPathV2DTO( + @description("The unique id of the learningpath") id: Long, + @description("The revision number for this learningpath") revision: Int, + @description("The id this learningpath is based on, if any") isBasedOn: Option[Long], + @description("The title of the learningpath") title: TitleDTO, + @description("The description of the learningpath") description: DescriptionDTO, + @description("The full url to where the complete metainformation about the learningpath can be found") metaUrl: String, + @description("The learningsteps-summaries for this learningpath") learningsteps: Seq[LearningStepV2DTO], + @description("The full url to where the learningsteps can be found") learningstepUrl: String, + @description("Information about where the cover photo can be found") coverPhoto: Option[CoverPhotoDTO], + @description("The duration of the learningpath in minutes") duration: Option[Int], + @description("The publishing status of the learningpath") status: String, + @description("Verification status") verificationStatus: String, + @description("The date when this learningpath was created.") created: NDLADate, + @description("The date when this learningpath was last updated.") lastUpdated: NDLADate, + @description("Searchable tags for the learningpath") tags: LearningPathTagsDTO, + @description("Describes the copyright information for the learningpath") copyright: CopyrightDTO, + @description("True if authenticated user may edit this learningpath") canEdit: Boolean, + @description("The supported languages for this learningpath") supportedLanguages: Seq[String], + @description("Visible if administrator or owner of LearningPath") ownerId: Option[String], + @description("Message set by administrator. Visible if administrator or owner of LearningPath") message: Option[MessageDTO], + @description("The date when this learningpath was made available to the public.") madeAvailable: Option[NDLADate] +) + +object LearningPathV2DTO { + implicit val encoder: Encoder[LearningPathV2DTO] = deriveEncoder + implicit val decoder: Decoder[LearningPathV2DTO] = deriveDecoder +} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummary.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummaryDTO.scala similarity index 68% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummary.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummaryDTO.scala index 442cba8ecb..75994105be 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummary.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepContainerSummaryDTO.scala @@ -13,13 +13,13 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Summary of meta information for a learningstep including language and supported languages") -case class LearningStepContainerSummary( +case class LearningStepContainerSummaryDTO( @description("The chosen search language") language: String, - @description("The chosen search language") learningsteps: Seq[LearningStepSummaryV2], + @description("The chosen search language") learningsteps: Seq[LearningStepSummaryV2DTO], @description("The chosen search language") supportedLanguages: Seq[String] ) -object LearningStepContainerSummary { - implicit val encoder: Encoder[LearningStepContainerSummary] = deriveEncoder - implicit val decoder: Decoder[LearningStepContainerSummary] = deriveDecoder +object LearningStepContainerSummaryDTO { + implicit val encoder: Encoder[LearningStepContainerSummaryDTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepContainerSummaryDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNo.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNoDTO.scala similarity index 67% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNo.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNoDTO.scala index 135ddf8e3b..4cee379497 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNo.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSeqNoDTO.scala @@ -13,11 +13,11 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about the sequence number for a step") -case class LearningStepSeqNo( +case class LearningStepSeqNoDTO( @description("The sequence number for the learningstep") seqNo: Int ) -object LearningStepSeqNo { - implicit val encoder: Encoder[LearningStepSeqNo] = deriveEncoder - implicit val decoder: Decoder[LearningStepSeqNo] = deriveDecoder +object LearningStepSeqNoDTO { + implicit val encoder: Encoder[LearningStepSeqNoDTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepSeqNoDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatus.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatusDTO.scala similarity index 66% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatus.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatusDTO.scala index 571477187a..a6a4f93d17 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatus.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepStatusDTO.scala @@ -13,11 +13,11 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Status information about a learningpath") -case class LearningStepStatus( +case class LearningStepStatusDTO( @description("The status of the learningstep") status: String ) -object LearningStepStatus { - implicit val encoder: Encoder[LearningStepStatus] = deriveEncoder - implicit val decoder: Decoder[LearningStepStatus] = deriveDecoder +object LearningStepStatusDTO { + implicit val encoder: Encoder[LearningStepStatusDTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepStatusDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2.scala deleted file mode 100644 index 977489bcc1..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Summary of meta information for a learningstep") -case class LearningStepSummaryV2( - @description("The id of the learningstep") id: Long, - @description("The sequence number for the step. The first step has seqNo 0.") seqNo: Int, - @description("The title of the learningstep") title: Title, - @description("The type of the step") `type`: String, - @description("The full url to where the complete metainformation about the learningstep can be found") metaUrl: String -) - -object LearningStepSummaryV2{ - implicit val encoder: Encoder[LearningStepSummaryV2] = deriveEncoder - implicit val decoder: Decoder[LearningStepSummaryV2] = deriveDecoder -} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2DTO.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2DTO.scala new file mode 100644 index 0000000000..099e726b8a --- /dev/null +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepSummaryV2DTO.scala @@ -0,0 +1,28 @@ +/* + * Part of NDLA learningpath-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.learningpathapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Summary of meta information for a learningstep") +case class LearningStepSummaryV2DTO( + @description("The id of the learningstep") id: Long, + @description("The sequence number for the step. The first step has seqNo 0.") seqNo: Int, + @description("The title of the learningstep") title: TitleDTO, + @description("The type of the step") `type`: String, + @description("The full url to where the complete metainformation about the learningstep can be found") metaUrl: String +) + +object LearningStepSummaryV2DTO{ + implicit val encoder: Encoder[LearningStepSummaryV2DTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepSummaryV2DTO] = deriveDecoder +} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2.scala deleted file mode 100644 index f14d264a37..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.License -import sttp.tapir.Schema.annotations.description - -// format: off -@description("Information about a learningstep") -case class LearningStepV2( - @description("The id of the learningstep") id: Long, - @description("The revision number for this learningstep") revision: Int, - @description("The sequence number for the step. The first step has seqNo 0.") seqNo: Int, - @description("The title of the learningstep") title: Title, - @description("The introduction of the learningstep") introduction: Option[Introduction], - @description("The description of the learningstep") description: Option[Description], - @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2], - @description("Determines if the title of the step should be displayed in viewmode") showTitle: Boolean, - @description("The type of the step") `type`: String, - @description("Describes the copyright information for the learningstep") license: Option[License], - @description("The full url to where the complete metainformation about the learningstep can be found") metaUrl: String, - @description("True if authenticated user may edit this learningstep") canEdit: Boolean, - @description("The status of the learningstep") status: String, - @description("The supported languages of the learningstep") supportedLanguages: Seq[String] -) - -object LearningStepV2{ - implicit val encoder: Encoder[LearningStepV2] = deriveEncoder - implicit val decoder: Decoder[LearningStepV2] = deriveDecoder -} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2DTO.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2DTO.scala new file mode 100644 index 0000000000..e4eee1babc --- /dev/null +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/LearningStepV2DTO.scala @@ -0,0 +1,38 @@ +/* + * Part of NDLA learningpath-api + * Copyright (C) 2016 NDLA + * + * See LICENSE + * + */ + +package no.ndla.learningpathapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.api.LicenseDTO +import sttp.tapir.Schema.annotations.description + +// format: off +@description("Information about a learningstep") +case class LearningStepV2DTO( + @description("The id of the learningstep") id: Long, + @description("The revision number for this learningstep") revision: Int, + @description("The sequence number for the step. The first step has seqNo 0.") seqNo: Int, + @description("The title of the learningstep") title: TitleDTO, + @description("The introduction of the learningstep") introduction: Option[IntroductionDTO], + @description("The description of the learningstep") description: Option[DescriptionDTO], + @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2DTO], + @description("Determines if the title of the step should be displayed in viewmode") showTitle: Boolean, + @description("The type of the step") `type`: String, + @description("Describes the copyright information for the learningstep") license: Option[LicenseDTO], + @description("The full url to where the complete metainformation about the learningstep can be found") metaUrl: String, + @description("True if authenticated user may edit this learningstep") canEdit: Boolean, + @description("The status of the learningstep") status: String, + @description("The supported languages of the learningstep") supportedLanguages: Seq[String] +) + +object LearningStepV2DTO{ + implicit val encoder: Encoder[LearningStepV2DTO] = deriveEncoder + implicit val decoder: Decoder[LearningStepV2DTO] = deriveDecoder +} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Message.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/MessageDTO.scala similarity index 76% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Message.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/MessageDTO.scala index e6a413ce1c..d2f3422c46 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Message.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/MessageDTO.scala @@ -12,12 +12,12 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Administrator message left on learningpaths") -case class Message( +case class MessageDTO( @description("Message left on a learningpath by administrator") message: String, @description("When the message was left") date: NDLADate ) -object Message { - implicit val encoder: Encoder[Message] = deriveEncoder - implicit val decoder: Decoder[Message] = deriveDecoder +object MessageDTO { + implicit val encoder: Encoder[MessageDTO] = deriveEncoder + implicit val decoder: Decoder[MessageDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2DTO.scala similarity index 77% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2DTO.scala index b9c511bbc8..fbdc49ed67 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewCopyLearningPathV2DTO.scala @@ -13,17 +13,17 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta information for a new learningpath based on a copy") -case class NewCopyLearningPathV2( +case class NewCopyLearningPathV2DTO( @description("The titles of the learningpath") title: String, @description("The descriptions of the learningpath") description: Option[String], @description("The chosen language") language: String, @description("Url to cover-photo in NDLA image-api.") coverPhotoMetaUrl: Option[String], @description("The duration of the learningpath in minutes. Must be greater than 0") duration: Option[Int], @description("Searchable tags for the learningpath") tags: Option[Seq[String]], - @description("Describes the copyright information for the learningpath") copyright: Option[Copyright] + @description("Describes the copyright information for the learningpath") copyright: Option[CopyrightDTO] ) -object NewCopyLearningPathV2 { - implicit val encoder: Encoder[NewCopyLearningPathV2] = deriveEncoder - implicit val decoder: Decoder[NewCopyLearningPathV2] = deriveDecoder +object NewCopyLearningPathV2DTO { + implicit val encoder: Encoder[NewCopyLearningPathV2DTO] = deriveEncoder + implicit val decoder: Decoder[NewCopyLearningPathV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2DTO.scala similarity index 78% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2DTO.scala index 8881b553da..cee5a07c47 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningPathV2DTO.scala @@ -13,17 +13,17 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta information for a new learningpath") -case class NewLearningPathV2( +case class NewLearningPathV2DTO( @description("The titles of the learningpath") title: String, @description("The descriptions of the learningpath") description: String, @description("Url to cover-photo in NDLA image-api.") coverPhotoMetaUrl: Option[String], @description("The duration of the learningpath in minutes. Must be greater than 0") duration: Option[Int], @description("Searchable tags for the learningpath") tags: Seq[String], @description("The chosen language") language: String, - @description("Describes the copyright information for the learningpath") copyright: Copyright + @description("Describes the copyright information for the learningpath") copyright: CopyrightDTO ) -object NewLearningPathV2 { - implicit val encoder: Encoder[NewLearningPathV2] = deriveEncoder - implicit val decoder: Decoder[NewLearningPathV2] = deriveDecoder +object NewLearningPathV2DTO { + implicit val encoder: Encoder[NewLearningPathV2DTO] = deriveEncoder + implicit val decoder: Decoder[NewLearningPathV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2DTO.scala similarity index 80% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2DTO.scala index 5505c472d6..fbf8915eb8 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/NewLearningStepV2DTO.scala @@ -13,18 +13,18 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a new learningstep") -case class NewLearningStepV2( +case class NewLearningStepV2DTO( @description("The titles of the learningstep") title: String, @description("The introduction of the learningstep") introduction: Option[String], @description("The descriptions of the learningstep") description: Option[String], @description("The chosen language") language: String, - @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2], + @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2DTO], @description("Determines if the title of the step should be displayed in viewmode") showTitle: Boolean, @description("The type of the step") `type`: String, @description("Describes the copyright information for the learningstep") license: Option[String] ) -object NewLearningStepV2 { - implicit val encoder: Encoder[NewLearningStepV2] = deriveEncoder - implicit val decoder: Decoder[NewLearningStepV2] = deriveDecoder +object NewLearningStepV2DTO { + implicit val encoder: Encoder[NewLearningStepV2DTO] = deriveEncoder + implicit val decoder: Decoder[NewLearningStepV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParams.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParams.scala deleted file mode 100644 index 715552649b..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParams.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2017 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.learningpathapi.model.domain.Sort -import sttp.tapir.Schema.annotations.description - -// format: off -@description("The search parameters") -case class SearchParams( - @description("The search query") query: Option[String], - @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], - @description("The page number of the search hits to display.") page: Option[Int], - @description("The number of search hits to display for each page.") pageSize: Option[Int], - @description("Return only learning paths that have one of the provided ids") ids: Option[List[Long]], - @description("Return only learning paths that are tagged with this exact tag.") tag: Option[String], - @description("The sorting used on results. Default is by -relevance.") sort: Option[Sort], - @description("Return all matched learning paths whether they exist on selected language or not.") fallback: Option[Boolean], - @description("Return only learning paths that have the provided verification status.") verificationStatus: Option[String], - @description("A search context retrieved from the response header of a previous search.") scrollId: Option[String] -) - -object SearchParams{ - implicit val encoder: Encoder[SearchParams] = deriveEncoder - implicit val decoder: Decoder[SearchParams] = deriveDecoder -} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParamsDTO.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParamsDTO.scala new file mode 100644 index 0000000000..0d783227bd --- /dev/null +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchParamsDTO.scala @@ -0,0 +1,34 @@ +/* + * Part of NDLA learningpath-api + * Copyright (C) 2017 NDLA + * + * See LICENSE + * + */ + +package no.ndla.learningpathapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.learningpathapi.model.domain.Sort +import sttp.tapir.Schema.annotations.description + +// format: off +@description("The search parameters") +case class SearchParamsDTO( + @description("The search query") query: Option[String], + @description("The ISO 639-1 language code describing language used in query-params") language: Option[String], + @description("The page number of the search hits to display.") page: Option[Int], + @description("The number of search hits to display for each page.") pageSize: Option[Int], + @description("Return only learning paths that have one of the provided ids") ids: Option[List[Long]], + @description("Return only learning paths that are tagged with this exact tag.") tag: Option[String], + @description("The sorting used on results. Default is by -relevance.") sort: Option[Sort], + @description("Return all matched learning paths whether they exist on selected language or not.") fallback: Option[Boolean], + @description("Return only learning paths that have the provided verification status.") verificationStatus: Option[String], + @description("A search context retrieved from the response header of a previous search.") scrollId: Option[String] +) + +object SearchParamsDTO{ + implicit val encoder: Encoder[SearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[SearchParamsDTO] = deriveDecoder +} diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2DTO.scala similarity index 77% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2DTO.scala index b073815746..3e5285d773 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/SearchResultV2DTO.scala @@ -13,15 +13,15 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class SearchResultV2( +case class SearchResultV2DTO( @description("The total number of learningpaths matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[LearningPathSummaryV2] + @description("The search results") results: Seq[LearningPathSummaryV2DTO] ) -object SearchResultV2 { - implicit val encoder: Encoder[SearchResultV2] = deriveEncoder - implicit val decoder: Decoder[SearchResultV2] = deriveDecoder +object SearchResultV2DTO { + implicit val encoder: Encoder[SearchResultV2DTO] = deriveEncoder + implicit val decoder: Decoder[SearchResultV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Title.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/TitleDTO.scala similarity index 81% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Title.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/TitleDTO.scala index 21faf6f380..d7c0c63238 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/Title.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/TitleDTO.scala @@ -14,7 +14,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("Representation of a title") -case class Title( +case class TitleDTO( @description("The title of the content. Must be plain text") title: String, @description("ISO 639-1 code that represents the language used in title") language: String ) extends LanguageField[String] { @@ -22,7 +22,7 @@ case class Title( override def isEmpty: Boolean = title.isEmpty } -object Title { - implicit val encoder: Encoder[Title] = deriveEncoder - implicit val decoder: Decoder[Title] = deriveDecoder +object TitleDTO { + implicit val encoder: Encoder[TitleDTO] = deriveEncoder + implicit val decoder: Decoder[TitleDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatus.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatusDTO.scala similarity index 71% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatus.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatusDTO.scala index 8607878937..5bd2302166 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatus.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdateLearningPathStatusDTO.scala @@ -12,12 +12,12 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Status information about a learningpath") -case class UpdateLearningPathStatus( +case class UpdateLearningPathStatusDTO( @description("The publishing status of the learningpath") status: String, @description("Message that admins can place on a LearningPath for notifying a owner of issues with the LearningPath") message: Option[String] ) -object UpdateLearningPathStatus { - implicit val encoder: Encoder[UpdateLearningPathStatus] = deriveEncoder - implicit val decoder: Decoder[UpdateLearningPathStatus] = deriveDecoder +object UpdateLearningPathStatusDTO { + implicit val encoder: Encoder[UpdateLearningPathStatusDTO] = deriveEncoder + implicit val decoder: Decoder[UpdateLearningPathStatusDTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2DTO.scala similarity index 80% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2DTO.scala index cab6de04ac..05b5e18dbd 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningPathV2DTO.scala @@ -13,7 +13,7 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Meta information for a new learningpath") -case class UpdatedLearningPathV2( +case class UpdatedLearningPathV2DTO( @description("The revision number for this learningpath") revision: Int, @description("The title of the learningpath") title: Option[String], @description("The chosen language") language: String, @@ -21,13 +21,13 @@ case class UpdatedLearningPathV2( @description("Url to cover-photo in NDLA image-api.") coverPhotoMetaUrl: Option[String], @description("The duration of the learningpath in minutes. Must be greater than 0") duration: Option[Int], @description("Searchable tags for the learningpath") tags: Option[Seq[String]], - @description("Describes the copyright information for the learningpath") copyright: Option[Copyright], + @description("Describes the copyright information for the learningpath") copyright: Option[CopyrightDTO], @description("Whether to delete a message connected to a learningpath by an administrator.") deleteMessage: Option[ Boolean ] ) -object UpdatedLearningPathV2 { - implicit val encoder: Encoder[UpdatedLearningPathV2] = deriveEncoder - implicit val decoder: Decoder[UpdatedLearningPathV2] = deriveDecoder +object UpdatedLearningPathV2DTO { + implicit val encoder: Encoder[UpdatedLearningPathV2DTO] = deriveEncoder + implicit val decoder: Decoder[UpdatedLearningPathV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2DTO.scala similarity index 81% rename from learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2.scala rename to learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2DTO.scala index 74403240cf..36bc8246ef 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/UpdatedLearningStepV2DTO.scala @@ -13,19 +13,19 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about a new learningstep") -case class UpdatedLearningStepV2( +case class UpdatedLearningStepV2DTO( @description("The revision number for this learningstep") revision: Int, @description("The title of the learningstep") title: Option[String], @description("The introduction of the learningstep") introduction: Option[String], @description("The chosen language") language: String, @description("The description of the learningstep") description: Option[String], - @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2], + @description("The embed content for the learningstep") embedUrl: Option[EmbedUrlV2DTO], @description("Determines if the title of the step should be displayed in viewmode") showTitle: Option[Boolean], @description("The type of the step") `type`: Option[String], @description("Describes the copyright information for the learningstep") license: Option[String] ) -object UpdatedLearningStepV2 { - implicit val encoder: Encoder[UpdatedLearningStepV2] = deriveEncoder - implicit val decoder: Decoder[UpdatedLearningStepV2] = deriveDecoder +object UpdatedLearningStepV2DTO { + implicit val encoder: Encoder[UpdatedLearningStepV2DTO] = deriveEncoder + implicit val decoder: Decoder[UpdatedLearningStepV2DTO] = deriveDecoder } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/ValidationError.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/ValidationError.scala deleted file mode 100644 index 1dfb18c6e1..0000000000 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/api/ValidationError.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Part of NDLA learningpath-api - * Copyright (C) 2016 NDLA - * - * See LICENSE - * - */ - -package no.ndla.learningpathapi.model.api - -import no.ndla.common.errors.ValidationMessage -import sttp.tapir.Schema.annotations.description - -import java.time.LocalDateTime - -@description("Information about validation errors") -case class ValidationError( - @description("Code stating the type of error") code: String, - @description("Description of the error") description: String, - @description("List of validation messages") messages: Seq[ValidationMessage], - @description("When the error occured") occuredAt: LocalDateTime = LocalDateTime.now() -) diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/domain/SearchResult.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/domain/SearchResult.scala index 5cb30093aa..84e651f9e2 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/domain/SearchResult.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/domain/SearchResult.scala @@ -6,13 +6,13 @@ */ package no.ndla.learningpathapi.model.domain -import no.ndla.learningpathapi.model.api.LearningPathSummaryV2 +import no.ndla.learningpathapi.model.api.LearningPathSummaryV2DTO case class SearchResult( totalCount: Long, page: Option[Int], pageSize: Int, language: String, - results: Seq[LearningPathSummaryV2], + results: Seq[LearningPathSummaryV2DTO], scrollId: Option[String] ) diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/search/SearchableLearningPath.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/search/SearchableLearningPath.scala index 36c5033d90..24034d0b35 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/search/SearchableLearningPath.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/model/search/SearchableLearningPath.scala @@ -11,7 +11,7 @@ package no.ndla.learningpathapi.model.search import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import no.ndla.common.model.NDLADate -import no.ndla.learningpathapi.model.api.Copyright +import no.ndla.learningpathapi.model.api.CopyrightDTO import no.ndla.search.model.{SearchableLanguageList, SearchableLanguageValues} case class SearchableLearningPath( @@ -27,7 +27,7 @@ case class SearchableLearningPath( defaultTitle: Option[String], tags: SearchableLanguageList, learningsteps: Seq[SearchableLearningStep], - copyright: Copyright, + copyright: CopyrightDTO, isBasedOn: Option[Long] ) diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ConverterService.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ConverterService.scala index b6599ad89b..813b2f1ca0 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ConverterService.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ConverterService.scala @@ -30,7 +30,7 @@ import no.ndla.common.{Clock, errors} import no.ndla.language.Language.* import no.ndla.learningpathapi.Props import no.ndla.learningpathapi.integration.* -import no.ndla.learningpathapi.model.api.{LearningPathStatus as _, *} +import no.ndla.learningpathapi.model.api.{LearningPathStatusDTO as _, *} import no.ndla.learningpathapi.model.domain.UserInfo.LearningpathCombinedUser import no.ndla.learningpathapi.model.domain.ImplicitLearningPath.ImplicitLearningPathMethods import no.ndla.learningpathapi.model.{api, domain} @@ -51,51 +51,51 @@ trait ConverterService { class ConverterService { import props.* - def asEmbedUrlV2(embedUrl: api.EmbedUrlV2, language: String): EmbedUrl = { + def asEmbedUrlV2(embedUrl: api.EmbedUrlV2DTO, language: String): EmbedUrl = { learningpath.EmbedUrl(embedUrl.url, language, EmbedType.valueOfOrError(embedUrl.embedType)) } - def asDescription(description: api.Description): learningpath.Description = { + def asDescription(description: api.DescriptionDTO): learningpath.Description = { Description(description.description, description.language) } - def asTitle(title: api.Title): common.Title = { + def asTitle(title: api.TitleDTO): common.Title = { common.Title(title.title, title.language) } - def asLearningPathTags(tags: api.LearningPathTags): common.Tag = { + def asLearningPathTags(tags: api.LearningPathTagsDTO): common.Tag = { common.Tag(tags.tags, tags.language) } - private def asApiLearningPathTags(tags: common.Tag): api.LearningPathTags = { - api.LearningPathTags(tags.tags, tags.language) + private def asApiLearningPathTags(tags: common.Tag): api.LearningPathTagsDTO = { + api.LearningPathTagsDTO(tags.tags, tags.language) } - def asApiCopyright(copyright: learningpath.LearningpathCopyright): api.Copyright = { - api.Copyright(asApiLicense(copyright.license), copyright.contributors.map(_.toApi)) + def asApiCopyright(copyright: learningpath.LearningpathCopyright): api.CopyrightDTO = { + api.CopyrightDTO(asApiLicense(copyright.license), copyright.contributors.map(_.toApi)) } - def asApiLicense(license: String): commonApi.License = + def asApiLicense(license: String): commonApi.LicenseDTO = getLicense(license) match { - case Some(l) => commonApi.License(l.license.toString, Option(l.description), l.url) - case None => commonApi.License(license, Some("Invalid license"), None) + case Some(l) => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url) + case None => commonApi.LicenseDTO(license, Some("Invalid license"), None) } - def asAuthor(user: domain.NdlaUserName): commonApi.Author = { + def asAuthor(user: domain.NdlaUserName): commonApi.AuthorDTO = { val names = Array(user.first_name, user.middle_name, user.last_name) .filter(_.isDefined) .map(_.get) - commonApi.Author("Forfatter", names.mkString(" ")) + commonApi.AuthorDTO("Forfatter", names.mkString(" ")) } - def asCoverPhoto(imageId: String): Option[CoverPhoto] = { + def asCoverPhoto(imageId: String): Option[CoverPhotoDTO] = { val metaUrl = createUrlToImageApi(imageId) val imageUrl = createUrlToImageApiRaw(imageId) - Some(api.CoverPhoto(imageUrl, metaUrl)) + Some(api.CoverPhotoDTO(imageUrl, metaUrl)) } - private def asCopyright(copyright: api.Copyright): learningpath.LearningpathCopyright = { + private def asCopyright(copyright: api.CopyrightDTO): learningpath.LearningpathCopyright = { learningpath.LearningpathCopyright(copyright.license.license, copyright.contributors.map(_.toDomain)) } @@ -104,7 +104,7 @@ trait ConverterService { language: String, fallback: Boolean, userInfo: CombinedUser - ): Try[api.LearningPathV2] = { + ): Try[api.LearningPathV2DTO] = { val supportedLanguages = lp.supportedLanguages if (languageIsSupported(supportedLanguages, language) || fallback) { @@ -112,15 +112,15 @@ trait ConverterService { val title = findByLanguageOrBestEffort(lp.title, language) .map(asApiTitle) - .getOrElse(api.Title("", DefaultLanguage)) + .getOrElse(api.TitleDTO("", DefaultLanguage)) val description = findByLanguageOrBestEffort(lp.description, language) .map(asApiDescription) - .getOrElse(api.Description("", DefaultLanguage)) + .getOrElse(api.DescriptionDTO("", DefaultLanguage)) val tags = findByLanguageOrBestEffort(lp.tags, language) .map(asApiLearningPathTags) - .getOrElse(api.LearningPathTags(Seq(), DefaultLanguage)) + .getOrElse(api.LearningPathTagsDTO(Seq(), DefaultLanguage)) val learningSteps = lp.learningsteps .map(lsteps => { lsteps @@ -133,7 +133,7 @@ trait ConverterService { val message = lp.message.filter(_ => lp.canEdit(userInfo)).map(asApiMessage) val owner = Some(lp.owner).filter(_ => userInfo.isAdmin) Success( - api.LearningPathV2( + api.LearningPathV2DTO( lp.id.get, lp.revision.get, lp.isBasedOn, @@ -163,8 +163,8 @@ trait ConverterService { ) } - private def asApiMessage(message: learningpath.Message): api.Message = - api.Message(message.message, message.date) + private def asApiMessage(message: learningpath.Message): api.MessageDTO = + api.MessageDTO(message.message, message.date) private def extractImageId(url: String): Option[String] = { learningPathValidator.validateCoverPhoto(url) match { @@ -194,7 +194,7 @@ trait ConverterService { def mergeLearningPaths( existing: LearningPath, - updated: UpdatedLearningPathV2, + updated: UpdatedLearningPathV2DTO, userInfo: CombinedUser ): LearningPath = { val status = mergeStatus(existing, userInfo) @@ -241,7 +241,7 @@ trait ConverterService { ) } - def asDomainLearningStep(newLearningStep: NewLearningStepV2, learningPath: LearningPath): Try[LearningStep] = { + def asDomainLearningStep(newLearningStep: NewLearningStepV2DTO, learningPath: LearningPath): Try[LearningStep] = { val introduction = newLearningStep.introduction .map(Introduction(_, newLearningStep.language)) .toSeq @@ -302,7 +302,7 @@ trait ConverterService { learningPath.copy(learningsteps = Some(steps), status = status, lastUpdated = clock.now()) } - def mergeLearningSteps(existing: LearningStep, updated: UpdatedLearningStepV2): Try[LearningStep] = { + def mergeLearningSteps(existing: LearningStep, updated: UpdatedLearningStepV2DTO): Try[LearningStep] = { val titles = updated.title match { case None => existing.title case Some(value) => @@ -352,7 +352,7 @@ trait ConverterService { def newFromExistingLearningPath( existing: LearningPath, - newLearningPath: NewCopyLearningPathV2, + newLearningPath: NewCopyLearningPathV2DTO, user: CombinedUser ): Try[LearningPath] = { val oldTitle = Seq(common.Title(newLearningPath.title, newLearningPath.language)) @@ -404,7 +404,7 @@ trait ConverterService { } } - def newLearningPath(newLearningPath: NewLearningPathV2, user: CombinedUser): Try[LearningPath] = { + def newLearningPath(newLearningPath: NewLearningPathV2DTO, user: CombinedUser): Try[LearningPath] = { val domainTags = if (newLearningPath.tags.isEmpty) Seq.empty else @@ -432,12 +432,12 @@ trait ConverterService { } } - def getApiIntroduction(learningSteps: Seq[LearningStep]): Seq[api.Introduction] = { + def getApiIntroduction(learningSteps: Seq[LearningStep]): Seq[api.IntroductionDTO] = { learningSteps .find(_.`type` == learningpath.StepType.INTRODUCTION) .toList .flatMap(x => x.description) - .map(x => api.Introduction(x.description, x.language)) + .map(x => api.IntroductionDTO(x.description, x.language)) } def languageIsNotSupported(supportedLanguages: Seq[String], language: String): Boolean = { @@ -447,26 +447,26 @@ trait ConverterService { def asApiLearningpathSummaryV2( learningpath: LearningPath, user: CombinedUser - ): Try[api.LearningPathSummaryV2] = { + ): Try[api.LearningPathSummaryV2DTO] = { val supportedLanguages = learningpath.supportedLanguages val title = findByLanguageOrBestEffort(learningpath.title, AllLanguages) .map(asApiTitle) - .getOrElse(api.Title("", DefaultLanguage)) + .getOrElse(api.TitleDTO("", DefaultLanguage)) val description = findByLanguageOrBestEffort(learningpath.description, AllLanguages) .map(asApiDescription) - .getOrElse(api.Description("", DefaultLanguage)) + .getOrElse(api.DescriptionDTO("", DefaultLanguage)) val tags = findByLanguageOrBestEffort(learningpath.tags, AllLanguages) .map(asApiLearningPathTags) - .getOrElse(api.LearningPathTags(Seq(), DefaultLanguage)) + .getOrElse(api.LearningPathTagsDTO(Seq(), DefaultLanguage)) val introduction = findByLanguageOrBestEffort(getApiIntroduction(learningpath.learningsteps.getOrElse(Seq.empty)), AllLanguages) - .getOrElse(api.Introduction("", DefaultLanguage)) + .getOrElse(api.IntroductionDTO("", DefaultLanguage)) val message = learningpath.message.filter(_ => learningpath.canEdit(user)).map(_.message) Success( - api.LearningPathSummaryV2( + api.LearningPathSummaryV2DTO( learningpath.id.get, revision = learningpath.revision, title, @@ -499,13 +499,13 @@ trait ConverterService { language: String, fallback: Boolean, user: CombinedUser - ): Try[api.LearningStepV2] = { + ): Try[api.LearningStepV2DTO] = { val supportedLanguages = ls.supportedLanguages if (languageIsSupported(supportedLanguages, language) || fallback) { val title = findByLanguageOrBestEffort(ls.title, language) .map(asApiTitle) - .getOrElse(api.Title("", DefaultLanguage)) + .getOrElse(api.TitleDTO("", DefaultLanguage)) val introduction = findByLanguageOrBestEffort(ls.introduction, language) .map(asApiIntroduction) @@ -517,7 +517,7 @@ trait ConverterService { .map(createEmbedUrl) Success( - api.LearningStepV2( + api.LearningStepV2DTO( ls.id.get, ls.revision.get, ls.seqNo, @@ -547,9 +547,9 @@ trait ConverterService { ls: LearningStep, lp: LearningPath, language: String - ): Option[api.LearningStepSummaryV2] = { + ): Option[api.LearningStepSummaryV2DTO] = { findByLanguageOrBestEffort(ls.title, language).map(title => - api.LearningStepSummaryV2( + api.LearningStepSummaryV2DTO( ls.id.get, ls.seqNo, asApiTitle(title), @@ -564,7 +564,7 @@ trait ConverterService { learningPath: LearningPath, language: String, fallback: Boolean - ): Try[api.LearningStepContainerSummary] = { + ): Try[api.LearningStepContainerSummaryDTO] = { val learningSteps = learningPathRepository .learningStepsFor(learningPath.id.get) .filter(_.status == status) @@ -578,7 +578,7 @@ trait ConverterService { else language Success( - api.LearningStepContainerSummary( + api.LearningStepContainerSummaryDTO( searchLanguage, learningSteps .flatMap(ls => @@ -596,10 +596,10 @@ trait ConverterService { } def asApiLearningPathTagsSummary( - allTags: List[api.LearningPathTags], + allTags: List[api.LearningPathTagsDTO], language: String, fallback: Boolean - ): Option[api.LearningPathTagsSummary] = { + ): Option[api.LearningPathTagsSummaryDTO] = { val supportedLanguages = allTags.map(_.language).distinct if (languageIsSupported(supportedLanguages, language) || fallback) { @@ -609,7 +609,7 @@ trait ConverterService { .flatMap(_.tags) Some( - api.LearningPathTagsSummary( + api.LearningPathTagsSummaryDTO( searchLanguage, supportedLanguages, tags @@ -619,23 +619,23 @@ trait ConverterService { None } - private def asApiTitle(title: common.Title): api.Title = { - api.Title(title.title, title.language) + private def asApiTitle(title: common.Title): api.TitleDTO = { + api.TitleDTO(title.title, title.language) } - private def asApiIntroduction(introduction: Introduction): api.Introduction = { - api.Introduction(introduction.introduction, introduction.language) + private def asApiIntroduction(introduction: Introduction): api.IntroductionDTO = { + api.IntroductionDTO(introduction.introduction, introduction.language) } - private def asApiDescription(description: Description): api.Description = { - api.Description(description.description, description.language) + private def asApiDescription(description: Description): api.DescriptionDTO = { + api.DescriptionDTO(description.description, description.language) } - private def asApiEmbedUrlV2(embedUrl: EmbedUrl): api.EmbedUrlV2 = { - api.EmbedUrlV2(embedUrl.url, embedUrl.embedType.toString) + private def asApiEmbedUrlV2(embedUrl: EmbedUrl): api.EmbedUrlV2DTO = { + api.EmbedUrlV2DTO(embedUrl.url, embedUrl.embedType.toString) } - def asDomainEmbedUrl(embedUrl: api.EmbedUrlV2, language: String): Try[EmbedUrl] = { + def asDomainEmbedUrl(embedUrl: api.EmbedUrlV2DTO, language: String): Try[EmbedUrl] = { val hostOpt = embedUrl.url.hostOption hostOpt match { case Some(host) if NdlaFrontendHostNames.contains(host.toString) => @@ -674,7 +674,7 @@ trait ConverterService { s"${ApplicationUrl.get}${lp.id.get}" } - def createUrlToLearningPath(lp: api.LearningPathV2): String = { + def createUrlToLearningPath(lp: api.LearningPathV2DTO): String = { s"${ApplicationUrl.get}${lp.id}" } @@ -685,7 +685,7 @@ trait ConverterService { s"${ExternalApiUrls.ImageApiRawUrl}/id/$imageId" } - private def createEmbedUrl(embedUrlOrPath: EmbedUrlV2): EmbedUrlV2 = { + private def createEmbedUrl(embedUrlOrPath: EmbedUrlV2DTO): EmbedUrlV2DTO = { embedUrlOrPath.url.hostOption match { case Some(_) => embedUrlOrPath case None => diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ReadService.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ReadService.scala index c1ad9fea60..12b742ed23 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ReadService.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/ReadService.scala @@ -31,15 +31,15 @@ trait ReadService { class ReadService { - def tags: List[LearningPathTags] = { - learningPathRepository.allPublishedTags.map(tags => LearningPathTags(tags.tags, tags.language)) + def tags: List[LearningPathTagsDTO] = { + learningPathRepository.allPublishedTags.map(tags => LearningPathTagsDTO(tags.tags, tags.language)) } - def contributors: List[commonApi.Author] = { - learningPathRepository.allPublishedContributors.map(author => commonApi.Author(author.`type`, author.name)) + def contributors: List[commonApi.AuthorDTO] = { + learningPathRepository.allPublishedContributors.map(author => commonApi.AuthorDTO(author.`type`, author.name)) } - def withOwnerV2(user: CombinedUserRequired, language: String, fallback: Boolean): List[LearningPathV2] = { + def withOwnerV2(user: CombinedUserRequired, language: String, fallback: Boolean): List[LearningPathV2DTO] = { learningPathRepository .withOwner(user.id) .flatMap(value => converterService.asApiLearningpathV2(value, language, fallback, user).toOption) @@ -52,7 +52,7 @@ trait ReadService { page: Int, pageSize: Int, userInfo: CombinedUser - ): Try[Seq[LearningPathV2]] = { + ): Try[Seq[LearningPathV2DTO]] = { if (ids.isEmpty) Failure(ValidationException("ids", "Query parameter 'ids' is missing")) else { val offset = (page - 1) * pageSize @@ -68,14 +68,14 @@ trait ReadService { language: String, fallback: Boolean, user: CombinedUser - ): Try[LearningPathV2] = { + ): Try[LearningPathV2DTO] = { withIdAndAccessGranted(learningPathId, user).flatMap(lp => converterService.asApiLearningpathV2(lp, language, fallback, user) ) } - def statusFor(learningPathId: Long, user: CombinedUser): Try[LearningPathStatus] = { - withIdAndAccessGranted(learningPathId, user).map(lp => LearningPathStatus(lp.status.toString)) + def statusFor(learningPathId: Long, user: CombinedUser): Try[LearningPathStatusDTO] = { + withIdAndAccessGranted(learningPathId, user).map(lp => LearningPathStatusDTO(lp.status.toString)) } def learningStepStatusForV2( @@ -84,9 +84,9 @@ trait ReadService { language: String, fallback: Boolean, user: CombinedUser - ): Try[LearningStepStatus] = { + ): Try[LearningStepStatusDTO] = { learningstepV2For(learningPathId, learningStepId, language, fallback, user).map(ls => - LearningStepStatus(ls.status) + LearningStepStatusDTO(ls.status) ) } @@ -96,7 +96,7 @@ trait ReadService { language: String, fallback: Boolean, user: CombinedUser - ): Try[LearningStepContainerSummary] = { + ): Try[LearningStepContainerSummaryDTO] = { withIdAndAccessGranted(learningPathId, user) match { case Success(lp) => converterService.asLearningStepContainerSummary(status, lp, language, fallback) case Failure(ex) => Failure(ex) @@ -109,7 +109,7 @@ trait ReadService { language: String, fallback: Boolean, user: CombinedUser - ): Try[LearningStepV2] = { + ): Try[LearningStepV2DTO] = { withIdAndAccessGranted(learningPathId, user) match { case Success(lp) => learningPathRepository @@ -136,7 +136,11 @@ trait ReadService { } } - def getLearningPathDomainDump(pageNo: Int, pageSize: Int, onlyIncludePublished: Boolean): LearningPathDomainDump = { + def getLearningPathDomainDump( + pageNo: Int, + pageSize: Int, + onlyIncludePublished: Boolean + ): LearningPathDomainDumpDTO = { val (safePageNo, safePageSize) = (max(pageNo, 1), max(pageSize, 0)) val resultFunc = @@ -149,10 +153,10 @@ trait ReadService { val results = resultFunc(safePageSize, (safePageNo - 1) * safePageSize) - LearningPathDomainDump(count, safePageNo, safePageSize, results) + LearningPathDomainDumpDTO(count, safePageNo, safePageSize, results) } - def learningPathWithStatus(status: String, user: CombinedUser): Try[List[LearningPathV2]] = { + def learningPathWithStatus(status: String, user: CombinedUser): Try[List[LearningPathV2DTO]] = { if (user.isAdmin) { learningpath.LearningPathStatus.valueOf(status) match { case Some(ps) => diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/UpdateService.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/UpdateService.scala index e081ea6d7c..800145e99a 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/UpdateService.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/UpdateService.scala @@ -43,7 +43,7 @@ trait UpdateService { language: String, fallback: Boolean, userInfo: CombinedUser - ): Try[LearningPathV2] = { + ): Try[LearningPathV2DTO] = { writeOrAccessDenied(userInfo.isWriter) { readService.withIdAndAccessGranted(pathId, userInfo) match { case Failure(ex) => Failure(ex) @@ -69,7 +69,11 @@ trait UpdateService { if (willExecute) w else Failure(AccessDeniedException(reason)) - def newFromExistingV2(id: Long, newLearningPath: NewCopyLearningPathV2, owner: CombinedUser): Try[LearningPathV2] = + def newFromExistingV2( + id: Long, + newLearningPath: NewCopyLearningPathV2DTO, + owner: CombinedUser + ): Try[LearningPathV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { learningPathRepository.withId(id).map(_.isOwnerOrPublic(owner)) match { case None => Failure(NotFoundException("Could not find learningpath to copy.")) @@ -88,7 +92,7 @@ trait UpdateService { } } - def addLearningPathV2(newLearningPath: NewLearningPathV2, owner: CombinedUser): Try[LearningPathV2] = + def addLearningPathV2(newLearningPath: NewLearningPathV2DTO, owner: CombinedUser): Try[LearningPathV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { for { learningPath <- converterService.newLearningPath(newLearningPath, owner) @@ -100,9 +104,9 @@ trait UpdateService { def updateLearningPathV2( id: Long, - learningPathToUpdate: UpdatedLearningPathV2, + learningPathToUpdate: UpdatedLearningPathV2DTO, owner: CombinedUser - ): Try[LearningPathV2] = writeDuringWriteRestrictionOrAccessDenied(owner) { + ): Try[LearningPathV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { learningPathValidator.validate(learningPathToUpdate) withId(id).flatMap(_.canEditLearningpath(owner)) match { @@ -145,7 +149,7 @@ trait UpdateService { owner: CombinedUserRequired, language: String, message: Option[String] = None - ): Try[LearningPathV2] = + ): Try[LearningPathV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { withId(learningPathId, includeDeleted = true) .flatMap(_.canSetStatus(status, owner)) @@ -205,9 +209,9 @@ trait UpdateService { def addLearningStepV2( learningPathId: Long, - newLearningStep: NewLearningStepV2, + newLearningStep: NewLearningStepV2DTO, owner: CombinedUserRequired - ): Try[LearningStepV2] = writeDuringWriteRestrictionOrAccessDenied(owner) { + ): Try[LearningStepV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { optimisticLockRetries(10) { withId(learningPathId).flatMap(_.canEditLearningpath(owner)) match { case Failure(ex) => Failure(ex) @@ -247,9 +251,9 @@ trait UpdateService { def updateLearningStepV2( learningPathId: Long, learningStepId: Long, - learningStepToUpdate: UpdatedLearningStepV2, + learningStepToUpdate: UpdatedLearningStepV2DTO, owner: CombinedUserRequired - ): Try[LearningStepV2] = writeDuringWriteRestrictionOrAccessDenied(owner) { + ): Try[LearningStepV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { withId(learningPathId).flatMap(_.canEditLearningpath(owner)) match { case Failure(ex) => Failure(ex) case Success(learningPath) => @@ -301,7 +305,7 @@ trait UpdateService { learningStepId: Long, newStatus: StepStatus, owner: CombinedUserRequired - ): Try[LearningStepV2] = + ): Try[LearningStepV2DTO] = writeDuringWriteRestrictionOrAccessDenied(owner) { withId(learningPathId).flatMap(_.canEditLearningpath(owner)) match { case Failure(ex) => Failure(ex) @@ -364,7 +368,7 @@ trait UpdateService { learningStepId: Long, seqNo: Int, owner: CombinedUser - ): Try[LearningStepSeqNo] = { + ): Try[LearningStepSeqNoDTO] = { writeDuringWriteRestrictionOrAccessDenied(owner) { optimisticLockRetries(10) { withId(learningPathId).flatMap(_.canEditLearningpath(owner)) match { @@ -393,7 +397,7 @@ trait UpdateService { }) } - Success(LearningStepSeqNo(seqNo)) + Success(LearningStepSeqNoDTO(seqNo)) } } } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchConverterServiceComponent.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchConverterServiceComponent.scala index b0b4878f41..509574001a 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchConverterServiceComponent.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchConverterServiceComponent.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.domain.learningpath.{LearningPath, LearningStep, Ste import no.ndla.language.Language.{findByLanguageOrBestEffort, getSupportedLanguages} import no.ndla.learningpathapi.Props import no.ndla.learningpathapi.model.* -import no.ndla.learningpathapi.model.api.{LearningPathSummaryV2, SearchResultV2} +import no.ndla.learningpathapi.model.api.{LearningPathSummaryV2DTO, SearchResultV2DTO} import no.ndla.learningpathapi.model.domain.* import no.ndla.learningpathapi.model.search.* import no.ndla.learningpathapi.service.ConverterService @@ -32,27 +32,27 @@ trait SearchConverterServiceComponent { def asApiLearningPathSummaryV2( searchableLearningPath: SearchableLearningPath, language: String - ): LearningPathSummaryV2 = { - val titles = searchableLearningPath.titles.languageValues.map(lv => api.Title(lv.value, lv.language)) + ): LearningPathSummaryV2DTO = { + val titles = searchableLearningPath.titles.languageValues.map(lv => api.TitleDTO(lv.value, lv.language)) val descriptions = - searchableLearningPath.descriptions.languageValues.map(lv => api.Description(lv.value, lv.language)) + searchableLearningPath.descriptions.languageValues.map(lv => api.DescriptionDTO(lv.value, lv.language)) val introductions = searchableLearningPath.learningsteps.find(_.stepType == StepType.INTRODUCTION.toString) match { - case Some(step) => step.descriptions.languageValues.map(lv => api.Introduction(lv.value, lv.language)) + case Some(step) => step.descriptions.languageValues.map(lv => api.IntroductionDTO(lv.value, lv.language)) case _ => Seq.empty } - val tags = searchableLearningPath.tags.languageValues.map(lv => api.LearningPathTags(lv.value, lv.language)) + val tags = searchableLearningPath.tags.languageValues.map(lv => api.LearningPathTagsDTO(lv.value, lv.language)) val supportedLanguages = getSupportedLanguages(titles, descriptions, introductions, tags) - LearningPathSummaryV2( + LearningPathSummaryV2DTO( searchableLearningPath.id, revision = None, findByLanguageOrBestEffort(titles, language) - .getOrElse(api.Title("", DefaultLanguage)), + .getOrElse(api.TitleDTO("", DefaultLanguage)), findByLanguageOrBestEffort(descriptions, language) - .getOrElse(api.Description("", DefaultLanguage)), + .getOrElse(api.DescriptionDTO("", DefaultLanguage)), findByLanguageOrBestEffort(introductions, language) - .getOrElse(api.Introduction("", DefaultLanguage)), + .getOrElse(api.IntroductionDTO("", DefaultLanguage)), createUrlToLearningPath(searchableLearningPath.id), searchableLearningPath.coverPhotoUrl, searchableLearningPath.duration, @@ -60,7 +60,7 @@ trait SearchConverterServiceComponent { searchableLearningPath.created, searchableLearningPath.lastUpdated, findByLanguageOrBestEffort(tags, language) - .getOrElse(api.LearningPathTags(Seq(), DefaultLanguage)), + .getOrElse(api.LearningPathTagsDTO(Seq(), DefaultLanguage)), searchableLearningPath.copyright, supportedLanguages, searchableLearningPath.isBasedOn, @@ -138,8 +138,8 @@ trait SearchConverterServiceComponent { } } - def asApiSearchResult(searchResult: SearchResult): SearchResultV2 = - SearchResultV2( + def asApiSearchResult(searchResult: SearchResult): SearchResultV2DTO = + SearchResultV2DTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchService.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchService.scala index 617c8b8e1a..61f40402a1 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchService.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/service/search/SearchService.scala @@ -21,7 +21,7 @@ import no.ndla.common.model.domain.learningpath.LearningPathStatus import no.ndla.language.Language.{AllLanguages, NoLanguage} import no.ndla.language.model.Iso639 import no.ndla.learningpathapi.Props -import no.ndla.learningpathapi.model.api.{ErrorHandling, LearningPathSummaryV2} +import no.ndla.learningpathapi.model.api.{ErrorHandling, LearningPathSummaryV2DTO} import no.ndla.learningpathapi.model.domain.* import no.ndla.learningpathapi.model.search.SearchableLearningPath import no.ndla.search.{Elastic4sClient, IndexNotFoundException, NdlaSearchException} @@ -55,7 +55,7 @@ trait SearchService extends StrictLogging { ) }) - private def getHitsV2(response: SearchResponse, language: String): Seq[LearningPathSummaryV2] = { + private def getHitsV2(response: SearchResponse, language: String): Seq[LearningPathSummaryV2DTO] = { response.totalHits match { case count if count > 0 => val resultArray = response.hits.hits.toList @@ -75,7 +75,7 @@ trait SearchService extends StrictLogging { } } - private def hitAsLearningPathSummaryV2(hitString: String, language: String): LearningPathSummaryV2 = { + private def hitAsLearningPathSummaryV2(hitString: String, language: String): LearningPathSummaryV2DTO = { val searchable = CirceUtil.unsafeParseAs[SearchableLearningPath](hitString) searchConverterService.asApiLearningPathSummaryV2(searchable, language) } diff --git a/learningpath-api/src/main/scala/no/ndla/learningpathapi/validation/LearningPathValidator.scala b/learningpath-api/src/main/scala/no/ndla/learningpathapi/validation/LearningPathValidator.scala index dbba12248f..7d735501a6 100644 --- a/learningpath-api/src/main/scala/no/ndla/learningpathapi/validation/LearningPathValidator.scala +++ b/learningpath-api/src/main/scala/no/ndla/learningpathapi/validation/LearningPathValidator.scala @@ -12,7 +12,7 @@ import io.lemonlabs.uri.Url import no.ndla.common.errors.{ValidationException, ValidationMessage} import no.ndla.common.model.domain.{Author, Tag} import no.ndla.common.model.domain.learningpath.{Description, LearningPath, LearningpathCopyright} -import no.ndla.learningpathapi.model.api.UpdatedLearningPathV2 +import no.ndla.learningpathapi.model.api.UpdatedLearningPathV2DTO import no.ndla.mapping.License.getLicense trait LearningPathValidator { @@ -37,7 +37,7 @@ trait LearningPathValidator { } } - def validate(updateLearningPath: UpdatedLearningPathV2): Unit = { + def validate(updateLearningPath: UpdatedLearningPathV2DTO): Unit = { languageValidator.validate("language", updateLearningPath.language, allowUnknownLanguage = true) match { case None => case Some(validationMessage) => diff --git a/learningpath-api/src/test/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2Test.scala b/learningpath-api/src/test/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2Test.scala index d6cd4cb404..614403d5d1 100644 --- a/learningpath-api/src/test/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2Test.scala +++ b/learningpath-api/src/test/scala/no/ndla/learningpathapi/controller/LearningpathControllerV2Test.scala @@ -12,7 +12,7 @@ import no.ndla.common.CirceUtil import no.ndla.common.model.{NDLADate, api as commonApi} import no.ndla.learningpathapi.TestData.searchSettings import no.ndla.learningpathapi.integration.Node -import no.ndla.learningpathapi.model.api.{LearningPathSummaryV2, SearchResultV2} +import no.ndla.learningpathapi.model.api.{LearningPathSummaryV2DTO, SearchResultV2DTO} import no.ndla.learningpathapi.model.domain.* import no.ndla.learningpathapi.model.{api, domain} import no.ndla.learningpathapi.{TestData, TestEnvironment, UnitSuite} @@ -36,21 +36,21 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T when(searchConverterService.asApiSearchResult(any)).thenCallRealMethod() } - val copyright: api.Copyright = api.Copyright(commonApi.License("by-sa", None, None), List()) + val copyright: api.CopyrightDTO = api.CopyrightDTO(commonApi.LicenseDTO("by-sa", None, None), List()) - val DefaultLearningPathSummary: LearningPathSummaryV2 = api.LearningPathSummaryV2( + val DefaultLearningPathSummary: LearningPathSummaryV2DTO = api.LearningPathSummaryV2DTO( 1, None, - api.Title("Tittel", "nb"), - api.Description("", "nb"), - api.Introduction("", "nb"), + api.TitleDTO("Tittel", "nb"), + api.DescriptionDTO("", "nb"), + api.IntroductionDTO("", "nb"), "", None, None, "", NDLADate.now(), NDLADate.now(), - api.LearningPathTags(Seq(), "nb"), + api.LearningPathTagsDTO(Seq(), "nb"), copyright, List("nb"), None, @@ -67,7 +67,7 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T val verificationStatus = "EXTERNAL" val result = SearchResult(1, Some(1), 1, language, Seq(DefaultLearningPathSummary), None) - val apiResult = SearchResultV2(1, Some(1), 1, language, Seq(DefaultLearningPathSummary)) + val apiResult = SearchResultV2DTO(1, Some(1), 1, language, Seq(DefaultLearningPathSummary)) when(searchConverterService.asApiSearchResult(result)).thenReturn(apiResult) val expectedSettings = searchSettings.copy( @@ -98,8 +98,8 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T quickRequest.get(uri"http://localhost:$serverPort/learningpath-api/v2/learningpaths?$queryParams") ) res.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2](res.body) - convertedBody.results.head.title should equal(api.Title("Tittel", "nb")) + val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2DTO](res.body) + convertedBody.results.head.title should equal(api.TitleDTO("Tittel", "nb")) } test("That GET / will handle all empty query-params as missing query params") { @@ -110,7 +110,7 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T val ids = "1,2" val result = SearchResult(-1, Some(1), 1, "nb", Seq(DefaultLearningPathSummary), None) - val apiResult = SearchResultV2(-1, Some(1), 1, "nb", Seq(DefaultLearningPathSummary)) + val apiResult = SearchResultV2DTO(-1, Some(1), 1, "nb", Seq(DefaultLearningPathSummary)) when(searchConverterService.asApiSearchResult(result)).thenReturn(apiResult) when(searchService.matchingQuery(any[SearchSettings])).thenReturn(Success(result)) @@ -126,7 +126,7 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T quickRequest.get(uri"http://localhost:$serverPort/learningpath-api/v2/learningpaths?$queryParams") ) res.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2](res.body) + val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2DTO](res.body) convertedBody.totalCount should be(-1) } @@ -139,7 +139,7 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T val pageSize = 111 val result = SearchResult(1, Some(page), pageSize, language, Seq(DefaultLearningPathSummary), None) - val apiResult = SearchResultV2(1, Some(page), pageSize, language, Seq(DefaultLearningPathSummary)) + val apiResult = SearchResultV2DTO(1, Some(page), pageSize, language, Seq(DefaultLearningPathSummary)) when(searchConverterService.asApiSearchResult(result)).thenReturn(apiResult) val expectedSettings = searchSettings.copy( @@ -161,27 +161,27 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T .body(inputBody) ) res.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2](res.body) - convertedBody.results.head.title should equal(api.Title("Tittel", "nb")) + val convertedBody = CirceUtil.unsafeParseAs[api.SearchResultV2DTO](res.body) + convertedBody.results.head.title should equal(api.TitleDTO("Tittel", "nb")) } test("That GET /licenses with filter sat to by only returns creative common licenses") { val creativeCommonlicenses = getLicenses .filter(_.license.toString.startsWith("by")) - .map(l => commonApi.License(l.license.toString, Option(l.description), l.url)) + .map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)) .toSet val res = simpleHttpClient.send( quickRequest .get(uri"http://localhost:$serverPort/learningpath-api/v2/learningpaths/licenses/?filter=by") ) res.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.License]](res.body) + val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.LicenseDTO]](res.body) convertedBody should equal(creativeCommonlicenses) } test("That GET /licenses with filter not specified returns all licenses") { val allLicenses = getLicenses - .map(l => commonApi.License(l.license.toString, Option(l.description), l.url)) + .map(l => commonApi.LicenseDTO(l.license.toString, Option(l.description), l.url)) .toSet val res = simpleHttpClient.send( @@ -189,7 +189,7 @@ class LearningpathControllerV2Test extends UnitSuite with TestEnvironment with T .get(uri"http://localhost:$serverPort/learningpath-api/v2/learningpaths/licenses/") ) res.code.code should be(200) - val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.License]](res.body) + val convertedBody = CirceUtil.unsafeParseAs[Set[commonApi.LicenseDTO]](res.body) convertedBody should equal(allLicenses) } diff --git a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/ConverterServiceTest.scala b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/ConverterServiceTest.scala index d7050c07f0..0db88c0bf8 100644 --- a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/ConverterServiceTest.scala +++ b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/ConverterServiceTest.scala @@ -23,7 +23,12 @@ import no.ndla.common.model.domain.learningpath.{ import no.ndla.common.model.domain.{Tag, Title} import no.ndla.common.model.{NDLADate, api as commonApi} import no.ndla.learningpathapi.model.api -import no.ndla.learningpathapi.model.api.{CoverPhoto, NewCopyLearningPathV2, NewLearningPathV2, NewLearningStepV2} +import no.ndla.learningpathapi.model.api.{ + CoverPhotoDTO, + NewCopyLearningPathV2DTO, + NewLearningPathV2DTO, + NewLearningStepV2DTO +} import no.ndla.learningpathapi.{TestData, UnitSuite, UnitTestEnvironment} import no.ndla.mapping.License.CC_BY import no.ndla.network.ApplicationUrl @@ -38,17 +43,17 @@ import scala.util.{Failure, Success} class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { import props.DefaultLanguage - val clinton: commonApi.Author = commonApi.Author("author", "Crooked Hillary") - val license: commonApi.License = - commonApi.License("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) - val copyright: api.Copyright = api.Copyright(license, List(clinton)) + val clinton: commonApi.AuthorDTO = commonApi.AuthorDTO("author", "Crooked Hillary") + val license: commonApi.LicenseDTO = + commonApi.LicenseDTO("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) + val copyright: api.CopyrightDTO = api.CopyrightDTO(license, List(clinton)) - val apiLearningPath: api.LearningPathV2 = api.LearningPathV2( + val apiLearningPath: api.LearningPathV2DTO = api.LearningPathV2DTO( 1, 1, None, - api.Title("Tittel", "nb"), - api.Description("Beskrivelse", "nb"), + api.TitleDTO("Tittel", "nb"), + api.DescriptionDTO("Beskrivelse", "nb"), "", List(), "", @@ -58,7 +63,7 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { "CREATED_BY_NDLA", NDLADate.now(), NDLADate.now(), - api.LearningPathTags(List(), "nb"), + api.LearningPathTagsDTO(List(), "nb"), copyright, true, List("nb"), @@ -82,7 +87,7 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { StepType.INTRODUCTION, None ) - val apiTags: List[api.LearningPathTags] = List(api.LearningPathTags(Seq("tag"), DefaultLanguage)) + val apiTags: List[api.LearningPathTagsDTO] = List(api.LearningPathTagsDTO(Seq("tag"), DefaultLanguage)) val randomDate: NDLADate = NDLADate.now() var service: ConverterService = _ @@ -112,12 +117,12 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningpathV2 converts domain to api LearningPathV2") { val expected = Success( - api.LearningPathV2( + api.LearningPathV2DTO( 1, 1, None, - api.Title("tittel", DefaultLanguage), - api.Description("deskripsjon", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), + api.DescriptionDTO("deskripsjon", DefaultLanguage), "null1", List.empty, "null1/learningsteps", @@ -127,9 +132,9 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { LearningPathVerificationStatus.CREATED_BY_NDLA.toString, randomDate, randomDate, - api.LearningPathTags(Seq("tag"), DefaultLanguage), - api.Copyright( - commonApi.License( + api.LearningPathTagsDTO(Seq("tag"), DefaultLanguage), + api.CopyrightDTO( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -164,12 +169,12 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningpathV2 converts domain to api LearningPathV2 with fallback if true") { val expected = Success( - api.LearningPathV2( + api.LearningPathV2DTO( 1, 1, None, - api.Title("tittel", DefaultLanguage), - api.Description("deskripsjon", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), + api.DescriptionDTO("deskripsjon", DefaultLanguage), "null1", List.empty, "null1/learningsteps", @@ -179,9 +184,9 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { LearningPathVerificationStatus.CREATED_BY_NDLA.toString, randomDate, randomDate, - api.LearningPathTags(Seq("tag"), DefaultLanguage), - api.Copyright( - commonApi.License( + api.LearningPathTagsDTO(Seq("tag"), DefaultLanguage), + api.CopyrightDTO( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -205,21 +210,21 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningpathSummaryV2 converts domain to api LearningpathSummaryV2") { val expected = Success( - api.LearningPathSummaryV2( + api.LearningPathSummaryV2DTO( 1, Some(1), - api.Title("tittel", DefaultLanguage), - api.Description("deskripsjon", DefaultLanguage), - api.Introduction("", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), + api.DescriptionDTO("deskripsjon", DefaultLanguage), + api.IntroductionDTO("", DefaultLanguage), "null1", None, Some(60), LearningPathStatus.PRIVATE.toString, randomDate, randomDate, - api.LearningPathTags(Seq("tag"), DefaultLanguage), - api.Copyright( - commonApi.License( + api.LearningPathTagsDTO(Seq("tag"), DefaultLanguage), + api.CopyrightDTO( + commonApi.LicenseDTO( CC_BY.toString, Some("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -239,13 +244,13 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningStepV2 converts domain learningstep to api LearningStepV2") { val learningstep = Success( - api.LearningStepV2( + api.LearningStepV2DTO( 1, 1, 1, - api.Title("tittel", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), None, - Some(api.Description("deskripsjon", DefaultLanguage)), + Some(api.DescriptionDTO("deskripsjon", DefaultLanguage)), None, showTitle = false, "INTRODUCTION", @@ -285,13 +290,13 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { "asApiLearningStepV2 converts domain learningstep to api LearningStepV2 if fallback is true and language undefined" ) { val learningstep = Success( - api.LearningStepV2( + api.LearningStepV2DTO( 1, 1, 1, - api.Title("tittel", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), None, - Some(api.Description("deskripsjon", DefaultLanguage)), + Some(api.DescriptionDTO("deskripsjon", DefaultLanguage)), None, showTitle = false, "INTRODUCTION", @@ -313,10 +318,10 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningStepSummaryV2 converts domain learningstep to LearningStepSummaryV2") { val expected = Some( - api.LearningStepSummaryV2( + api.LearningStepSummaryV2DTO( 1, 1, - api.Title("tittel", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), "INTRODUCTION", "null1/learningsteps/1" ) @@ -327,10 +332,10 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningStepSummaryV2 returns what we have when not supported language is given") { val expected = Some( - api.LearningStepSummaryV2( + api.LearningStepSummaryV2DTO( 1, 1, - api.Title("tittel", DefaultLanguage), + api.TitleDTO("tittel", DefaultLanguage), "INTRODUCTION", "null1/learningsteps/1" ) @@ -343,7 +348,7 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLearningPathTagsSummary converts api LearningPathTags to api LearningPathTagsSummary") { val expected = - Some(api.LearningPathTagsSummary(DefaultLanguage, Seq(DefaultLanguage), Seq("tag"))) + Some(api.LearningPathTagsSummaryDTO(DefaultLanguage, Seq(DefaultLanguage), Seq("tag"))) service.asApiLearningPathTagsSummary(apiTags, DefaultLanguage, false) should equal(expected) } @@ -355,7 +360,7 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { "asApiLearningPathTagsSummary converts api LearningPathTags to api LearningPathTagsSummary if language is undefined and fallback is true" ) { val expected = - Some(api.LearningPathTagsSummary(DefaultLanguage, Seq(DefaultLanguage), Seq("tag"))) + Some(api.LearningPathTagsSummaryDTO(DefaultLanguage, Seq(DefaultLanguage), Seq("tag"))) service.asApiLearningPathTagsSummary(apiTags, "hurr durr I'm a language", true) should equal(expected) } @@ -403,7 +408,7 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asApiLicense returns a License object for a given valid license") { service.asApiLicense("CC-BY-4.0") should equal( - commonApi.License( + commonApi.LicenseDTO( CC_BY.toString, Option("Creative Commons Attribution 4.0 International"), Some("https://creativecommons.org/licenses/by/4.0/") @@ -412,11 +417,11 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { } test("asApiLicense returns a default license object for an invalid license") { - service.asApiLicense("invalid") should equal(commonApi.License("invalid", Option("Invalid license"), None)) + service.asApiLicense("invalid") should equal(commonApi.LicenseDTO("invalid", Option("Invalid license"), None)) } test("asEmbedUrl returns embedUrl if embedType is oembed") { - service.asEmbedUrlV2(api.EmbedUrlV2("http://test.no/2/oembed/", "oembed"), "nb") should equal( + service.asEmbedUrlV2(api.EmbedUrlV2DTO("http://test.no/2/oembed/", "oembed"), "nb") should equal( EmbedUrl("http://test.no/2/oembed/", "nb", EmbedType.OEmbed) ) } @@ -424,14 +429,14 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asEmbedUrl throws error if an not allowed value for embedType is used") { assertResult("Validation Error") { intercept[ValidationException] { - service.asEmbedUrlV2(api.EmbedUrlV2("http://test.no/2/oembed/", "test"), "nb") + service.asEmbedUrlV2(api.EmbedUrlV2DTO("http://test.no/2/oembed/", "test"), "nb") }.getMessage } } test("asCoverPhoto converts an image id to CoverPhoto") { val expectedResult = - CoverPhoto( + CoverPhotoDTO( s"${props.Domain}/image-api/raw/id/1", s"${props.Domain}/image-api/v3/images/1" ) @@ -442,12 +447,12 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asDomainEmbed should only use context path if hostname is ndla-frontend but full url when not") { val url = "https://ndla.no/subjects/resource:1234?a=test" when(oembedProxyClient.getIframeUrl(eqTo(url))).thenReturn(Success(url)) - service.asDomainEmbedUrl(api.EmbedUrlV2(url, "oembed"), "nb") should equal( + service.asDomainEmbedUrl(api.EmbedUrlV2DTO(url, "oembed"), "nb") should equal( Success(EmbedUrl(s"/subjects/resource:1234?a=test", "nb", EmbedType.IFrame)) ) val externalUrl = "https://youtube.com/watch?v=8992BFHks" - service.asDomainEmbedUrl(api.EmbedUrlV2(externalUrl, "oembed"), "nb") should equal( + service.asDomainEmbedUrl(api.EmbedUrlV2DTO(externalUrl, "oembed"), "nb") should equal( Success(EmbedUrl(externalUrl, "nb", EmbedType.OEmbed)) ) } @@ -473,13 +478,13 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { } test("New learningPaths get correct verification") { - val apiRubio = commonApi.Author("author", "Little Marco") + val apiRubio = commonApi.AuthorDTO("author", "Little Marco") val apiLicense = - commonApi.License("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) - val apiCopyright = api.Copyright(apiLicense, List(apiRubio)) + commonApi.LicenseDTO("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) + val apiCopyright = api.CopyrightDTO(apiLicense, List(apiRubio)) - val newCopyLp = NewCopyLearningPathV2("Tittel", Some("Beskrivelse"), "nb", None, Some(1), None, None) - val newLp = NewLearningPathV2("Tittel", "Beskrivelse", None, Some(1), List(), "nb", apiCopyright) + val newCopyLp = NewCopyLearningPathV2DTO("Tittel", Some("Beskrivelse"), "nb", None, Some(1), None, None) + val newLp = NewLearningPathV2DTO("Tittel", "Beskrivelse", None, Some(1), List(), "nb", apiCopyright) service .newFromExistingLearningPath(domainLearningPath, newCopyLp, TokenUser("Me", Set.empty, None).toCombined) @@ -512,12 +517,12 @@ class ConverterServiceTest extends UnitSuite with UnitTestEnvironment { test("asDomainLearningStep should work with learningpaths no matter the amount of steps") { val newLs = - NewLearningStepV2( + NewLearningStepV2DTO( "Tittel", Some("Beskrivelse"), None, "nb", - Some(api.EmbedUrlV2("", "oembed")), + Some(api.EmbedUrlV2DTO("", "oembed")), true, "TEXT", None diff --git a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/UpdateServiceTest.scala b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/UpdateServiceTest.scala index e493dfb79c..01ab697651 100644 --- a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/UpdateServiceTest.scala +++ b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/UpdateServiceTest.scala @@ -25,11 +25,11 @@ import no.ndla.common.model.domain.learningpath.{ import no.ndla.learningpathapi.* import no.ndla.learningpathapi.model.* import no.ndla.learningpathapi.model.api.{ - NewCopyLearningPathV2, - NewLearningPathV2, - NewLearningStepV2, - UpdatedLearningPathV2, - UpdatedLearningStepV2 + NewCopyLearningPathV2DTO, + NewLearningPathV2DTO, + NewLearningStepV2DTO, + UpdatedLearningPathV2DTO, + UpdatedLearningStepV2DTO } import no.ndla.network.tapir.auth.Permission.LEARNINGPATH_API_ADMIN import no.ndla.network.tapir.auth.TokenUser @@ -37,7 +37,7 @@ import org.mockito.invocation.InvocationOnMock import scalikejdbc.DBSession import scala.util.{Failure, Success} -import no.ndla.learningpathapi.model.api.Copyright +import no.ndla.learningpathapi.model.api.CopyrightDTO import no.ndla.network.model.CombinedUser import org.mockito.ArgumentMatchers.{any, eq as eqTo} import org.mockito.Mockito.{never, times, verify, when} @@ -144,19 +144,28 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { status = StepStatus.ACTIVE ) - val NEW_STEPV2: NewLearningStepV2 = - NewLearningStepV2("Tittel", Some("Beskrivelse"), None, "nb", Some(api.EmbedUrlV2("", "oembed")), true, "TEXT", None) + val NEW_STEPV2: NewLearningStepV2DTO = + NewLearningStepV2DTO( + "Tittel", + Some("Beskrivelse"), + None, + "nb", + Some(api.EmbedUrlV2DTO("", "oembed")), + true, + "TEXT", + None + ) - val UPDATED_STEPV2: UpdatedLearningStepV2 = - UpdatedLearningStepV2(1, Option("Tittel"), None, "nb", Some("Beskrivelse"), None, Some(false), None, None) + val UPDATED_STEPV2: UpdatedLearningStepV2DTO = + UpdatedLearningStepV2DTO(1, Option("Tittel"), None, "nb", Some("Beskrivelse"), None, Some(false), None, None) val rubio: Author = Author("author", "Little Marco") val license = "publicdomain" val copyright: LearningpathCopyright = LearningpathCopyright(license, List(rubio)) - val apiRubio: commonApi.Author = commonApi.Author("author", "Little Marco") - val apiLicense: commonApi.License = - commonApi.License("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) - val apiCopyright: Copyright = api.Copyright(apiLicense, List(apiRubio)) + val apiRubio: commonApi.AuthorDTO = commonApi.AuthorDTO("author", "Little Marco") + val apiLicense: commonApi.LicenseDTO = + commonApi.LicenseDTO("publicdomain", Some("Public Domain"), Some("https://creativecommons.org/about/pdm")) + val apiCopyright: CopyrightDTO = api.CopyrightDTO(apiLicense, List(apiRubio)) val PUBLISHED_LEARNINGPATH: LearningPath = LearningPath( Some(PUBLISHED_ID), @@ -252,16 +261,16 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { copyright, Some(STEP1 :: STEP2 :: STEP3 :: STEP4 :: STEP5 :: STEP6 :: Nil) ) - val NEW_PRIVATE_LEARNINGPATHV2: NewLearningPathV2 = - NewLearningPathV2("Tittel", "Beskrivelse", None, Some(1), List(), "nb", apiCopyright) - val NEW_COPIED_LEARNINGPATHV2: NewCopyLearningPathV2 = - NewCopyLearningPathV2("Tittel", Some("Beskrivelse"), "nb", None, Some(1), None, None) + val NEW_PRIVATE_LEARNINGPATHV2: NewLearningPathV2DTO = + NewLearningPathV2DTO("Tittel", "Beskrivelse", None, Some(1), List(), "nb", apiCopyright) + val NEW_COPIED_LEARNINGPATHV2: NewCopyLearningPathV2DTO = + NewCopyLearningPathV2DTO("Tittel", Some("Beskrivelse"), "nb", None, Some(1), None, None) - val UPDATED_PRIVATE_LEARNINGPATHV2: UpdatedLearningPathV2 = - UpdatedLearningPathV2(1, None, "nb", None, None, Some(1), None, Some(apiCopyright), None) + val UPDATED_PRIVATE_LEARNINGPATHV2: UpdatedLearningPathV2DTO = + UpdatedLearningPathV2DTO(1, None, "nb", None, None, Some(1), None, Some(apiCopyright), None) - val UPDATED_PUBLISHED_LEARNINGPATHV2: UpdatedLearningPathV2 = - UpdatedLearningPathV2(1, None, "nb", None, None, Some(1), None, Some(apiCopyright), None) + val UPDATED_PUBLISHED_LEARNINGPATHV2: UpdatedLearningPathV2DTO = + UpdatedLearningPathV2DTO(1, None, "nb", None, None, Some(1), None, Some(apiCopyright), None) override def beforeEach(): Unit = { service = new UpdateService @@ -1149,7 +1158,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { .thenReturn(learningpathWithUnknownLang) val newCopy = - NewCopyLearningPathV2("hehe", None, "nb", None, None, None, None) + NewCopyLearningPathV2DTO("hehe", None, "nb", None, None, None, None) service .newFromExistingV2(learningpathWithUnknownLang.id.get, newCopy, TokenUser("me", Set.empty, None).toCombined) .isSuccess should be(true) @@ -1178,7 +1187,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { when(clock.now()).thenReturn(newDate) when(learningPathRepository.learningPathsWithIsBasedOn(any[Long])).thenReturn(List.empty) - val updatedLs = UpdatedLearningStepV2(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) + val updatedLs = UpdatedLearningStepV2DTO(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) service.updateLearningStepV2(PUBLISHED_ID, STEP1.id.get, updatedLs, PUBLISHED_OWNER.toCombined) val updatedPath = PUBLISHED_LEARNINGPATH.copy( status = LearningPathStatus.UNLISTED, @@ -1204,7 +1213,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { when(clock.now()).thenReturn(newDate) when(learningPathRepository.learningPathsWithIsBasedOn(any[Long])).thenReturn(List.empty) - val lpToUpdate = UpdatedLearningPathV2(1, Some("YapThisUpdated"), "nb", None, None, None, None, None, None) + val lpToUpdate = UpdatedLearningPathV2DTO(1, Some("YapThisUpdated"), "nb", None, None, None, None, None, None) service.updateLearningPathV2(PUBLISHED_ID, lpToUpdate, PUBLISHED_OWNER.toCombined) val expectedUpdatedPath = PUBLISHED_LEARNINGPATH.copy( @@ -1233,7 +1242,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { when(clock.now()).thenReturn(newDate) when(learningPathRepository.learningPathsWithIsBasedOn(any[Long])).thenReturn(List.empty) - val updatedLs = UpdatedLearningStepV2(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) + val updatedLs = UpdatedLearningStepV2DTO(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) service.updateLearningStepV2(PRIVATE_ID, STEP1.id.get, updatedLs, PRIVATE_OWNER.toCombined) val updatedPath = PRIVATE_LEARNINGPATH.copy( lastUpdated = newDate, @@ -1260,7 +1269,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { ) when(clock.now()).thenReturn(newDate) - val updatedLs = UpdatedLearningStepV2(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) + val updatedLs = UpdatedLearningStepV2DTO(1, Some("Dårlig tittel"), None, "nb", None, None, None, None, None) service.updateLearningStepV2( PUBLISHED_ID, STEP1.id.get, @@ -1396,12 +1405,12 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { verificationStatus = LearningPathVerificationStatus.EXTERNAL, owner = PRIVATE_OWNER.id, lastUpdated = now, - title = Seq(converterService.asTitle(api.Title(titlesToOverride, "nb"))), + title = Seq(converterService.asTitle(api.TitleDTO(titlesToOverride, "nb"))), description = descriptionsToOverride - .map(desc => converterService.asDescription(api.Description(desc, "nb"))) + .map(desc => converterService.asDescription(api.DescriptionDTO(desc, "nb"))) .toSeq, tags = tagsToOverride - .map(tagSeq => converterService.asLearningPathTags(api.LearningPathTags(tagSeq, "nb"))) + .map(tagSeq => converterService.asLearningPathTags(api.LearningPathTagsDTO(tagSeq, "nb"))) .toSeq, coverPhotoId = Some(coverPhotoId), duration = durationOverride @@ -1455,7 +1464,7 @@ class UpdateServiceTest extends UnitSuite with UnitTestEnvironment { when(clock.now()).thenReturn(newDate) when(learningPathRepository.learningPathsWithIsBasedOn(any[Long])).thenReturn(List.empty) - val lpToUpdate = UpdatedLearningPathV2(1, None, "nb", None, None, None, None, None, Some(true)) + val lpToUpdate = UpdatedLearningPathV2DTO(1, None, "nb", None, None, None, None, None, Some(true)) service.updateLearningPathV2(PUBLISHED_ID, lpToUpdate, PUBLISHED_OWNER.toCombined) val expectedUpdatedPath = PUBLISHED_LEARNINGPATH.copy( diff --git a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/search/SearchServiceTest.scala b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/search/SearchServiceTest.scala index 689762e106..d111f0460d 100644 --- a/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/search/SearchServiceTest.scala +++ b/learningpath-api/src/test/scala/no/ndla/learningpathapi/service/search/SearchServiceTest.scala @@ -93,7 +93,7 @@ class SearchServiceTest if (elasticSearchContainer.isSuccess) { searchIndexService.createIndexAndAlias().get - doReturn(commonApi.Author("Forfatter", "En eier"), Nil*).when(converterService).asAuthor(any[NdlaUserName]) + doReturn(commonApi.AuthorDTO("Forfatter", "En eier"), Nil*).when(converterService).asAuthor(any[NdlaUserName]) val today = NDLADate.now() val yesterday = NDLADate.now().minusDays(1) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ArenaController.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ArenaController.scala index fc391b8c13..4371b17268 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ArenaController.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ArenaController.scala @@ -8,24 +8,24 @@ package no.ndla.myndlaapi.controller import io.circe.generic.auto.* -import no.ndla.common.model.api.myndla.{MyNDLAUser, UpdatedMyNDLAUser} -import no.ndla.myndlaapi.model.api.{ArenaUser, PaginatedArenaUsers} +import no.ndla.common.model.api.myndla.{MyNDLAUserDTO, UpdatedMyNDLAUserDTO} +import no.ndla.myndlaapi.model.api.{ArenaUserDTO, PaginatedArenaUsersDTO} import no.ndla.myndlaapi.MyNDLAAuthHelpers import no.ndla.myndlaapi.model.arena.api.{ - Category, - CategorySort, - CategoryWithTopics, - Flag, - NewCategory, - NewFlag, - NewPost, - NewTopic, - PaginatedNewPostNotifications, - PaginatedPosts, - PaginatedTopics, - Post, - Topic, - TopicWithPosts + CategoryDTO, + CategorySortDTO, + CategoryWithTopicsDTO, + FlagDTO, + NewCategoryDTO, + NewFlagDTO, + NewPostDTO, + NewTopicDTO, + PaginatedNewPostNotificationsDTO, + PaginatedPostsDTO, + PaginatedTopicsDTO, + PostDTO, + TopicDTO, + TopicWithPostsDTO } import no.ndla.myndlaapi.service.{ArenaReadService, UserService} import no.ndla.network.clients.FeideApiClient @@ -60,8 +60,8 @@ trait ArenaController { .summary("Get all categories") .description("Get all categories") .in(query[Boolean]("followed").description("Filter on followed categories").default(false)) - .in(query[CategorySort]("sort").description("Sort categories").default(CategorySort.ByRank)) - .out(jsonBody[List[Category]]) + .in(query[CategorySortDTO]("sort").description("Sort categories").default(CategorySortDTO.ByRank)) + .out(jsonBody[List[CategoryDTO]]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -74,7 +74,7 @@ trait ArenaController { .in("categories" / pathCategoryId) .summary("Get single category") .description("Get single category") - .out(jsonBody[CategoryWithTopics]) + .out(jsonBody[CategoryWithTopicsDTO]) .in(queryPage) .in(queryPageSize) .errorOut(errorOutputsFor(401, 403, 404)) @@ -89,7 +89,7 @@ trait ArenaController { .in("categories" / pathCategoryId / "topics") .summary("Get topics for a category") .description("Get topics for a category") - .out(jsonBody[PaginatedTopics]) + .out(jsonBody[PaginatedTopicsDTO]) .in(queryPage) .in(queryPageSize) .errorOut(errorOutputsFor(401, 403, 404)) @@ -106,7 +106,7 @@ trait ArenaController { .summary("Sort categories") .description("Sort categories") .in(jsonBody[List[Long]].description("List of category ids in the order they should be sorted")) - .out(jsonBody[List[Category]]) + .out(jsonBody[List[CategoryDTO]]) .errorOut(errorOutputsFor(401, 403)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { user => @@ -119,7 +119,7 @@ trait ArenaController { .in("topics" / pathTopicId) .summary("Get single topic") .description("Get single topic") - .out(jsonBody[TopicWithPosts]) + .out(jsonBody[TopicWithPostsDTO]) .errorOut(errorOutputsFor(401, 403, 404, 410)) .in(queryPage) .in(queryPageSize) @@ -137,7 +137,7 @@ trait ArenaController { .in(queryPage) .in(queryPageSize) .in(query[Option[Long]]("user-id").description("A users id to filter on")) - .out(jsonBody[PaginatedTopics]) + .out(jsonBody[PaginatedTopicsDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -150,7 +150,7 @@ trait ArenaController { .in("categories" / pathCategoryId / "follow") .summary("Follow category") .description("Follow category") - .out(jsonBody[CategoryWithTopics]) + .out(jsonBody[CategoryWithTopicsDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => categoryId => @@ -161,7 +161,7 @@ trait ArenaController { .in("categories" / pathCategoryId / "unfollow") .summary("Unfollow category") .description("Unfollow category") - .out(jsonBody[CategoryWithTopics]) + .out(jsonBody[CategoryWithTopicsDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => categoryId => @@ -172,7 +172,7 @@ trait ArenaController { .in("topics" / pathTopicId / "follow") .summary("Follow topic") .description("Follow topic") - .out(jsonBody[TopicWithPosts]) + .out(jsonBody[TopicWithPostsDTO]) .errorOut(errorOutputsFor(401, 403, 404, 410)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => topicId => @@ -183,7 +183,7 @@ trait ArenaController { .in("topics" / pathTopicId / "unfollow") .summary("Unfollow topic") .description("Unfollow topic") - .out(jsonBody[TopicWithPosts]) + .out(jsonBody[TopicWithPostsDTO]) .errorOut(errorOutputsFor(401, 403, 404, 410)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => topicId => @@ -194,7 +194,7 @@ trait ArenaController { .in("posts" / pathPostId / "upvote") .summary("Upvote post") .description("Upvote post") - .out(jsonBody[Post]) + .out(jsonBody[PostDTO]) .errorOut(errorOutputsFor(401, 403, 404, 409)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => postId => @@ -205,7 +205,7 @@ trait ArenaController { .in("posts" / pathPostId / "upvote") .summary("Remove upvote from post") .description("Remove a previously cast upvote from a post") - .out(jsonBody[Post]) + .out(jsonBody[PostDTO]) .errorOut(errorOutputsFor(401, 403, 404, 409)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => postId => @@ -216,8 +216,8 @@ trait ArenaController { .in("categories" / pathCategoryId / "topics") .summary("Create new topic") .description("Create new topic") - .in(jsonBody[NewTopic]) - .out(statusCode(StatusCode.Created).and(jsonBody[Topic])) + .in(jsonBody[NewTopicDTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[TopicDTO])) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -230,8 +230,8 @@ trait ArenaController { .in("topics" / pathTopicId) .summary("Edit a topic") .description("Edit a topic") - .in(jsonBody[NewTopic]) - .out(jsonBody[Topic]) + .in(jsonBody[NewTopicDTO]) + .out(jsonBody[TopicDTO]) .errorOut(errorOutputsFor(401, 403, 404, 410)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -244,8 +244,8 @@ trait ArenaController { .in("topics" / pathTopicId / "posts") .summary("Add post to topic") .description("Add post to topic") - .in(jsonBody[NewPost]) - .out(statusCode(StatusCode.Created).and(jsonBody[Post])) + .in(jsonBody[NewPostDTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[PostDTO])) .errorOut(errorOutputsFor(401, 403, 404, 410)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -258,8 +258,8 @@ trait ArenaController { .in("categories") .summary("Create new arena category") .description("Create new arena category") - .in(jsonBody[NewCategory]) - .out(statusCode(StatusCode.Created).and(jsonBody[Category])) + .in(jsonBody[NewCategoryDTO]) + .out(statusCode(StatusCode.Created).and(jsonBody[CategoryDTO])) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { _ => newCategory => @@ -270,8 +270,8 @@ trait ArenaController { .in("categories" / pathCategoryId) .summary("Update arena category") .description("Update arena category") - .in(jsonBody[NewCategory]) - .out(jsonBody[Category]) + .in(jsonBody[NewCategoryDTO]) + .out(jsonBody[CategoryDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { user => @@ -284,8 +284,8 @@ trait ArenaController { .in("posts" / pathPostId) .summary("Update arena post") .description("Update arena post") - .in(jsonBody[NewPost]) - .out(jsonBody[Post]) + .in(jsonBody[NewPostDTO]) + .out(jsonBody[PostDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -332,7 +332,7 @@ trait ArenaController { .summary("Flag arena post") .description("Flag arena post") .out(emptyOutput) - .in(jsonBody[NewFlag]) + .in(jsonBody[NewFlagDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -345,7 +345,7 @@ trait ArenaController { .in("flags" / pathFlagId) .summary("Toggle arena flag resolution status") .description("Toggle arena flag resolution status") - .out(jsonBody[Flag]) + .out(jsonBody[FlagDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { _ => flagId => @@ -358,7 +358,7 @@ trait ArenaController { .description("List flagged posts") .in(queryPage) .in(queryPageSize) - .out(jsonBody[PaginatedPosts]) + .out(jsonBody[PaginatedPostsDTO]) .errorOut(errorOutputsFor(401, 403)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { user => @@ -373,7 +373,7 @@ trait ArenaController { .description("Get your notifications") .in(queryPage) .in(queryPageSize) - .out(jsonBody[PaginatedNewPostNotifications]) + .out(jsonBody[PaginatedNewPostNotificationsDTO]) .errorOut(errorOutputsFor(401, 403)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { user => @@ -430,7 +430,7 @@ trait ArenaController { .in("posts" / pathPostId / "topic") .summary("Get a topic on the page where the post is") .description("Get a topic on the page where the post is") - .out(jsonBody[TopicWithPosts]) + .out(jsonBody[TopicWithPostsDTO]) .errorOut(errorOutputsFor(401, 403, 404, 410)) .in(queryPageSize) .requireMyNDLAUser(requireArena = true) @@ -445,7 +445,7 @@ trait ArenaController { .description("Get user data by username") .in("user") .in(path[String]("username").description("Username of user")) - .out(jsonBody[ArenaUser]) + .out(jsonBody[ArenaUserDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArena = true) .serverLogicPure { _ => username => @@ -460,7 +460,7 @@ trait ArenaController { .in(queryPageSize) .in(query[Boolean]("filter-teachers").description("Whether to filter teachers or not").default(false)) .in(query[Option[String]]("query").description("Search query to match against username or display name")) - .out(jsonBody[PaginatedArenaUsers]) + .out(jsonBody[PaginatedArenaUsersDTO]) .errorOut(errorOutputsFor(401, 403)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { _ => @@ -480,8 +480,8 @@ trait ArenaController { .summary("Update some one elses user data") .description("Update some one elses user data") .in("users" / path[Long]("user-id").description("UserID of user to update")) - .in(jsonBody[UpdatedMyNDLAUser]) - .out(jsonBody[MyNDLAUser]) + .in(jsonBody[UpdatedMyNDLAUserDTO]) + .out(jsonBody[MyNDLAUserDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .requireMyNDLAUser(requireArenaAdmin = true) .serverLogicPure { adminUser => diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ConfigController.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ConfigController.scala index a5ecea1545..62ef3624d4 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ConfigController.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/ConfigController.scala @@ -16,7 +16,7 @@ import sttp.tapir.* import sttp.tapir.generic.auto.* import sttp.tapir.codec.enumeratum.* import io.circe.generic.auto.* -import no.ndla.common.model.api.config.{ConfigMeta, ConfigMetaRestricted, ConfigMetaValue} +import no.ndla.common.model.api.config.{ConfigMetaDTO, ConfigMetaRestrictedDTO, ConfigMetaValueDTO} import no.ndla.common.model.domain.config.ConfigKey import no.ndla.myndlaapi.service.ConfigService import no.ndla.network.tapir.auth.Permission.LEARNINGPATH_API_ADMIN @@ -39,7 +39,7 @@ trait ConfigController { .summary("Get db configuration by key") .description("Get db configuration by key") .in(pathConfigKey) - .out(jsonBody[ConfigMetaRestricted]) + .out(jsonBody[ConfigMetaRestrictedDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .serverLogicPure { configKey => configService.getConfig(configKey) @@ -49,9 +49,9 @@ trait ConfigController { .summary("Update configuration used by api.") .description("Update configuration used by api.") .in(pathConfigKey) - .in(jsonBody[ConfigMetaValue]) + .in(jsonBody[ConfigMetaValueDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[ConfigMeta]) + .out(jsonBody[ConfigMetaDTO]) .requirePermission(LEARNINGPATH_API_ADMIN) .serverLogicPure { user => { case (configKey, configValue) => diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/FolderController.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/FolderController.scala index 9ef2d29ca7..589fb534d9 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/FolderController.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/FolderController.scala @@ -11,14 +11,14 @@ import no.ndla.common.model.api.CommaSeparatedList.* import no.ndla.common.model.domain.ResourceType import no.ndla.common.model.domain.myndla.FolderStatus import no.ndla.myndlaapi.model.api.{ - Folder, - FolderSortRequest, - NewFolder, - NewResource, - Resource, - UpdatedFolder, - UpdatedResource, - UserFolder + FolderDTO, + FolderSortRequestDTO, + NewFolderDTO, + NewResourceDTO, + ResourceDTO, + UpdatedFolderDTO, + UpdatedResourceDTO, + UserFolderDTO } import no.ndla.myndlaapi.model.domain.FolderSortObject.{ FolderSorting, @@ -80,7 +80,7 @@ trait FolderController { .in(includeResources) .in(includeSubfolders) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[UserFolder]) + .out(jsonBody[UserFolderDTO]) .serverLogicPure { case (feideHeader, includeResources, includeSubfolders) => folderReadService.getFolders(includeSubfolders, includeResources, feideHeader) } @@ -93,7 +93,7 @@ trait FolderController { .in(includeResources) .in(includeSubfolders) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Folder]) + .out(jsonBody[FolderDTO]) .serverLogicPure { case (folderId, feideHeader, includeResources, includeSubfolders) => folderReadService .getSingleFolder(folderId, includeSubfolders, includeResources, feideHeader) @@ -104,9 +104,9 @@ trait FolderController { .summary("Creates new folder") .description("Creates new folder") .in(feideHeader) - .in(jsonBody[NewFolder]) + .in(jsonBody[NewFolderDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Folder]) + .out(jsonBody[FolderDTO]) .serverLogicPure { case (feideHeader, newFolder) => folderWriteService.newFolder(newFolder, feideHeader) } @@ -116,9 +116,9 @@ trait FolderController { .description("Update folder with new data") .in(feideHeader) .in(pathFolderId) - .in(jsonBody[UpdatedFolder]) + .in(jsonBody[UpdatedFolderDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Folder]) + .out(jsonBody[FolderDTO]) .serverLogicPure { case (feideHeader, folderId, updatedFolder) => folderWriteService.updateFolder(folderId, updatedFolder, feideHeader) } @@ -146,7 +146,7 @@ trait FolderController { .in(feideHeader) .in(size) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[List[Resource]]) + .out(jsonBody[List[ResourceDTO]]) .serverLogicPure { case (feideHeader, inputSize) => val size = if (inputSize < 1) defaultSize else inputSize folderReadService.getAllResources(size, feideHeader) @@ -160,7 +160,7 @@ trait FolderController { .in(queryRecentSize) .in(queryExcludeResourceTypes) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Seq[Resource]]) + .out(jsonBody[Seq[ResourceDTO]]) .serverLogicPure { case (queryRecentSize, queryExcludeResourceTypes) => folderReadService .getRecentFavorite(queryRecentSize, queryExcludeResourceTypes.values) @@ -172,9 +172,9 @@ trait FolderController { .description("Creates new folder resource") .in(feideHeader) .in(pathFolderId / "resources") - .in(jsonBody[NewResource]) + .in(jsonBody[NewResourceDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Resource]) + .out(jsonBody[ResourceDTO]) .serverLogicPure { case (feideHeader, folderId, newResource) => folderWriteService.newFolderResourceConnection(folderId, newResource, feideHeader) } @@ -184,9 +184,9 @@ trait FolderController { .description("Updates selected resource") .in("resources" / pathResourceId) .in(feideHeader) - .in(jsonBody[UpdatedResource]) + .in(jsonBody[UpdatedResourceDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404)) - .out(jsonBody[Resource]) + .out(jsonBody[ResourceDTO]) .serverLogicPure { case (resourceId, feideHeader, updatedResource) => folderWriteService.updateResource(resourceId, updatedResource, feideHeader) } @@ -209,7 +209,7 @@ trait FolderController { .description("Fetch a shared folder and all its content") .in("shared" / pathFolderId) .in(feideHeader) - .out(jsonBody[Folder]) + .out(jsonBody[FolderDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .serverLogicPure { case (folderId, feideHeader) => folderReadService.getSharedFolder(folderId, feideHeader) @@ -235,7 +235,7 @@ trait FolderController { .in("clone" / sourceFolderId) .in(destinationFolderId) .in(feideHeader) - .out(jsonBody[Folder]) + .out(jsonBody[FolderDTO]) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .serverLogicPure { case (sourceFolderId, destinationFolderId, feideId) => folderWriteService.cloneFolder(sourceFolderId, destinationFolderId, feideId) @@ -246,7 +246,7 @@ trait FolderController { .description("Decide order of resource ids in a folder") .in("sort-resources" / pathFolderId) .in(feideHeader) - .in(jsonBody[FolderSortRequest]) + .in(jsonBody[FolderSortRequestDTO]) .out(emptyOutput) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .serverLogicPure { case (folderId, feideHeader, sortRequest) => @@ -259,7 +259,7 @@ trait FolderController { .description("Decide order of subfolder ids in a folder") .in("sort-subfolders") .in(feideHeader) - .in(jsonBody[FolderSortRequest]) + .in(jsonBody[FolderSortRequestDTO]) .in(queryFolderId) .out(emptyOutput) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) @@ -273,7 +273,7 @@ trait FolderController { .description("Decide order of saved shared folders") .in("sort-saved") .in(feideHeader) - .in(jsonBody[FolderSortRequest]) + .in(jsonBody[FolderSortRequestDTO]) .out(emptyOutput) .errorOut(errorOutputsFor(400, 401, 403, 404, 502)) .serverLogicPure { case (feideHeader, sortRequest) => diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/StatsController.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/StatsController.scala index c42e72433a..5e6f6f8d36 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/StatsController.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/StatsController.scala @@ -8,9 +8,9 @@ package no.ndla.myndlaapi.controller import no.ndla.common.errors.NotFoundException -import no.ndla.common.model.api.SingleResourceStats +import no.ndla.common.model.api.SingleResourceStatsDTO import no.ndla.common.model.domain.ResourceType -import no.ndla.myndlaapi.model.api.Stats +import no.ndla.myndlaapi.model.api.StatsDTO import no.ndla.myndlaapi.service.FolderReadService import no.ndla.network.tapir.NoNullJsonPrinter.jsonBody import no.ndla.network.tapir.TapirController @@ -30,7 +30,7 @@ trait StatsController { def getStats: ServerEndpoint[Any, Eff] = endpoint.get .summary("Get stats") .description("Get stats") - .out(jsonBody[Stats]) + .out(jsonBody[StatsDTO]) .errorOut(errorOutputsFor(404)) .serverLogicPure { _ => folderReadService.getStats match { @@ -51,7 +51,7 @@ trait StatsController { .summary("Get folder resource favorites") .description("Get folder resource favorites") .in("favorites" / pathResourceType / pathResourceIds) - .out(jsonBody[List[SingleResourceStats]]) + .out(jsonBody[List[SingleResourceStatsDTO]]) .errorOut(errorOutputsFor(404)) .serverLogicPure { case (resourceType, resourceIds) => folderReadService.getFavouriteStatsForResource(resourceIds.values, resourceType.values) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/UserController.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/UserController.scala index 80b1fd5a3d..f1d84ec773 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/UserController.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/controller/UserController.scala @@ -19,9 +19,9 @@ import sttp.tapir.server.ServerEndpoint import sttp.tapir.* import sttp.tapir.generic.auto.* import io.circe.generic.auto.* -import no.ndla.common.model.api.myndla.{MyNDLAUser, UpdatedMyNDLAUser} +import no.ndla.common.model.api.myndla.{MyNDLAUserDTO, UpdatedMyNDLAUserDTO} import no.ndla.common.model.domain.myndla.auth.AuthUtility -import no.ndla.myndlaapi.model.api.ExportedUserData +import no.ndla.myndlaapi.model.api.ExportedUserDataDTO import no.ndla.myndlaapi.service.{ArenaReadService, FolderReadService, FolderWriteService, UserService} import no.ndla.network.model.FeideID import no.ndla.network.tapir.auth.TokenUser @@ -45,7 +45,7 @@ trait UserController { .summary("Get user data") .description("Get user data") .in(feideHeader) - .out(jsonBody[MyNDLAUser]) + .out(jsonBody[MyNDLAUserDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .serverLogicPure { feideHeader => userService.getMyNDLAUserData(feideHeader) @@ -55,8 +55,8 @@ trait UserController { .summary("Update user data") .description("Update user data") .in(feideHeader) - .in(jsonBody[UpdatedMyNDLAUser]) - .out(jsonBody[MyNDLAUser]) + .in(jsonBody[UpdatedMyNDLAUserDTO]) + .out(jsonBody[MyNDLAUserDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .serverLogicPure { case (feideHeader, updatedMyNdlaUser) => userService.updateMyNDLAUserData(updatedMyNdlaUser, feideHeader) @@ -67,8 +67,8 @@ trait UserController { .description("Update some one elses user data") .in("update-other-user") .in(query[Option[FeideID]]("feide-id").description("FeideID of user")) - .in(jsonBody[UpdatedMyNDLAUser]) - .out(jsonBody[MyNDLAUser]) + .in(jsonBody[UpdatedMyNDLAUserDTO]) + .out(jsonBody[MyNDLAUserDTO]) .errorOut(errorOutputsFor(401, 403, 404)) .securityIn(TokenUser.oauth2Input(Seq.empty)) .securityIn(AuthUtility.feideOauth()) @@ -102,7 +102,7 @@ trait UserController { .description("Export all stored user-related data as a json structure") .in("export") .in(feideHeader) - .out(jsonBody[ExportedUserData]) + .out(jsonBody[ExportedUserDataDTO]) .errorOut(errorOutputsFor(401, 403)) .serverLogicPure { feideHeader => folderReadService.exportUserData(feideHeader) @@ -113,8 +113,8 @@ trait UserController { .description("Import all stored user-related data from a exported json structure") .in("import") .in(feideHeader) - .in(jsonBody[ExportedUserData]) - .out(jsonBody[ExportedUserData]) + .in(jsonBody[ExportedUserDataDTO]) + .out(jsonBody[ExportedUserDataDTO]) .errorOut(errorOutputsFor(401, 403)) .serverLogicPure { case (feideHeader, importBody) => folderWriteService.importUserData(importBody, feideHeader) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUser.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUserDTO.scala similarity index 77% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUser.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUserDTO.scala index 92b28eb53c..7df4ae49e4 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUser.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ArenaUserDTO.scala @@ -14,7 +14,7 @@ import no.ndla.common.model.domain import sttp.tapir.Schema.annotations.description @description("Arena owner data") -case class ArenaUser( +case class ArenaUserDTO( @description("The owners id") id: Long, @description("The name") displayName: String, @description("The username") username: String, @@ -22,14 +22,14 @@ case class ArenaUser( @description("Which groups the user belongs to") groups: List[domain.myndla.ArenaGroup] ) -object ArenaUser { +object ArenaUserDTO { - def from(user: domain.myndla.MyNDLAUser): ArenaUser = { + def from(user: domain.myndla.MyNDLAUser): ArenaUserDTO = { val location = user.groups .find(_.isPrimarySchool) .map(_.displayName) .getOrElse(user.organization) - ArenaUser( + ArenaUserDTO( id = user.id, displayName = user.displayName, username = user.username, @@ -38,7 +38,7 @@ object ArenaUser { ) } - implicit val arenaUserEncoder: Encoder[ArenaUser] = deriveEncoder - implicit val arenaUserDecoder: Decoder[ArenaUser] = deriveDecoder + implicit val arenaUserEncoder: Encoder[ArenaUserDTO] = deriveEncoder + implicit val arenaUserDecoder: Decoder[ArenaUserDTO] = deriveDecoder } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Breadcrumb.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/BreadcrumbDTO.scala similarity index 62% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Breadcrumb.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/BreadcrumbDTO.scala index a5978f3252..6773c3fcaf 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Breadcrumb.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/BreadcrumbDTO.scala @@ -12,12 +12,12 @@ import io.circe.generic.semiauto._ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description -case class Breadcrumb( +case class BreadcrumbDTO( @description("UUID of the folder") id: String, @description("Folder name") name: String ) -object Breadcrumb { - implicit val encoder: Encoder[Breadcrumb] = deriveEncoder[Breadcrumb] - implicit val decoder: Decoder[Breadcrumb] = deriveDecoder[Breadcrumb] +object BreadcrumbDTO { + implicit val encoder: Encoder[BreadcrumbDTO] = deriveEncoder[BreadcrumbDTO] + implicit val decoder: Decoder[BreadcrumbDTO] = deriveDecoder[BreadcrumbDTO] } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserData.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserData.scala deleted file mode 100644 index 920e3dbf0b..0000000000 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserData.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Part of NDLA myndla-api - * Copyright (C) 2024 NDLA - * - * See LICENSE - * - */ -package no.ndla.myndlaapi.model.api - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.myndla.MyNDLAUser -import sttp.tapir.Schema.annotations.description - -case class ExportedUserData( - @description("The users data") userData: MyNDLAUser, - @description("The users folders") folders: List[Folder] -) - -object ExportedUserData { - implicit def encoder: Encoder[ExportedUserData] = deriveEncoder[ExportedUserData] - implicit def decoder: Decoder[ExportedUserData] = deriveDecoder[ExportedUserData] -} diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserDataDTO.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserDataDTO.scala new file mode 100644 index 0000000000..bbdc6df8f9 --- /dev/null +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/ExportedUserDataDTO.scala @@ -0,0 +1,23 @@ +/* + * Part of NDLA myndla-api + * Copyright (C) 2024 NDLA + * + * See LICENSE + * + */ +package no.ndla.myndlaapi.model.api + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.api.myndla.MyNDLAUserDTO +import sttp.tapir.Schema.annotations.description + +case class ExportedUserDataDTO( + @description("The users data") userData: MyNDLAUserDTO, + @description("The users folders") folders: List[FolderDTO] +) + +object ExportedUserDataDTO { + implicit def encoder: Encoder[ExportedUserDataDTO] = deriveEncoder[ExportedUserDataDTO] + implicit def decoder: Decoder[ExportedUserDataDTO] = deriveDecoder[ExportedUserDataDTO] +} diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Folder.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderDTO.scala similarity index 70% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Folder.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderDTO.scala index 25e7eff9ff..2f270f7a40 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Folder.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderDTO.scala @@ -20,53 +20,53 @@ import sttp.tapir.Schema.annotations.description import scala.annotation.unused -case class Owner( +case class OwnerDTO( @description("Name of the owner") name: String ) -object Owner { - implicit val encoder: Encoder[Owner] = deriveEncoder - implicit val decoder: Decoder[Owner] = deriveDecoder +object OwnerDTO { + implicit val encoder: Encoder[OwnerDTO] = deriveEncoder + implicit val decoder: Decoder[OwnerDTO] = deriveDecoder } -// format: off -case class Folder( +case class FolderDTO( @description("UUID of the folder") id: String, @description("Folder name") name: String, @description("Folder status") status: String, @description("UUID of parent folder") parentId: Option[String], - @description("List of parent folders to resource") breadcrumbs: List[Breadcrumb], - @description("List of subfolders") subfolders: List[FolderData], - @description("List of resources") resources: List[Resource], + @description("List of parent folders to resource") breadcrumbs: List[BreadcrumbDTO], + @description("List of subfolders") subfolders: List[FolderDataDTO], + @description("List of resources") resources: List[ResourceDTO], @description("Where the folder is sorted within its parent") rank: Int, @description("When the folder was created") created: NDLADate, @description("When the folder was updated") updated: NDLADate, @description("When the folder was last shared") shared: Option[NDLADate], @description("Description of the folder") description: Option[String], - @description("Owner of the folder, if the owner have opted in to share their name") owner: Option[Owner], -) extends FolderData with CopyableFolder + @description("Owner of the folder, if the owner have opted in to share their name") owner: Option[OwnerDTO] +) extends FolderDataDTO + with CopyableFolder // format: on // 1: This object is needed for generating recursive Folder typescript type. -object Folder { - implicit val resource: TSIType[Resource] = TSType.fromCaseClass[Resource] - implicit val folderTSI: TSIType[Folder] = { +object FolderDTO { + implicit val resource: TSIType[ResourceDTO] = TSType.fromCaseClass[ResourceDTO] + implicit val folderTSI: TSIType[FolderDTO] = { @unused // 2: We are saying here that there is no need for scala-tsi to generate IFolderData type automatically. // We assure scala-tsi that we are getting IFolderData from external source. We point that source to FolderData. - implicit val folderData: TSNamedType[FolderData] = TSType.external[FolderData]("IFolderData") - TSType.fromCaseClass[Folder] + implicit val folderData: TSNamedType[FolderDataDTO] = TSType.external[FolderDataDTO]("IFolderDataDTO") + TSType.fromCaseClass[FolderDTO] } - implicit val folderEncoder: Encoder[Folder] = deriveEncoder - implicit val folderDecoder: Decoder[Folder] = deriveDecoder + implicit val folderEncoder: Encoder[FolderDTO] = deriveEncoder + implicit val folderDecoder: Decoder[FolderDTO] = deriveDecoder - implicit val folderDataEncoder: Encoder[FolderData] = Encoder.instance { case folder: Folder => folder.asJson } - implicit val folderDataDecoder: Decoder[FolderData] = Decoder[Folder].widen + implicit val folderDataEncoder: Encoder[FolderDataDTO] = Encoder.instance { case folder: FolderDTO => folder.asJson } + implicit val folderDataDecoder: Decoder[FolderDataDTO] = Decoder[FolderDTO].widen } -sealed trait FolderData extends CopyableFolder {} -object FolderData { +sealed trait FolderDataDTO extends CopyableFolder {} +object FolderDataDTO { // implicit val encoder: Encoder[FolderData] = Encoder.instance { case data: Folder => data.asJson } // implicit val decoder: Decoder[FolderData] = Decoder[Folder].widen @@ -76,17 +76,17 @@ object FolderData { name: String, status: String, parentId: Option[String], - breadcrumbs: List[Breadcrumb], - subfolders: List[FolderData], - resources: List[Resource], + breadcrumbs: List[BreadcrumbDTO], + subfolders: List[FolderDataDTO], + resources: List[ResourceDTO], rank: Int, created: NDLADate, updated: NDLADate, shared: Option[NDLADate], description: Option[String], username: Option[String] - ): FolderData = { - Folder( + ): FolderDataDTO = { + FolderDTO( id, name, status, @@ -99,30 +99,30 @@ object FolderData { updated, shared, description, - username.map(name => Owner(name)) + username.map(name => OwnerDTO(name)) ) } // 3: After being redirected here from TSType.external we are manually making the union of FolderData, // with Folder. After that we alias it as IFolderData so that scala-tsi can incorporate it. - implicit val folderDataAlias: TSNamedType[FolderData] = TSType.alias[FolderData]("IFolderData", Folder.folderTSI.get) + implicit val folderDataAlias: TSNamedType[FolderDataDTO] = + TSType.alias[FolderDataDTO]("IFolderDataDTO", FolderDTO.folderTSI.get) } -case class NewFolder( +case class NewFolderDTO( @description("Folder name") name: String, @description("Id of parent folder") parentId: Option[String], @description("Status of the folder (private, shared)") status: Option[String], @description("Description of the folder") description: Option[String] ) -case class UpdatedFolder( +case class UpdatedFolderDTO( @description("Folder name") name: Option[String], @description("Status of the folder (private, shared)") status: Option[String], @description("Description of the folder") description: Option[String] ) -// format: off -case class Resource( +case class ResourceDTO( @description("Unique ID of the resource") id: String, @description("Type of the resource. (Article, Learningpath)") resourceType: ResourceType, @description("Relative path of this resource") path: String, @@ -131,21 +131,20 @@ case class Resource( @description("The id of the resource, useful for fetching metadata for the resource") resourceId: String, @description("The which rank the resource appears in a sorted sequence") rank: Option[Int] ) extends CopyableResource -// format: on -object Resource { - implicit val encoder: Encoder[Resource] = deriveEncoder[Resource] - implicit val decoder: Decoder[Resource] = deriveDecoder[Resource] +object ResourceDTO { + implicit val encoder: Encoder[ResourceDTO] = deriveEncoder[ResourceDTO] + implicit val decoder: Decoder[ResourceDTO] = deriveDecoder[ResourceDTO] } -case class NewResource( +case class NewResourceDTO( @description("Type of the resource. (Article, Learningpath)") resourceType: ResourceType, @description("Relative path of this resource") path: String, @description("List of tags") tags: Option[List[String]], @description("The id of the resource, useful for fetching metadata for the resource") resourceId: String ) -case class UpdatedResource( +case class UpdatedResourceDTO( @description("List of tags") tags: Option[List[String]], @description("The id of the resource, useful for fetching metadata for the resource") resourceId: Option[String] ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequest.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequestDTO.scala similarity index 89% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequest.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequestDTO.scala index 2444e41938..a6cf9bf101 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequest.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/FolderSortRequestDTO.scala @@ -12,6 +12,6 @@ import sttp.tapir.Schema.annotations.description import java.util.UUID -case class FolderSortRequest( +case class FolderSortRequestDTO( @description("List of the children ids in sorted order, MUST be all ids") sortedIds: Seq[UUID] ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsers.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsersDTO.scala similarity index 80% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsers.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsersDTO.scala index f95ea4fba3..fda03a0870 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsers.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/PaginatedArenaUsersDTO.scala @@ -11,9 +11,9 @@ package no.ndla.myndlaapi.model.api import sttp.tapir.Schema.annotations.description @description("Model to describe pagination of users") -case class PaginatedArenaUsers( +case class PaginatedArenaUsersDTO( @description("How many items across all pages") totalCount: Long, @description("Which page number this is") page: Long, @description("How many items per page") pageSize: Long, - @description("The paginated items") items: List[ArenaUser] + @description("The paginated items") items: List[ArenaUserDTO] ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Stats.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/StatsDTO.scala similarity index 74% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Stats.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/StatsDTO.scala index 3223f7ee88..30bdb822c3 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/Stats.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/StatsDTO.scala @@ -13,28 +13,28 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Stats for my-ndla usage") -case class Stats( +case class StatsDTO( @description("The total number of users registered ") numberOfUsers: Long, @description("The total number of created folders") numberOfFolders: Long, @description("The total number of favourited resources ") numberOfResources: Long, @description("The total number of created tags") numberOfTags: Long, @description("The total number of favourited subjects") numberOfSubjects: Long, @description("The total number of shared folders") numberOfSharedFolders: Long, - @description("Stats for type resources") favouritedResources: List[ResourceStats], + @description("Stats for type resources") favouritedResources: List[ResourceStatsDTO], @description("Stats for favourited resources") favourited: Map[String, Long] ) -object Stats { - implicit def encoder: Encoder[Stats] = deriveEncoder - implicit def decoder: Decoder[Stats] = deriveDecoder +object StatsDTO { + implicit def encoder: Encoder[StatsDTO] = deriveEncoder + implicit def decoder: Decoder[StatsDTO] = deriveDecoder } -case class ResourceStats( +case class ResourceStatsDTO( @description("The type of favourited resouce") `type`: String, @description("The number of favourited resource") number: Long ) -object ResourceStats { - implicit def encoder: Encoder[ResourceStats] = deriveEncoder - implicit def decoder: Decoder[ResourceStats] = deriveDecoder +object ResourceStatsDTO { + implicit def encoder: Encoder[ResourceStatsDTO] = deriveEncoder + implicit def decoder: Decoder[ResourceStatsDTO] = deriveDecoder } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolder.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolderDTO.scala similarity index 69% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolder.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolderDTO.scala index e47bb480b2..14e99f656c 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolder.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/api/UserFolderDTO.scala @@ -11,7 +11,7 @@ package no.ndla.myndlaapi.model.api import sttp.tapir.Schema.annotations.description @description("User folder data") -case class UserFolder( - @description("The users own folders") folders: List[Folder], - @description("The shared folder the user has saved") sharedFolders: List[Folder] +case class UserFolderDTO( + @description("The users own folders") folders: List[FolderDTO], + @description("The shared folder the user has saved") sharedFolders: List[FolderDTO] ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumb.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumbDTO.scala similarity index 90% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumb.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumbDTO.scala index 0e164a56b2..bcf20bb8ab 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumb.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryBreadcrumbDTO.scala @@ -10,7 +10,7 @@ package no.ndla.myndlaapi.model.arena.api import sttp.tapir.Schema.annotations.description @description("Arena category data") -case class CategoryBreadcrumb( +case class CategoryBreadcrumbDTO( @description("The category's id") id: Long, @description("The category's title") title: String ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Category.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryDTO.scala similarity index 86% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Category.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryDTO.scala index e3b02c95bc..35c77c5921 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Category.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategoryDTO.scala @@ -9,13 +9,13 @@ package no.ndla.myndlaapi.model.arena.api import sttp.tapir.Schema.annotations.description -sealed trait CategoryType { +sealed trait CategoryTypeDTO { val id: Long - val subcategories: List[CategoryType] + val subcategories: List[CategoryTypeDTO] } @description("Arena category data") -case class Category( +case class CategoryDTO( @description("The category's id") id: Long, @description("The category's title") title: String, @description("The category's description") description: String, @@ -26,12 +26,12 @@ case class Category( @description("Where the category is sorted when sorting by rank") rank: Int, @description("The id of the parent category if any") parentCategoryId: Option[Long], @description("Count of subcategories in the category") categoryCount: Long, - @description("Categories in the category") subcategories: List[Category], - @description("Breadcrumb path of categories") breadcrumbs: List[CategoryBreadcrumb] -) extends CategoryType + @description("Categories in the category") subcategories: List[CategoryDTO], + @description("Breadcrumb path of categories") breadcrumbs: List[CategoryBreadcrumbDTO] +) extends CategoryTypeDTO @description("Arena category data") -case class CategoryWithTopics( +case class CategoryWithTopicsDTO( @description("The category's id") id: Long, @description("The category's title") title: String, @description("The category's description") description: String, @@ -39,12 +39,12 @@ case class CategoryWithTopics( @description("Count of posts in the category") postCount: Long, @description("Which page of topics") topicPage: Long, @description("Page size of topics") topicPageSize: Long, - @description("Topics in the category") topics: List[Topic], + @description("Topics in the category") topics: List[TopicDTO], @description("Whether the requesting user is following the category") isFollowing: Boolean, @description("Whether the category is visible to regular users") visible: Boolean, @description("Where the category is sorted when sorting by rank") rank: Int, @description("The id of the parent category if any") parentCategoryId: Option[Long], @description("Count of subcategories in the category") categoryCount: Long, - @description("Categories in the category") subcategories: List[Category], - @description("Breadcrumb path of categories") breadcrumbs: List[CategoryBreadcrumb] -) extends CategoryType + @description("Categories in the category") subcategories: List[CategoryDTO], + @description("Breadcrumb path of categories") breadcrumbs: List[CategoryBreadcrumbDTO] +) extends CategoryTypeDTO diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySort.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySortDTO.scala similarity index 55% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySort.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySortDTO.scala index 2ba8e9451e..c10e3cba56 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySort.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/CategorySortDTO.scala @@ -11,21 +11,21 @@ import enumeratum._ import sttp.tapir.CodecFormat.TextPlain import sttp.tapir.{Codec, CodecFormat, DecodeResult, Schema} -sealed abstract class CategorySort(override val entryName: String) extends EnumEntry +sealed abstract class CategorySortDTO(override val entryName: String) extends EnumEntry -object CategorySort extends Enum[CategorySort] with CirceEnum[CategorySort] { - case object ByTitle extends CategorySort("title") - case object ByRank extends CategorySort("rank") +object CategorySortDTO extends Enum[CategorySortDTO] with CirceEnum[CategorySortDTO] { + case object ByTitle extends CategorySortDTO("title") + case object ByRank extends CategorySortDTO("rank") val all: Seq[String] = values.map(_.entryName) - override def values: IndexedSeq[CategorySort] = findValues + override def values: IndexedSeq[CategorySortDTO] = findValues - private def fromOptString(maybeString: Option[String]): Option[CategorySort] = { - maybeString.flatMap { s => CategorySort.withNameInsensitiveOption(s) } + private def fromOptString(maybeString: Option[String]): Option[CategorySortDTO] = { + maybeString.flatMap { s => CategorySortDTO.withNameInsensitiveOption(s) } } - implicit val queryParamCodec: Codec[List[String], CategorySort, CodecFormat.TextPlain] = { + implicit val queryParamCodec: Codec[List[String], CategorySortDTO, CodecFormat.TextPlain] = { Codec .id[List[String], TextPlain](TextPlain(), Schema.string) .mapDecode(x => DecodeResult.fromOption(fromOptString(x.headOption)))(x => List(x.entryName)) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Flag.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/FlagDTO.scala similarity index 70% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Flag.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/FlagDTO.scala index afc80ca9e1..fc3444def6 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Flag.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/FlagDTO.scala @@ -10,20 +10,20 @@ package no.ndla.myndlaapi.model.arena.api import io.circe.{Decoder, Encoder} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import no.ndla.common.model.NDLADate -import no.ndla.myndlaapi.model.api.ArenaUser +import no.ndla.myndlaapi.model.api.ArenaUserDTO import sttp.tapir.Schema.annotations.description @description("Arena flag data") -case class Flag( +case class FlagDTO( @description("The flag id") id: Long, @description("The flag reason") reason: String, @description("The flag creation date") created: NDLADate, @description("The flag resolution date") resolved: Option[NDLADate], @description("Whether the flag has been resolved or not") isResolved: Boolean, - @description("The flagging user") flagger: Option[ArenaUser] + @description("The flagging user") flagger: Option[ArenaUserDTO] ) -object Flag { - implicit val flagEncoder: Encoder[Flag] = deriveEncoder - implicit val flagDecoder: Decoder[Flag] = deriveDecoder +object FlagDTO { + implicit val flagEncoder: Encoder[FlagDTO] = deriveEncoder + implicit val flagDecoder: Decoder[FlagDTO] = deriveDecoder } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategory.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategoryDTO.scala similarity index 94% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategory.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategoryDTO.scala index bcd3e3cb36..979fbbf931 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategory.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewCategoryDTO.scala @@ -10,7 +10,7 @@ package no.ndla.myndlaapi.model.arena.api import sttp.tapir.Schema.annotations.description @description("Arena category data") -case class NewCategory( +case class NewCategoryDTO( @description("The category's title") title: String, @description("The category's description") description: String, @description("Whether the category is visible to users") visible: Boolean, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlag.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlagDTO.scala similarity index 91% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlag.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlagDTO.scala index 6199ea0601..adc2fd455e 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlag.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewFlagDTO.scala @@ -10,6 +10,6 @@ package no.ndla.myndlaapi.model.arena.api import sttp.tapir.Schema.annotations.description @description("Flag data") -case class NewFlag( +case class NewFlagDTO( @description("The reason for flagging") reason: String ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPost.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostDTO.scala similarity index 72% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPost.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostDTO.scala index 44228eba86..4dd380fabb 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPost.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostDTO.scala @@ -12,12 +12,12 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import sttp.tapir.Schema.annotations.description @description("Arena post data") -case class NewPost( +case class NewPostDTO( @description("The post content") content: String, @description("The id of the post that is replied to") toPostId: Option[Long] ) -object NewPost { - implicit val encodeMenu: Encoder[NewPost] = deriveEncoder - implicit val decodeMenu: Decoder[NewPost] = deriveDecoder +object NewPostDTO { + implicit val encodeMenu: Encoder[NewPostDTO] = deriveEncoder + implicit val decodeMenu: Decoder[NewPostDTO] = deriveDecoder } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotification.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotificationDTO.scala similarity index 81% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotification.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotificationDTO.scala index 34c161f162..5f57195a2d 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotification.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewPostNotificationDTO.scala @@ -10,17 +10,17 @@ package no.ndla.myndlaapi.model.arena.api import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description -sealed trait Notifications { +sealed trait NotificationsDTO { val id: Long val notificationTime: NDLADate } @description("Notification data") -case class NewPostNotification( +case class NewPostNotificationDTO( @description("The notification id") id: Long, @description("The topic id which got a new post") topicId: Long, @description("Whether the notification has been read or not") isRead: Boolean, @description("The topic title which got a new post") topicTitle: String, - @description("The new post id") post: Post, + @description("The new post id") post: PostDTO, @description("Notification time") notificationTime: NDLADate -) extends Notifications +) extends NotificationsDTO diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopic.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopicDTO.scala similarity index 79% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopic.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopicDTO.scala index c22600e86d..d91e5c5910 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopic.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/NewTopicDTO.scala @@ -13,14 +13,14 @@ import sttp.tapir.Schema.annotations.description // format: off @description("Arena topic data") -case class NewTopic( +case class NewTopicDTO( @description("The topics title") title: String, - @description("The initial post in the topic") initialPost: NewPost, + @description("The initial post in the topic") initialPost: NewPostDTO, @description("Whether the topic should be locked or not, only usable by administrators") isLocked: Option[Boolean], @description("Whether the topic should be pinned to the top of the category, only usable by administrators") isPinned: Option[Boolean] ) -object NewTopic { - implicit val encodeMenu: Encoder[NewTopic] = deriveEncoder - implicit val decodeMenu: Decoder[NewTopic] = deriveDecoder +object NewTopicDTO { + implicit val encodeMenu: Encoder[NewTopicDTO] = deriveEncoder + implicit val decodeMenu: Decoder[NewTopicDTO] = deriveDecoder } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Paginated.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Paginated.scala index 18ddc44a16..0bc8c7a383 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Paginated.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Paginated.scala @@ -10,25 +10,25 @@ package no.ndla.myndlaapi.model.arena.api import sttp.tapir.Schema.annotations.description @description("Model to describe pagination of Topic") -case class PaginatedTopics( +case class PaginatedTopicsDTO( @description("How many items across all pages") totalCount: Long, @description("Which page number this is") page: Long, @description("How many items per page") pageSize: Long, - @description("The paginated items") items: List[Topic] + @description("The paginated items") items: List[TopicDTO] ) @description("Model to describe pagination of Post") -case class PaginatedPosts( +case class PaginatedPostsDTO( @description("How many items across all pages") totalCount: Long, @description("Which page number this is") page: Long, @description("How many items per page") pageSize: Long, - @description("The paginated items") items: List[Post] + @description("The paginated items") items: List[PostDTO] ) @description("Model to describe pagination of Flag") -case class PaginatedNewPostNotifications( +case class PaginatedNewPostNotificationsDTO( @description("How many items across all pages") totalCount: Long, @description("Which page number this is") page: Long, @description("How many items per page") pageSize: Long, - @description("The paginated items") items: List[NewPostNotification] + @description("The paginated items") items: List[NewPostNotificationDTO] ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Post.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/PostDTO.scala similarity index 53% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Post.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/PostDTO.scala index bd0705c980..1b21ff41b3 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Post.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/PostDTO.scala @@ -13,41 +13,42 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.syntax.EncoderOps import io.circe.{Decoder, Encoder} import no.ndla.common.model.NDLADate -import no.ndla.myndlaapi.model.api.ArenaUser +import no.ndla.myndlaapi.model.api.ArenaUserDTO import sttp.tapir.Schema.annotations.description import scala.annotation.unused -sealed trait PostWrapper +sealed trait PostWrapperDTO @description("Arena post data") -case class Post( +case class PostDTO( @description("The post id") id: Long, @description("The post content") content: String, @description("The post creation date") created: NDLADate, @description("The post edit date") updated: NDLADate, - @description("The post owner") owner: Option[ArenaUser], - @description("The flags that have been added to post. Only visible to admins.") flags: Option[List[Flag]], + @description("The post owner") owner: Option[ArenaUserDTO], + @description("The flags that have been added to post. Only visible to admins.") flags: Option[List[FlagDTO]], @description("The id of the parenting topic") topicId: Long, - @description("The replies to the post") replies: List[PostWrapper], + @description("The replies to the post") replies: List[PostWrapperDTO], @description("Number of upvotes on the post") upvotes: Int, @description("Flag saying if the logged in user has upvoted or not") upvoted: Boolean -) extends PostWrapper +) extends PostWrapperDTO -object Post { - implicit val postTSI: TSIType[Post] = { +object PostDTO { + implicit val postTSI: TSIType[PostDTO] = { @unused - implicit val postWrapper: TSNamedType[PostWrapper] = TSType.external[PostWrapper]("IPostWrapper") - TSType.fromCaseClass[Post] + implicit val postWrapper: TSNamedType[PostWrapperDTO] = TSType.external[PostWrapperDTO]("IPostWrapperDTO") + TSType.fromCaseClass[PostDTO] } - implicit val postEncoder: Encoder[Post] = deriveEncoder - implicit val postDecoder: Decoder[Post] = deriveDecoder + implicit val postEncoder: Encoder[PostDTO] = deriveEncoder + implicit val postDecoder: Decoder[PostDTO] = deriveDecoder - implicit val postDataEncoder: Encoder[PostWrapper] = Encoder.instance { case post: Post => post.asJson } - implicit val postDataDecoder: Decoder[PostWrapper] = Decoder[Post].widen + implicit val postDataEncoder: Encoder[PostWrapperDTO] = Encoder.instance { case post: PostDTO => post.asJson } + implicit val postDataDecoder: Decoder[PostWrapperDTO] = Decoder[PostDTO].widen } -object PostWrapper { - implicit val wrapperAlias: TSNamedType[PostWrapper] = TSType.alias[PostWrapper]("IPostWrapper", Post.postTSI.get) +object PostWrapperDTO { + implicit val wrapperAlias: TSNamedType[PostWrapperDTO] = + TSType.alias[PostWrapperDTO]("IPostWrapperDTO", PostDTO.postTSI.get) } diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Topic.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicDTO.scala similarity index 97% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Topic.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicDTO.scala index bd1028588b..6e85740369 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/Topic.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicDTO.scala @@ -11,7 +11,7 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Arena topic data") -case class Topic( +case class TopicDTO( @description("The topics id") id: Long, @description("The topics title") title: String, @description("Count of posts in the topic") postCount: Long, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPosts.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPostsDTO.scala similarity index 96% rename from myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPosts.scala rename to myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPostsDTO.scala index ee95bbdcd4..86ab506ace 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPosts.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/model/arena/api/TopicWithPostsDTO.scala @@ -11,11 +11,11 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Arena topic data") -case class TopicWithPosts( +case class TopicWithPostsDTO( @description("The topics id") id: Long, @description("The topics title") title: String, @description("Count of posts in the topic") postCount: Long, - @description("The posts in the topic") posts: PaginatedPosts, + @description("The posts in the topic") posts: PaginatedPostsDTO, @description("The post creation date") created: NDLADate, @description("The post edit date") updated: NDLADate, @description("The id of the parenting category") categoryId: Long, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/repository/ArenaRepository.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/repository/ArenaRepository.scala index b74d9c6189..04b8f7e4b1 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/repository/ArenaRepository.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/repository/ArenaRepository.scala @@ -19,7 +19,7 @@ import no.ndla.common.errors.{InvalidStateException, RollbackException} import no.ndla.common.implicits.* import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.myndla.MyNDLAUser -import no.ndla.myndlaapi.model.arena.api.{CategoryBreadcrumb, CategorySort} +import no.ndla.myndlaapi.model.arena.api.{CategoryBreadcrumbDTO, CategorySortDTO} import no.ndla.myndlaapi.model.arena.domain.database.{CompiledFlag, CompiledNotification, CompiledPost, CompiledTopic} import no.ndla.myndlaapi.model.arena.domain.{Notification, Owned, Post} import no.ndla.myndlaapi.model.domain.{DBMyNDLAUser, NDLASQLException} @@ -566,7 +566,7 @@ trait ArenaRepository { ) } - def getBreadcrumbs(categoryId: Long)(implicit session: DBSession): Try[List[CategoryBreadcrumb]] = Try { + def getBreadcrumbs(categoryId: Long)(implicit session: DBSession): Try[List[CategoryBreadcrumbDTO]] = Try { sql""" WITH RECURSIVE breadcrumbs AS ( SELECT id, title, parent_category_id @@ -580,7 +580,7 @@ trait ArenaRepository { SELECT id, title FROM breadcrumbs """ - .map(rs => CategoryBreadcrumb(id = rs.long("id"), title = rs.string("title"))) + .map(rs => CategoryBreadcrumbDTO(id = rs.long("id"), title = rs.string("title"))) .list .apply() .reverse @@ -1297,7 +1297,7 @@ trait ArenaRepository { def getCategories( user: MyNDLAUser, filterFollowed: Boolean, - sort: CategorySort, + sort: CategorySortDTO, parentCategoryId: Option[Long] )(implicit session: DBSession): Try[List[domain.Category]] = { val ca = domain.Category.syntax("ca") @@ -1325,8 +1325,8 @@ trait ArenaRepository { } else buildWhereClause(visibleSql.toSeq :+ parentFilter) val orderByClause = sort match { - case CategorySort.ByTitle => sqls"order by ${ca.title}" - case CategorySort.ByRank => sqls"order by ${ca.rank}" + case CategorySortDTO.ByTitle => sqls"order by ${ca.title}" + case CategorySortDTO.ByRank => sqls"order by ${ca.rank}" } Try { diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ArenaReadService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ArenaReadService.scala index c6f0be4e38..38e732f81b 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ArenaReadService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ArenaReadService.scala @@ -15,7 +15,7 @@ import no.ndla.common.implicits.OptionImplicit import no.ndla.common.model.domain.myndla.MyNDLAUser import no.ndla.network.clients.FeideApiClient import no.ndla.myndlaapi.model.arena.{api, domain} -import no.ndla.myndlaapi.model.arena.api.{Category, CategorySort, NewCategory, NewPost, NewTopic} +import no.ndla.myndlaapi.model.arena.api.{CategoryDTO, CategorySortDTO, NewCategoryDTO, NewPostDTO, NewTopicDTO} import no.ndla.myndlaapi.model.arena.domain.{MissingPostException, TopicGoneException} import no.ndla.myndlaapi.model.arena.domain.database.{CompiledPost, CompiledTopic} import no.ndla.myndlaapi.repository.{ArenaRepository, FolderRepository, UserRepository} @@ -36,7 +36,7 @@ trait ArenaReadService { val arenaReadService: ArenaReadService class ArenaReadService { - def sortCategories(parentId: Option[Long], sortedIds: List[Long], user: MyNDLAUser): Try[List[api.Category]] = + def sortCategories(parentId: Option[Long], sortedIds: List[Long], user: MyNDLAUser): Try[List[api.CategoryDTO]] = arenaRepository.rollbackOnFailure { session => for { existingCategoryIds <- arenaRepository.getAllCategoryIds(parentId)(session) @@ -48,7 +48,7 @@ trait ArenaReadService { categories <- getCategories( user, filterFollowed = false, - sort = CategorySort.ByRank, + sort = CategorySortDTO.ByRank, parentCategoryId = None )(session) } yield categories @@ -58,7 +58,7 @@ trait ArenaReadService { postId: Long, requester: MyNDLAUser, pageSize: Long - )(session: DBSession = AutoSession): Try[api.TopicWithPosts] = { + )(session: DBSession = AutoSession): Try[api.TopicWithPostsDTO] = { for { maybePost <- arenaRepository.getPost(postId)(session) (post, _) <- maybePost.toTry(NotFoundException(s"Could not find post with id $postId")) @@ -76,7 +76,7 @@ trait ArenaReadService { page: Long, pageSize: Long, requester: MyNDLAUser - )(session: DBSession = ReadOnlyAutoSession): Try[api.PaginatedPosts] = { + )(session: DBSession = ReadOnlyAutoSession): Try[api.PaginatedPostsDTO] = { val offset = (page - 1) * pageSize for { posts <- arenaRepository.getFlaggedPosts(offset, pageSize, requester)(session) @@ -85,7 +85,7 @@ trait ArenaReadService { val replies = getRepliesForPost(compiledPost.post.id, requester)(session).? converterService.toApiPost(compiledPost, requester, replies) }) - } yield api.PaginatedPosts( + } yield api.PaginatedPostsDTO( items = apiPosts, totalCount = postCount, pageSize = pageSize, @@ -109,7 +109,7 @@ trait ArenaReadService { def getNotifications(user: MyNDLAUser, page: Long, pageSize: Long)(implicit session: DBSession = ReadOnlyAutoSession - ): Try[api.PaginatedNewPostNotifications] = { + ): Try[api.PaginatedNewPostNotificationsDTO] = { val offset = (page - 1) * pageSize for { compiledNotifications <- arenaRepository.getNotifications(user, offset, pageSize)(session) @@ -118,7 +118,7 @@ trait ArenaReadService { { val replies = getRepliesForPost(notification.post.post.id, user)(session).? - api.NewPostNotification( + api.NewPostNotificationDTO( id = notification.notification.id, isRead = notification.notification.is_read, topicTitle = notification.topic.title, @@ -128,7 +128,7 @@ trait ArenaReadService { ) } } - } yield api.PaginatedNewPostNotifications( + } yield api.PaginatedNewPostNotificationsDTO( items = apiNotifications, totalCount = notificationsCount, pageSize = pageSize, @@ -136,7 +136,7 @@ trait ArenaReadService { ) } - def resolveFlag(flagId: Long)(session: DBSession = AutoSession): Try[api.Flag] = for { + def resolveFlag(flagId: Long)(session: DBSession = AutoSession): Try[api.FlagDTO] = for { maybeFlag <- arenaRepository.getFlag(flagId)(session) flag <- maybeFlag.toTry(NotFoundException(s"Could not find flag with id $flagId")) updated <- toggleFlagResolution(flag.flag)(session) @@ -151,7 +151,7 @@ trait ArenaReadService { } } - def flagPost(postId: Long, user: MyNDLAUser, newFlag: api.NewFlag)(session: DBSession = AutoSession): Try[Unit] = + def flagPost(postId: Long, user: MyNDLAUser, newFlag: api.NewFlagDTO)(session: DBSession = AutoSession): Try[Unit] = for { maybePost <- arenaRepository.getPost(postId)(session) _ <- maybePost.toTry(NotFoundException(s"Could not find post with id $postId")) @@ -181,14 +181,14 @@ trait ArenaReadService { def getTopicsForCategory(categoryId: Long, page: Long, pageSize: Long, requester: MyNDLAUser)( session: DBSession = ReadOnlyAutoSession - ): Try[api.PaginatedTopics] = { + ): Try[api.PaginatedTopicsDTO] = { val offset = (page - 1) * pageSize for { maybeCategory <- arenaRepository.getCategory(categoryId, includeHidden = false)(session) _ <- maybeCategory.toTry(NotFoundException(s"Could not find category with id $categoryId")) topics <- arenaRepository.getTopicsForCategory(categoryId, offset, pageSize, requester)(session) topicsCount <- arenaRepository.getTopicCountForCategory(categoryId)(session) - } yield api.PaginatedTopics( + } yield api.PaginatedTopicsDTO( items = topics.map { topic => converterService.toApiTopic(topic) }, totalCount = topicsCount, pageSize = pageSize, @@ -198,7 +198,7 @@ trait ArenaReadService { def getRecentTopics(page: Long, pageSize: Long, ownerId: Option[Long], requester: MyNDLAUser)( session: DBSession = ReadOnlyAutoSession - ): Try[api.PaginatedTopics] = { + ): Try[api.PaginatedTopicsDTO] = { val offset = (page - 1) * pageSize val topicsT = ownerId @@ -208,7 +208,7 @@ trait ArenaReadService { for { (topics, topicsCount) <- topicsT apiTopics = topics.map { topic => converterService.toApiTopic(topic) } - } yield api.PaginatedTopics( + } yield api.PaginatedTopicsDTO( items = apiTopics, totalCount = topicsCount, pageSize = pageSize, @@ -216,9 +216,9 @@ trait ArenaReadService { ) } - def updateTopic(topicId: Long, newTopic: NewTopic, user: MyNDLAUser)( + def updateTopic(topicId: Long, newTopic: NewTopicDTO, user: MyNDLAUser)( session: DBSession = AutoSession - ): Try[api.Topic] = { + ): Try[api.TopicDTO] = { val updatedTime = clock.now() for { topic <- getCompiledTopic(topicId, user)(session) @@ -239,9 +239,9 @@ trait ArenaReadService { } yield converterService.toApiTopic(compiledTopic) } - def updatePost(postId: Long, newPost: NewPost, user: MyNDLAUser)( + def updatePost(postId: Long, newPost: NewPostDTO, user: MyNDLAUser)( session: DBSession = AutoSession - ): Try[api.Post] = { + ): Try[api.PostDTO] = { val updatedTime = clock.now() for { maybePost <- arenaRepository.getPost(postId)(session) @@ -258,7 +258,7 @@ trait ArenaReadService { def getRepliesForPost(parentPostId: Long, requester: MyNDLAUser)( session: DBSession = AutoSession - ): Try[List[api.Post]] = Try { + ): Try[List[api.PostDTO]] = Try { val replies = arenaRepository.getReplies(parentPostId, requester)(session).? replies.map(r => { val replyReplies = getRepliesForPost(r.post.id, requester)(session).? @@ -275,7 +275,7 @@ trait ArenaReadService { Failure(AccessDeniedException.forbidden) } - def newCategory(newCategory: NewCategory)(session: DBSession = AutoSession): Try[Category] = { + def newCategory(newCategory: NewCategoryDTO)(session: DBSession = AutoSession): Try[CategoryDTO] = { val toInsert = domain.InsertCategory( newCategory.title, newCategory.description, @@ -288,14 +288,14 @@ trait ArenaReadService { } } - def getNewRank(existing: api.CategoryWithTopics, newParentId: Option[Long])(session: DBSession): Try[Int] = { + def getNewRank(existing: api.CategoryWithTopicsDTO, newParentId: Option[Long])(session: DBSession): Try[Int] = { val parentHasChanged = existing.parentCategoryId.exists(newParentId.contains) if (parentHasChanged) { arenaRepository.getNextParentRank(newParentId)(session) } else Success(existing.rank) } - private def validateParentCategory(category: api.CategoryType, maybeNewParentId: Option[Long], user: MyNDLAUser)( + private def validateParentCategory(category: api.CategoryTypeDTO, maybeNewParentId: Option[Long], user: MyNDLAUser)( session: DBSession ): Try[Unit] = { maybeNewParentId match { @@ -325,9 +325,9 @@ trait ArenaReadService { } } - def updateCategory(categoryId: Long, newCategory: NewCategory, user: MyNDLAUser)( + def updateCategory(categoryId: Long, newCategory: NewCategoryDTO, user: MyNDLAUser)( session: DBSession = AutoSession - ): Try[Category] = { + ): Try[CategoryDTO] = { val toInsert = domain.InsertCategory( newCategory.title, newCategory.description, @@ -340,7 +340,7 @@ trait ArenaReadService { newRank <- getNewRank(existing, toInsert.parentCategoryId)(session) updated <- arenaRepository.updateCategory(categoryId, toInsert, newRank)(session) following <- arenaRepository.getCategoryFollowing(categoryId, user.id)(session) - subcategories <- getCategories(user, filterFollowed = false, CategorySort.ByRank, categoryId.some)(session) + subcategories <- getCategories(user, filterFollowed = false, CategorySortDTO.ByRank, categoryId.some)(session) breadcrumbs <- arenaRepository.getBreadcrumbs(existing.id)(session) } yield converterService.toApiCategory( updated, @@ -352,7 +352,7 @@ trait ArenaReadService { ) } - def postTopic(categoryId: Long, newTopic: NewTopic, user: MyNDLAUser): Try[api.Topic] = { + def postTopic(categoryId: Long, newTopic: NewTopicDTO, user: MyNDLAUser): Try[api.TopicDTO] = { arenaRepository.withSession { session => val created = clock.now() for { @@ -381,7 +381,7 @@ trait ArenaReadService { Success(()) } - def postPost(topicId: Long, newPost: NewPost, user: MyNDLAUser): Try[api.Post] = + def postPost(topicId: Long, newPost: NewPostDTO, user: MyNDLAUser): Try[api.PostDTO] = arenaRepository.withSession { session => val created = clock.now() for { @@ -424,19 +424,19 @@ trait ArenaReadService { def getCategory(categoryId: Long, page: Long, pageSize: Long, requester: MyNDLAUser)( session: DBSession = ReadOnlyAutoSession - ): Try[api.CategoryWithTopics] = { + ): Try[api.CategoryWithTopicsDTO] = { val offset = (page - 1) * pageSize for { maybeCategory <- arenaRepository.getCategory(categoryId, includeHidden = requester.isAdmin)(session) category <- maybeCategory.toTry(NotFoundException(s"Could not find category with id $categoryId")) topics <- arenaRepository.getTopicsForCategory(categoryId, offset, pageSize, requester)(session) - subcats <- getCategories(requester, filterFollowed = false, CategorySort.ByRank, category.id.some)(session) + subcats <- getCategories(requester, filterFollowed = false, CategorySortDTO.ByRank, category.id.some)(session) topicsCount <- arenaRepository.getTopicCountForCategory(categoryId)(session) breadcrumb <- arenaRepository.getBreadcrumbs(categoryId)(session) postsCount <- arenaRepository.getPostCountForCategory(categoryId)(session) following <- arenaRepository.getCategoryFollowing(categoryId, requester.id)(session) tt = topics.map(topic => converterService.toApiTopic(topic)) - } yield api.CategoryWithTopics( + } yield api.CategoryWithTopicsDTO( id = categoryId, title = category.title, description = category.description, @@ -467,7 +467,7 @@ trait ArenaReadService { def getTopic(topicId: Long, user: MyNDLAUser, page: Long, pageSize: Long)( session: DBSession = AutoSession - ): Try[api.TopicWithPosts] = { + ): Try[api.TopicWithPostsDTO] = { val offset = (page - 1) * pageSize for { topic <- getCompiledTopic(topicId, user)(session) @@ -484,7 +484,7 @@ trait ArenaReadService { def getRepliesForPosts(posts: List[CompiledPost], requester: MyNDLAUser)( session: DBSession = AutoSession - ): Try[List[api.Post]] = Try { + ): Try[List[api.PostDTO]] = Try { posts.map(post => { val replies = getRepliesForPost(post.post.id, requester)(session).? converterService.toApiPost(post, requester, replies) @@ -499,7 +499,7 @@ trait ArenaReadService { read.map(_ => ()) } - def followTopic(topicId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.TopicWithPosts] = { + def followTopic(topicId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.TopicWithPostsDTO] = { for { apiTopic <- getTopic(topicId, user, 1, 10)(session) following <- arenaRepository.getTopicFollowing(topicId, user.id)(session) @@ -507,7 +507,7 @@ trait ArenaReadService { } yield apiTopic } - def unfollowTopic(topicId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.TopicWithPosts] = { + def unfollowTopic(topicId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.TopicWithPostsDTO] = { for { apiTopic <- getTopic(topicId, user, 0, 0)(session) following <- arenaRepository.getTopicFollowing(topicId, user.id)(session) @@ -515,7 +515,7 @@ trait ArenaReadService { } yield apiTopic } - def upvotePost(postId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.Post] = { + def upvotePost(postId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.PostDTO] = { for { maybePost <- arenaRepository.getPost(postId)(session) (post, owner) <- maybePost.toTry(NotFoundException(s"Could not find post with id $postId")) @@ -533,7 +533,7 @@ trait ArenaReadService { } yield converterService.toApiPost(compiledPost, user, replies) } - def unUpvotePost(postId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.Post] = { + def unUpvotePost(postId: Long, user: MyNDLAUser)(session: DBSession = AutoSession): Try[api.PostDTO] = { for { maybePost <- arenaRepository.getPost(postId)(session) (post, owner) <- maybePost.toTry(NotFoundException(s"Could not find post with id $postId")) @@ -548,7 +548,7 @@ trait ArenaReadService { def followCategory(categoryId: Long, user: MyNDLAUser)( session: DBSession = AutoSession - ): Try[api.CategoryWithTopics] = { + ): Try[api.CategoryWithTopicsDTO] = { for { apiCategory <- getCategory(categoryId, 1, 10, user)(session) following <- arenaRepository.getCategoryFollowing(categoryId, user.id)(session) @@ -558,7 +558,7 @@ trait ArenaReadService { def unfollowCategory(categoryId: Long, user: MyNDLAUser)( session: DBSession = AutoSession - ): Try[api.CategoryWithTopics] = { + ): Try[api.CategoryWithTopicsDTO] = { for { apiTopic <- getCategory(categoryId, 1, 10, user)(session) following <- arenaRepository.getCategoryFollowing(categoryId, user.id)(session) @@ -569,9 +569,9 @@ trait ArenaReadService { def getCategories( requester: MyNDLAUser, filterFollowed: Boolean, - sort: CategorySort, + sort: CategorySortDTO, parentCategoryId: Option[Long] - )(session: DBSession = ReadOnlyAutoSession): Try[List[api.Category]] = + )(session: DBSession = ReadOnlyAutoSession): Try[List[api.CategoryDTO]] = arenaRepository .getCategories(requester, filterFollowed, sort, parentCategoryId)(session) .flatMap(categories => { diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConfigService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConfigService.scala index 4ce8febedf..431d877ebe 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConfigService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConfigService.scala @@ -10,7 +10,7 @@ package no.ndla.myndlaapi.service import no.ndla.common.{Clock, model} import no.ndla.common.errors.{AccessDeniedException, NotFoundException} -import no.ndla.common.model.api.config.ConfigMetaRestricted +import no.ndla.common.model.api.config.ConfigMetaRestrictedDTO import no.ndla.common.model.domain.config.{BooleanValue, ConfigKey, ConfigMeta, ConfigMetaValue, StringListValue} import no.ndla.myndlaapi.repository.ConfigRepository import no.ndla.network.tapir.auth.Permission.LEARNINGPATH_API_ADMIN @@ -55,15 +55,15 @@ trait ConfigService { ) } - def getConfig(configKey: ConfigKey): Try[ConfigMetaRestricted] = { + def getConfig(configKey: ConfigKey): Try[ConfigMetaRestrictedDTO] = { configRepository.getConfigWithKey(configKey).flatMap { case None => Failure(NotFoundException(s"Configuration with key $configKey does not exist")) case Some(key) => Success(asApiConfigRestricted(key)) } } - private def asApiConfigRestricted(configValue: ConfigMeta): ConfigMetaRestricted = { - model.api.config.ConfigMetaRestricted( + private def asApiConfigRestricted(configValue: ConfigMeta): ConfigMetaRestrictedDTO = { + model.api.config.ConfigMetaRestrictedDTO( key = configValue.key.entryName, value = configValue.valueToEither ) @@ -71,9 +71,9 @@ trait ConfigService { def updateConfig( configKey: ConfigKey, - value: model.api.config.ConfigMetaValue, + value: model.api.config.ConfigMetaValueDTO, userInfo: TokenUser - ): Try[model.api.config.ConfigMeta] = if (!userInfo.hasPermission(LEARNINGPATH_API_ADMIN)) { + ): Try[model.api.config.ConfigMetaDTO] = if (!userInfo.hasPermission(LEARNINGPATH_API_ADMIN)) { Failure(AccessDeniedException("Only administrators can edit configuration.")) } else { val config = ConfigMeta(configKey, ConfigMetaValue.from(value), clock.now(), userInfo.id) @@ -83,8 +83,8 @@ trait ConfigService { } yield asApiConfig(stored) } - private def asApiConfig(configValue: ConfigMeta): model.api.config.ConfigMeta = { - model.api.config.ConfigMeta( + private def asApiConfig(configValue: ConfigMeta): model.api.config.ConfigMetaDTO = { + model.api.config.ConfigMetaDTO( configValue.key.entryName, configValue.valueToEither, configValue.updatedAt, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConverterService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConverterService.scala index 928da8fb9b..2022e7fd50 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConverterService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/ConverterService.scala @@ -8,7 +8,7 @@ package no.ndla.myndlaapi.service import no.ndla.common.model.domain.myndla.MyNDLAUser -import no.ndla.myndlaapi.model.api.ArenaUser +import no.ndla.myndlaapi.model.api.ArenaUserDTO import no.ndla.myndlaapi.model.arena.domain.database.{CompiledFlag, CompiledPost, CompiledTopic} import no.ndla.myndlaapi.model.arena.{api, domain} @@ -22,10 +22,10 @@ trait ConverterService { topicCount: Long, postCount: Long, isFollowing: Boolean, - subcategories: List[api.Category], - breadcrumbs: List[api.CategoryBreadcrumb] - ): api.Category = { - api.Category( + subcategories: List[api.CategoryDTO], + breadcrumbs: List[api.CategoryBreadcrumbDTO] + ): api.CategoryDTO = { + api.CategoryDTO( id = category.id, title = category.title, description = category.description, @@ -41,8 +41,8 @@ trait ConverterService { ) } - def toApiTopic(compiledTopic: CompiledTopic): api.Topic = { - api.Topic( + def toApiTopic(compiledTopic: CompiledTopic): api.TopicDTO = { + api.TopicDTO( id = compiledTopic.topic.id, title = compiledTopic.topic.title, created = compiledTopic.topic.created, @@ -60,17 +60,17 @@ trait ConverterService { compiledTopic: CompiledTopic, page: Long, pageSize: Long, - posts: List[api.Post] - ): api.TopicWithPosts = { + posts: List[api.PostDTO] + ): api.TopicWithPostsDTO = { - val pagination = api.PaginatedPosts( + val pagination = api.PaginatedPostsDTO( page = page, pageSize = pageSize, totalCount = compiledTopic.postCount, items = posts ) - api.TopicWithPosts( + api.TopicWithPostsDTO( id = compiledTopic.topic.id, title = compiledTopic.topic.title, created = compiledTopic.topic.created, @@ -85,12 +85,12 @@ trait ConverterService { ) } - def toApiFlag(flag: CompiledFlag): api.Flag = { - api.Flag( + def toApiFlag(flag: CompiledFlag): api.FlagDTO = { + api.FlagDTO( id = flag.flag.id, reason = flag.flag.reason, created = flag.flag.created, - flagger = flag.flagger.map(ArenaUser.from), + flagger = flag.flagger.map(ArenaUserDTO.from), resolved = flag.flag.resolved, isResolved = flag.flag.resolved.isDefined ) @@ -99,16 +99,16 @@ trait ConverterService { def toApiPost( compiledPost: CompiledPost, requester: MyNDLAUser, - replies: List[api.Post] - ): api.Post = { + replies: List[api.PostDTO] + ): api.PostDTO = { val maybeFlags = Option.when(requester.isAdmin)(compiledPost.flags.map(toApiFlag)) - api.Post( + api.PostDTO( id = compiledPost.post.id, content = compiledPost.post.content, created = compiledPost.post.created, updated = compiledPost.post.updated, - owner = compiledPost.owner.map(ArenaUser.from), + owner = compiledPost.owner.map(ArenaUserDTO.from), flags = maybeFlags, topicId = compiledPost.post.topic_id, replies = replies, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderConverterService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderConverterService.scala index 8b3aa1a7c9..9c2192e39a 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderConverterService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderConverterService.scala @@ -11,14 +11,14 @@ package no.ndla.myndlaapi.service import cats.implicits.* import no.ndla.common.{Clock, model} import no.ndla.common.errors.ValidationException -import no.ndla.common.model.api.myndla.{UpdatedMyNDLAUser} +import no.ndla.common.model.api.myndla.UpdatedMyNDLAUserDTO import no.ndla.common.model.domain.myndla import no.ndla.common.model.domain.myndla.{ FolderStatus, MyNDLAGroup as DomainMyNDLAGroup, MyNDLAUser as DomainMyNDLAUser } -import no.ndla.myndlaapi.model.api.{Folder, Owner} +import no.ndla.myndlaapi.model.api.{FolderDTO, OwnerDTO} import no.ndla.myndlaapi.model.{api, domain} import no.ndla.network.tapir.auth.Permission.LEARNINGPATH_API_ADMIN import no.ndla.network.tapir.auth.TokenUser @@ -35,17 +35,17 @@ trait FolderConverterService { class FolderConverterService { def toApiFolder( domainFolder: domain.Folder, - breadcrumbs: List[api.Breadcrumb], + breadcrumbs: List[api.BreadcrumbDTO], feideUser: Option[DomainMyNDLAUser], isOwner: Boolean - ): Try[Folder] = { + ): Try[FolderDTO] = { def loop( folder: domain.Folder, - crumbs: List[api.Breadcrumb], + crumbs: List[api.BreadcrumbDTO], feideUser: Option[DomainMyNDLAUser] - ): Try[Folder] = folder.subfolders + ): Try[FolderDTO] = folder.subfolders .traverse(folder => { - val newCrumb = api.Breadcrumb( + val newCrumb = api.BreadcrumbDTO( id = folder.id.toString, name = folder.name ) @@ -56,7 +56,7 @@ trait FolderConverterService { folder.resources .traverse(r => toApiResource(r, isOwner)) .map(resources => { - api.Folder( + api.FolderDTO( id = folder.id.toString, name = folder.name, status = folder.status.toString, @@ -69,7 +69,7 @@ trait FolderConverterService { updated = folder.updated, shared = folder.shared, description = folder.description, - owner = feideUser.flatMap(user => if (user.shareName) Some(Owner(user.displayName)) else None) + owner = feideUser.flatMap(user => if (user.shareName) Some(OwnerDTO(user.displayName)) else None) ) }) ) @@ -77,7 +77,7 @@ trait FolderConverterService { loop(domainFolder, breadcrumbs, feideUser) } - def mergeFolder(existing: domain.Folder, updated: api.UpdatedFolder): domain.Folder = { + def mergeFolder(existing: domain.Folder, updated: api.UpdatedFolderDTO): domain.Folder = { val name = updated.name.getOrElse(existing.name) val status = updated.status.flatMap(FolderStatus.valueOf).getOrElse(existing.status) val description = updated.description.orElse(existing.description) @@ -106,7 +106,7 @@ trait FolderConverterService { ) } - def mergeResource(existing: domain.Resource, updated: api.UpdatedResource): domain.Resource = { + def mergeResource(existing: domain.Resource, updated: api.UpdatedResourceDTO): domain.Resource = { val tags = updated.tags.getOrElse(existing.tags) val resourceId = updated.resourceId.getOrElse(existing.resourceId) @@ -122,7 +122,7 @@ trait FolderConverterService { ) } - def mergeResource(existing: domain.Resource, newResource: api.NewResource): domain.Resource = { + def mergeResource(existing: domain.Resource, newResource: api.NewResourceDTO): domain.Resource = { val tags = newResource.tags.getOrElse(existing.tags) domain.Resource( @@ -137,7 +137,7 @@ trait FolderConverterService { ) } - def toApiResource(domainResource: domain.Resource, isOwner: Boolean): Try[api.Resource] = { + def toApiResource(domainResource: domain.Resource, isOwner: Boolean): Try[api.ResourceDTO] = { val resourceType = domainResource.resourceType val path = domainResource.path val created = domainResource.created @@ -145,7 +145,7 @@ trait FolderConverterService { val resourceId = domainResource.resourceId Success( - api.Resource( + api.ResourceDTO( id = domainResource.id.toString, resourceType = resourceType, path = path, @@ -158,7 +158,7 @@ trait FolderConverterService { } def toNewFolderData( - newFolder: api.NewFolder, + newFolder: api.NewFolderDTO, parentId: Option[UUID], newRank: Int ): Try[domain.NewFolderData] = { @@ -178,9 +178,9 @@ trait FolderConverterService { def toApiUserData( domainUserData: DomainMyNDLAUser, arenaEnabledOrgs: List[String] - ): model.api.myndla.MyNDLAUser = { + ): model.api.myndla.MyNDLAUserDTO = { val arenaEnabled = getArenaEnabled(domainUserData, arenaEnabledOrgs) - model.api.myndla.MyNDLAUser( + model.api.myndla.MyNDLAUserDTO( id = domainUserData.id, feideId = domainUserData.feideId, username = domainUserData.username, @@ -218,8 +218,8 @@ trait FolderConverterService { loop(domainObjects, List()) } - private def toApiGroup(group: DomainMyNDLAGroup): model.api.myndla.MyNDLAGroup = { - model.api.myndla.MyNDLAGroup( + private def toApiGroup(group: DomainMyNDLAGroup): model.api.myndla.MyNDLAGroupDTO = { + model.api.myndla.MyNDLAGroupDTO( id = group.id, displayName = group.displayName, isPrimarySchool = group.isPrimarySchool, @@ -229,7 +229,7 @@ trait FolderConverterService { def mergeUserData( domainUserData: DomainMyNDLAUser, - updatedUser: UpdatedMyNDLAUser, + updatedUser: UpdatedMyNDLAUserDTO, updaterToken: Option[TokenUser], updaterUser: Option[DomainMyNDLAUser], arenaEnabledUsers: List[String] @@ -264,7 +264,7 @@ trait FolderConverterService { ) } - def toDomainResource(newResource: api.NewResource): domain.ResourceDocument = { + def toDomainResource(newResource: api.NewResourceDTO): domain.ResourceDocument = { val tags = newResource.tags.getOrElse(List.empty) domain.ResourceDocument( tags = tags, diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderReadService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderReadService.scala index e92d40ac1d..b7f795ebcb 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderReadService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderReadService.scala @@ -12,12 +12,12 @@ import cats.implicits.* import no.ndla.common.Clock import no.ndla.common.errors.NotFoundException import no.ndla.common.implicits.TryQuestionMark -import no.ndla.common.model.api.SingleResourceStats -import no.ndla.common.model.api.myndla.MyNDLAUser +import no.ndla.common.model.api.SingleResourceStatsDTO +import no.ndla.common.model.api.myndla.MyNDLAUserDTO import no.ndla.common.model.domain.{ResourceType, myndla} import no.ndla.common.model.domain.myndla.FolderStatus import no.ndla.myndlaapi.FavoriteFolderDefaultName -import no.ndla.myndlaapi.model.api.{ExportedUserData, Folder, Resource, UserFolder} +import no.ndla.myndlaapi.model.api.{ExportedUserDataDTO, FolderDTO, ResourceDTO, UserFolderDTO} import no.ndla.myndlaapi.model.{api, domain} import no.ndla.myndlaapi.repository.{FolderRepository, UserRepository} import no.ndla.network.clients.FeideApiClient @@ -40,7 +40,7 @@ trait FolderReadService { includeSubfolders: Boolean, includeResources: Boolean, feideId: FeideID - )(session: DBSession): Try[List[Folder]] = { + )(session: DBSession): Try[List[FolderDTO]] = { for { withFavorite <- mergeWithFavorite(topFolders, feideId) withData <- getSubfolders(withFavorite, includeSubfolders, includeResources)(session) @@ -50,7 +50,7 @@ trait FolderReadService { v => folderConverterService.toApiFolder( v, - List(api.Breadcrumb(id = v.id.toString, name = v.name)), + List(api.BreadcrumbDTO(id = v.id.toString, name = v.name)), feideUser, feideUser.exists(_.feideId == v.feideId) ) @@ -76,7 +76,7 @@ trait FolderReadService { (v: domain.Folder) => { folderConverterService.toApiFolder( v, - List(api.Breadcrumb(id = v.id.toString, name = v.name)), + List(api.BreadcrumbDTO(id = v.id.toString, name = v.name)), v.user, v.user.exists(_.feideId == v.feideId) ) @@ -90,7 +90,7 @@ trait FolderReadService { includeSubfolders: Boolean, includeResources: Boolean, feideId: FeideID - ): Try[UserFolder] = { + ): Try[UserFolderDTO] = { folderRepository.rollbackOnFailure(session => { for { myFolders <- folderRepository.foldersWithFeideAndParentID(None, feideId) @@ -98,11 +98,11 @@ trait FolderReadService { folders <- getSubFoldersAndResources(myFolders, includeSubfolders, includeResources, feideId)(session) sharedFolders <- getSharedSubFoldersAndResources(savedSharedFolders)(session) - } yield UserFolder(folders = folders, sharedFolders = sharedFolders) + } yield UserFolderDTO(folders = folders, sharedFolders = sharedFolders) }) } - def getSharedFolder(id: UUID, maybeFeideToken: Option[FeideAccessToken]): Try[Folder] = { + def getSharedFolder(id: UUID, maybeFeideToken: Option[FeideAccessToken]): Try[FolderDTO] = { implicit val session: DBSession = folderRepository.getSession(true) for { feideId <- maybeFeideToken.traverse(token => feideApiClient.getFeideID(Some(token))) @@ -184,20 +184,20 @@ trait FolderReadService { includeSubfolders: Boolean, includeResources: Boolean, feideAccessToken: Option[FeideAccessToken] - ): Try[UserFolder] = { + ): Try[UserFolderDTO] = { withFeideId(feideAccessToken)(getFoldersAuthenticated(includeSubfolders, includeResources, _)) } - def getBreadcrumbs(folder: domain.Folder)(implicit session: DBSession): Try[List[api.Breadcrumb]] = { + def getBreadcrumbs(folder: domain.Folder)(implicit session: DBSession): Try[List[api.BreadcrumbDTO]] = { @tailrec - def getParentRecursively(folder: domain.Folder, crumbs: List[api.Breadcrumb]): Try[List[api.Breadcrumb]] = { + def getParentRecursively(folder: domain.Folder, crumbs: List[api.BreadcrumbDTO]): Try[List[api.BreadcrumbDTO]] = { folder.parentId match { case None => Success(crumbs) case Some(parentId) => folderRepository.folderWithId(parentId) match { case Failure(ex) => Failure(ex) case Success(p) => - val newCrumb = api.Breadcrumb( + val newCrumb = api.BreadcrumbDTO( id = p.id.toString, name = p.name ) @@ -209,7 +209,7 @@ trait FolderReadService { getParentRecursively(folder, List.empty) match { case Failure(ex) => Failure(ex) case Success(value) => - val newCrumb = api.Breadcrumb( + val newCrumb = api.BreadcrumbDTO( id = folder.id.toString, name = folder.name ) @@ -222,7 +222,7 @@ trait FolderReadService { includeSubfolders: Boolean, includeResources: Boolean, feideAccessToken: Option[FeideAccessToken] - ): Try[Folder] = { + ): Try[FolderDTO] = { implicit val session: DBSession = folderRepository.getSession(true) for { feideId <- feideApiClient.getFeideID(feideAccessToken) @@ -242,7 +242,7 @@ trait FolderReadService { def getAllResources( size: Int, feideAccessToken: Option[FeideAccessToken] = None - ): Try[List[Resource]] = { + ): Try[List[ResourceDTO]] = { for { feideId <- feideApiClient.getFeideID(feideAccessToken) resources <- folderRepository.resourcesWithFeideId(feideId, size) @@ -269,7 +269,7 @@ trait FolderReadService { private def getFeideUserDataAuthenticated( feideId: FeideID, feideAccessToken: Option[FeideAccessToken] - ): Try[MyNDLAUser] = + ): Try[MyNDLAUserDTO] = for { users <- configService.getMyNDLAEnabledUsers user <- userRepository.rollbackOnFailure(session => @@ -278,10 +278,10 @@ trait FolderReadService { orgs <- configService.getMyNDLAEnabledOrgs } yield folderConverterService.toApiUserData(user, orgs) - def getStats: Option[api.Stats] = { + def getStats: Option[api.StatsDTO] = { implicit val session: DBSession = folderRepository.getSession(true) val groupedResources = folderRepository.numberOfResourcesGrouped() - val favouritedResources = groupedResources.map(gr => api.ResourceStats(gr._2, gr._1)) + val favouritedResources = groupedResources.map(gr => api.ResourceStatsDTO(gr._2, gr._1)) val favourited = groupedResources.map(gr => gr._2 -> gr._1).toMap for { numberOfUsers <- userRepository.numberOfUsers() @@ -290,7 +290,7 @@ trait FolderReadService { numberOfTags <- folderRepository.numberOfTags() numberOfSubjects <- userRepository.numberOfFavouritedSubjects() numberOfSharedFolders <- folderRepository.numberOfSharedFolders() - stats = api.Stats( + stats = api.StatsDTO( numberOfUsers, numberOfFolders, numberOfResources, @@ -303,7 +303,7 @@ trait FolderReadService { } yield stats } - def exportUserData(maybeFeideToken: Option[FeideAccessToken]): Try[ExportedUserData] = { + def exportUserData(maybeFeideToken: Option[FeideAccessToken]): Try[ExportedUserDataDTO] = { withFeideId(maybeFeideToken)(feideId => exportUserDataAuthenticated(maybeFeideToken, feideId)) } @@ -312,7 +312,7 @@ trait FolderReadService { folderRepository.getAllFavorites(session) } - def getRecentFavorite(size: Option[Int], excludeResourceTypes: List[ResourceType]): Try[List[Resource]] = { + def getRecentFavorite(size: Option[Int], excludeResourceTypes: List[ResourceType]): Try[List[ResourceDTO]] = { implicit val session: DBSession = folderRepository.getSession(true) folderRepository.getRecentFavorited(size, excludeResourceTypes)(session) match { case Failure(ex) => Failure(ex) @@ -323,7 +323,7 @@ trait FolderReadService { def getFavouriteStatsForResource( resourceIds: List[String], resourceTypes: List[String] - ): Try[List[SingleResourceStats]] = { + ): Try[List[SingleResourceStatsDTO]] = { implicit val session: DBSession = folderRepository.getSession(true) val result = @@ -331,7 +331,7 @@ trait FolderReadService { val countList = resourceTypes.map(rt => { folderRepository.numberOfFavouritesForResource(id, rt).? }) - SingleResourceStats(id, countList.sum) + SingleResourceStatsDTO(id, countList.sum) }) @@ -341,11 +341,11 @@ trait FolderReadService { private def exportUserDataAuthenticated( maybeFeideAccessToken: Option[FeideAccessToken], feideId: FeideID - ): Try[ExportedUserData] = + ): Try[ExportedUserDataDTO] = for { folders <- getFoldersAuthenticated(includeSubfolders = true, includeResources = true, feideId) feideUser <- getFeideUserDataAuthenticated(feideId, maybeFeideAccessToken) - } yield api.ExportedUserData( + } yield api.ExportedUserDataDTO( userData = feideUser, folders = folders.folders ) diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderWriteService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderWriteService.scala index 8e0279f7a7..3b4d0615b2 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderWriteService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/FolderWriteService.scala @@ -23,14 +23,14 @@ import no.ndla.myndlaapi.model.domain.FolderSortObject.{ SharedFolderSorting } import no.ndla.myndlaapi.model.api.{ - ExportedUserData, - Folder, - FolderSortRequest, - NewFolder, - NewResource, - Resource, - UpdatedFolder, - UpdatedResource + ExportedUserDataDTO, + FolderDTO, + FolderSortRequestDTO, + NewFolderDTO, + NewResourceDTO, + ResourceDTO, + UpdatedFolderDTO, + UpdatedResourceDTO } import no.ndla.myndlaapi.model.{api, domain} import no.ndla.myndlaapi.model.domain.{ @@ -67,7 +67,7 @@ trait FolderWriteService { private[service] def isOperationAllowedOrAccessDenied( feideId: FeideID, feideAccessToken: Option[FeideAccessToken], - updatedFolder: UpdatedFolder + updatedFolder: UpdatedFolderDTO ): Try[?] = { getMyNDLAUser(feideId, feideAccessToken).flatMap(myNDLAUser => { if (myNDLAUser.isStudent && updatedFolder.status.contains(FolderStatus.SHARED.toString)) @@ -123,7 +123,7 @@ trait FolderWriteService { val clonedResources = sourceFolder.resources.traverse(res => { val newResource = - NewResource( + NewResourceDTO( resourceType = res.resourceType, path = res.path, tags = if (isOwner) res.tags.some else None, @@ -160,7 +160,7 @@ trait FolderWriteService { )(implicit session: DBSession ): Try[domain.Folder] = { - val sourceFolderCopy = NewFolder( + val sourceFolderCopy = NewFolderDTO( name = sourceFolder.name, parentId = None, status = FolderStatus.PRIVATE.toString.some, @@ -197,7 +197,7 @@ trait FolderWriteService { sourceId: UUID, destinationId: Option[UUID], feideAccessToken: Option[FeideAccessToken] - ): Try[Folder] = { + ): Try[FolderDTO] = { folderRepository.rollbackOnFailure { implicit session => for { feideId <- feideApiClient.getFeideID(feideAccessToken) @@ -218,7 +218,7 @@ trait FolderWriteService { } } - private def importFolders(toImport: Seq[Folder], feideId: FeideID)(implicit + private def importFolders(toImport: Seq[FolderDTO], feideId: FeideID)(implicit session: DBSession ): Try[Seq[domain.Folder]] = toImport.traverse(folder => @@ -232,10 +232,10 @@ trait FolderWriteService { ) private def importUserDataAuthenticated( - toImport: ExportedUserData, + toImport: ExportedUserDataDTO, feideId: FeideID, maybeFeideToken: Option[FeideAccessToken] - ): Try[ExportedUserData] = { + ): Try[ExportedUserDataDTO] = { folderRepository.rollbackOnFailure { session => for { _ <- canWriteDuringMyNDLAWriteRestrictionsOrAccessDenied(feideId, maybeFeideToken) @@ -246,9 +246,9 @@ trait FolderWriteService { } def importUserData( - toImport: ExportedUserData, + toImport: ExportedUserDataDTO, maybeFeideToken: Option[FeideAccessToken] - ): Try[ExportedUserData] = { + ): Try[ExportedUserDataDTO] = { feideApiClient .getFeideID(maybeFeideToken) .flatMap(feideId => importUserDataAuthenticated(toImport, feideId, maybeFeideToken)) @@ -265,9 +265,9 @@ trait FolderWriteService { def updateFolder( id: UUID, - updatedFolder: UpdatedFolder, + updatedFolder: UpdatedFolderDTO, feideAccessToken: Option[FeideAccessToken] - ): Try[Folder] = { + ): Try[FolderDTO] = { implicit val session: DBSession = folderRepository.getSession(readOnly = false) for { feideId <- feideApiClient.getFeideID(feideAccessToken) @@ -286,9 +286,9 @@ trait FolderWriteService { def updateResource( id: UUID, - updatedResource: UpdatedResource, + updatedResource: UpdatedResourceDTO, feideAccessToken: Option[FeideAccessToken] = None - ): Try[Resource] = { + ): Try[ResourceDTO] = { for { feideId <- feideApiClient.getFeideID(feideAccessToken) _ <- canWriteDuringMyNDLAWriteRestrictionsOrAccessDenied(feideId, feideAccessToken) @@ -334,7 +334,7 @@ trait FolderWriteService { ) deletedFolderId <- deleteRecursively(folderWithData, feideId) siblingsToSort = parent.childrenFolders.filterNot(_.id == deletedFolderId) - sortRequest = FolderSortRequest(sortedIds = siblingsToSort.map(_.id)) + sortRequest = FolderSortRequestDTO(sortedIds = siblingsToSort.map(_.id)) _ <- performSort(siblingsToSort, sortRequest, feideId, sharedFolderSort = false) } yield deletedFolderId } @@ -355,7 +355,7 @@ trait FolderWriteService { id <- deleteResourceIfNoConnection(folderId, resourceId) parent <- getFolderWithDirectChildren(folder.id.some, feideId) siblingsToSort = parent.childrenResources.filterNot(c => c.resourceId == resourceId && c.folderId == folderId) - sortRequest = api.FolderSortRequest(sortedIds = siblingsToSort.map(_.resourceId)) + sortRequest = api.FolderSortRequestDTO(sortedIds = siblingsToSort.map(_.resourceId)) _ = updateSearchApi(resource) _ <- performSort(siblingsToSort, sortRequest, feideId, sharedFolderSort = false) } yield id @@ -373,7 +373,7 @@ trait FolderWriteService { private def performSort( rankables: Seq[Rankable], - sortRequest: api.FolderSortRequest, + sortRequest: api.FolderSortRequestDTO, feideId: FeideID, sharedFolderSort: Boolean ): Try[Unit] = { @@ -407,14 +407,14 @@ trait FolderWriteService { } } - private def sortRootFolders(sortRequest: api.FolderSortRequest, feideId: FeideID): Try[Unit] = { + private def sortRootFolders(sortRequest: api.FolderSortRequestDTO, feideId: FeideID): Try[Unit] = { val session = folderRepository.getSession(true) folderRepository .foldersWithFeideAndParentID(None, feideId)(session) .flatMap(rootFolders => performSort(rootFolders, sortRequest, feideId, sharedFolderSort = false)) } - private def sortSavedSharedFolders(sortRequest: api.FolderSortRequest, feideId: FeideID): Try[Unit] = { + private def sortSavedSharedFolders(sortRequest: api.FolderSortRequestDTO, feideId: FeideID): Try[Unit] = { val session = folderRepository.getSession(true) folderRepository .getSavedSharedFolders(feideId)(session) @@ -423,7 +423,7 @@ trait FolderWriteService { private def sortNonRootFolderResources( folderId: UUID, - sortRequest: api.FolderSortRequest, + sortRequest: api.FolderSortRequestDTO, feideId: FeideID )(implicit session: DBSession @@ -434,7 +434,7 @@ trait FolderWriteService { private def sortNonRootFolderSubfolders( folderId: UUID, - sortRequest: api.FolderSortRequest, + sortRequest: api.FolderSortRequestDTO, feideId: FeideID )(implicit session: DBSession @@ -445,7 +445,7 @@ trait FolderWriteService { def sortFolder( folderSortObject: domain.FolderSortObject, - sortRequest: api.FolderSortRequest, + sortRequest: api.FolderSortRequestDTO, feideAccessToken: Option[FeideAccessToken] ): Try[Unit] = { implicit val session: DBSession = folderRepository.getSession(readOnly = false) @@ -539,10 +539,10 @@ trait FolderWriteService { private def getNextRank(siblings: Seq[?]): Int = siblings.length + 1 private[service] def changeStatusToSharedIfParentIsShared( - newFolder: NewFolder, + newFolder: NewFolderDTO, parentFolder: Option[domain.Folder], isCloning: Boolean - ): NewFolder = { + ): NewFolderDTO = { import FolderStatus.SHARED parentFolder match { @@ -552,7 +552,7 @@ trait FolderWriteService { } private def createNewFolder( - newFolder: NewFolder, + newFolder: NewFolderDTO, feideId: FeideID, makeUniqueNamePostfix: Option[String], isCloning: Boolean @@ -591,7 +591,7 @@ trait FolderWriteService { } } - def newFolder(newFolder: NewFolder, feideAccessToken: Option[FeideAccessToken]): Try[Folder] = { + def newFolder(newFolder: NewFolderDTO, feideAccessToken: Option[FeideAccessToken]): Try[FolderDTO] = { implicit val session: DBSession = folderRepository.getSession(readOnly = false) for { feideId <- feideApiClient.getFeideID(feideAccessToken) @@ -605,7 +605,7 @@ trait FolderWriteService { private def createOrUpdateFolderResourceConnection( folderId: UUID, - newResource: NewResource, + newResource: NewResourceDTO, feideId: FeideID )(implicit session: DBSession @@ -631,9 +631,9 @@ trait FolderWriteService { def newFolderResourceConnection( folderId: UUID, - newResource: NewResource, + newResource: NewResourceDTO, feideAccessToken: Option[FeideAccessToken] - ): Try[Resource] = { + ): Try[ResourceDTO] = { implicit val session: DBSession = folderRepository.getSession(readOnly = false) for { feideId <- feideApiClient.getFeideID(feideAccessToken) @@ -644,7 +644,7 @@ trait FolderWriteService { } private[service] def createNewResourceOrUpdateExisting( - newResource: NewResource, + newResource: NewResourceDTO, folderId: UUID, siblings: domain.FolderAndDirectChildren, feideId: FeideID diff --git a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/UserService.scala b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/UserService.scala index eb6279c656..a69e64828d 100644 --- a/myndla-api/src/main/scala/no/ndla/myndlaapi/service/UserService.scala +++ b/myndla-api/src/main/scala/no/ndla/myndlaapi/service/UserService.scala @@ -12,9 +12,9 @@ import no.ndla.common.Clock import no.ndla.common.errors.{AccessDeniedException, NotFoundException, ValidationException} import no.ndla.common.implicits.TryQuestionMark import no.ndla.common.model.api.myndla -import no.ndla.common.model.api.myndla.UpdatedMyNDLAUser +import no.ndla.common.model.api.myndla.UpdatedMyNDLAUserDTO import no.ndla.common.model.domain.myndla.{ArenaGroup, MyNDLAGroup, MyNDLAUser, MyNDLAUserDocument, UserRole} -import no.ndla.myndlaapi.model.api.{ArenaUser, PaginatedArenaUsers} +import no.ndla.myndlaapi.model.api.{ArenaUserDTO, PaginatedArenaUsersDTO} import no.ndla.myndlaapi.repository.UserRepository import no.ndla.network.clients.{FeideApiClient, FeideGroup} import no.ndla.network.model.{FeideAccessToken, FeideID} @@ -30,10 +30,10 @@ trait UserService { val userService: UserService class UserService { - def getArenaUserByUserName(username: String): Try[ArenaUser] = { + def getArenaUserByUserName(username: String): Try[ArenaUserDTO] = { userRepository.userWithUsername(username) match { case Failure(ex) => Failure(ex) - case Success(Some(user)) => Success(ArenaUser.from(user)) + case Success(Some(user)) => Success(ArenaUserDTO.from(user)) case Success(None) => Failure(NotFoundException(s"User with username '$username' was not found")) } } @@ -48,12 +48,12 @@ trait UserService { def getArenaUsersPaginated(page: Long, pageSize: Long, filterTeachers: Boolean, query: Option[String])( session: DBSession = ReadOnlyAutoSession - ): Try[PaginatedArenaUsers] = { + ): Try[PaginatedArenaUsersDTO] = { val offset = (page - 1) * pageSize for { (totalCount, users) <- userRepository.getUsersPaginated(offset, pageSize, filterTeachers, query)(session) - arenaUsers = users.map(ArenaUser.from) - } yield PaginatedArenaUsers(totalCount, page, pageSize, arenaUsers) + arenaUsers = users.map(ArenaUserDTO.from) + } yield PaginatedArenaUsersDTO(totalCount, page, pageSize, arenaUsers) } def getMyNdlaUserDataDomain( @@ -78,7 +78,7 @@ trait UserService { } yield user } - def getMyNDLAUserData(feideAccessToken: Option[FeideAccessToken]): Try[myndla.MyNDLAUser] = { + def getMyNDLAUserData(feideAccessToken: Option[FeideAccessToken]): Try[myndla.MyNDLAUserDTO] = { for { users <- configService.getMyNDLAEnabledUsers userData <- getMyNdlaUserDataDomain(feideAccessToken, users) @@ -105,22 +105,22 @@ trait UserService { } def updateMyNDLAUserData( - updatedUser: UpdatedMyNDLAUser, + updatedUser: UpdatedMyNDLAUserDTO, feideAccessToken: Option[FeideAccessToken] - ): Try[myndla.MyNDLAUser] = { + ): Try[myndla.MyNDLAUserDTO] = { feideApiClient .getFeideID(feideAccessToken) .flatMap(feideId => updateFeideUserDataAuthenticated(updatedUser, feideId, feideAccessToken)(AutoSession)) } - def importUser(userData: myndla.MyNDLAUser, feideId: FeideID, feideAccessToken: Option[FeideAccessToken])(implicit - session: DBSession - ): Try[myndla.MyNDLAUser] = + def importUser(userData: myndla.MyNDLAUserDTO, feideId: FeideID, feideAccessToken: Option[FeideAccessToken])( + implicit session: DBSession + ): Try[myndla.MyNDLAUserDTO] = for { existingUser <- userService.getOrCreateMyNDLAUserIfNotExist(feideId, feideAccessToken, List.empty)(session) newFavorites = (existingUser.favoriteSubjects ++ userData.favoriteSubjects).distinct shareName = existingUser.shareName || userData.shareName - updatedFeideUser = UpdatedMyNDLAUser( + updatedFeideUser = UpdatedMyNDLAUserDTO( favoriteSubjects = Some(newFavorites), arenaEnabled = None, shareName = Some(shareName), @@ -130,10 +130,10 @@ trait UserService { } yield updated private def updateFeideUserDataAuthenticated( - updatedUser: UpdatedMyNDLAUser, + updatedUser: UpdatedMyNDLAUserDTO, feideId: FeideID, feideAccessToken: Option[FeideAccessToken] - )(implicit session: DBSession): Try[myndla.MyNDLAUser] = { + )(implicit session: DBSession): Try[myndla.MyNDLAUserDTO] = { for { _ <- folderWriteService.canWriteDuringMyNDLAWriteRestrictionsOrAccessDenied(feideId, feideAccessToken) existingUserData <- getMyNDLAUserOrFail(feideId) @@ -152,11 +152,11 @@ trait UserService { } def adminUpdateMyNDLAUserData( - updatedUser: UpdatedMyNDLAUser, + updatedUser: UpdatedMyNDLAUserDTO, feideId: Option[String], updaterToken: Option[TokenUser], updaterMyNdla: Option[MyNDLAUser] - ): Try[myndla.MyNDLAUser] = { + ): Try[myndla.MyNDLAUserDTO] = { feideId match { case None => Failure(ValidationException("feideId", "You need to supply a feideId to update a user.")) case Some(id) => @@ -179,9 +179,9 @@ trait UserService { def adminUpdateMyNDLAUserData( userId: Long, - updatedUser: UpdatedMyNDLAUser, + updatedUser: UpdatedMyNDLAUserDTO, updaterMyNdla: MyNDLAUser - )(session: DBSession = AutoSession): Try[myndla.MyNDLAUser] = { + )(session: DBSession = AutoSession): Try[myndla.MyNDLAUserDTO] = { for { existing <- userService.getUserById(userId)(session) enabledUsers <- configService.getMyNDLAEnabledUsers diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/TestData.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/TestData.scala index 2b990004fc..f92e7b2d80 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/TestData.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/TestData.scala @@ -71,7 +71,7 @@ object TestData { resourceId = "1" ) - val emptyApiFolder: api.Folder = api.Folder( + val emptyApiFolder: api.FolderDTO = api.FolderDTO( id = "", name = "", status = "", diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ArenaControllerTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ArenaControllerTest.scala index 4c822516df..ee76dbcc2f 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ArenaControllerTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ArenaControllerTest.scala @@ -9,7 +9,7 @@ package no.ndla.myndlaapi.controller import no.ndla.common.errors.AccessDeniedException import no.ndla.common.model.domain.myndla.{ArenaGroup, MyNDLAUser, UserRole} -import no.ndla.myndlaapi.model.arena.api.PaginatedTopics +import no.ndla.myndlaapi.model.arena.api.PaginatedTopicsDTO import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.scalatestsuite.UnitTestSuite import no.ndla.tapirtesting.TapirControllerTest @@ -50,7 +50,7 @@ class ArenaControllerTest extends UnitTestSuite with TestEnvironment with TapirC when(userService.getArenaEnabledUser(eqTo(Some(feideToken)))).thenReturn(Success(testUser)) when(arenaReadService.getRecentTopics(any, any, any, any)(any)).thenReturn( Success( - PaginatedTopics( + PaginatedTopicsDTO( items = List.empty, page = 1, pageSize = 10, @@ -71,7 +71,7 @@ class ArenaControllerTest extends UnitTestSuite with TestEnvironment with TapirC when(userService.getArenaEnabledUser(eqTo(Some(feideToken)))).thenReturn(Failure(AccessDeniedException.forbidden)) when(arenaReadService.getRecentTopics(any, any, any, any)(any)).thenReturn( Success( - PaginatedTopics( + PaginatedTopicsDTO( items = List.empty, page = 1, pageSize = 10, @@ -92,7 +92,7 @@ class ArenaControllerTest extends UnitTestSuite with TestEnvironment with TapirC when(userService.getArenaEnabledUser(eqTo(None))).thenReturn(Failure(AccessDeniedException.unauthorized)) when(arenaReadService.getRecentTopics(any, any, any, any)(any)).thenReturn( Success( - PaginatedTopics( + PaginatedTopicsDTO( items = List.empty, page = 1, pageSize = 10, diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ConfigControllerTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ConfigControllerTest.scala index 7fa07dba0b..1c8a24e4f7 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ConfigControllerTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/ConfigControllerTest.scala @@ -8,7 +8,7 @@ package no.ndla.myndlaapi.controller import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.config.{ConfigMeta, ConfigMetaValue} +import no.ndla.common.model.api.config.{ConfigMetaDTO, ConfigMetaValueDTO} import no.ndla.common.model.domain.config.ConfigKey import no.ndla.myndlaapi.TestData.{adminAndWriteScopeClientToken, adminScopeClientToken} import no.ndla.myndlaapi.TestEnvironment @@ -25,10 +25,10 @@ class ConfigControllerTest extends UnitTestSuite with TestEnvironment with Tapir val controller: ConfigController = new ConfigController() test("That updating config returns 200 if all is good") { - when(configService.updateConfig(any[ConfigKey], any[ConfigMetaValue], any[TokenUser])) + when(configService.updateConfig(any[ConfigKey], any[ConfigMetaValueDTO], any[TokenUser])) .thenReturn( Success( - ConfigMeta( + ConfigMetaDTO( ConfigKey.LearningpathWriteRestricted.entryName, Left(true), NDLADate.now(), diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/FolderControllerTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/FolderControllerTest.scala index 0eec2853fb..a0cfcfaa39 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/FolderControllerTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/FolderControllerTest.scala @@ -8,7 +8,7 @@ package no.ndla.myndlaapi.controller import no.ndla.common.model.domain.myndla.{MyNDLAUser, UserRole} -import no.ndla.myndlaapi.model.api.Folder +import no.ndla.myndlaapi.model.api.FolderDTO import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.scalatestsuite.UnitTestSuite import no.ndla.tapirtesting.TapirControllerTest @@ -62,7 +62,7 @@ class FolderControllerTest extends UnitTestSuite with TestEnvironment with Tapir val someId = UUID.randomUUID() when(folderReadService.getSingleFolder(eqTo(someId), any, any, any)).thenReturn( Success( - Folder( + FolderDTO( id = someId.toString, name = "folderName", status = "private", diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/StatsControllerTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/StatsControllerTest.scala index 7b23e7f324..c897d0e621 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/StatsControllerTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/controller/StatsControllerTest.scala @@ -7,8 +7,8 @@ package no.ndla.myndlaapi.controller -import no.ndla.common.model.api.SingleResourceStats -import no.ndla.myndlaapi.model.api.Stats +import no.ndla.common.model.api.SingleResourceStatsDTO +import no.ndla.myndlaapi.model.api.StatsDTO import no.ndla.myndlaapi.TestEnvironment import no.ndla.scalatestsuite.UnitTestSuite import no.ndla.tapirtesting.TapirControllerTest @@ -22,7 +22,7 @@ class StatsControllerTest extends UnitTestSuite with TestEnvironment with TapirC val controller: StatsController = new StatsController() test("That getting stats returns in fact stats") { - when(folderReadService.getStats).thenReturn(Some(Stats(1, 2, 3, 4, 5, 6, List.empty, Map.empty))) + when(folderReadService.getStats).thenReturn(Some(StatsDTO(1, 2, 3, 4, 5, 6, List.empty, Map.empty))) val response = simpleHttpClient.send(quickRequest.get(uri"http://localhost:$serverPort/myndla-api/v1/stats")) response.code.code should be(200) @@ -30,7 +30,7 @@ class StatsControllerTest extends UnitTestSuite with TestEnvironment with TapirC test("That getting multiple resourceTypes for id works") { when(folderReadService.getFavouriteStatsForResource(any, any)) - .thenReturn(Success(List(SingleResourceStats("1", 21)))) + .thenReturn(Success(List(SingleResourceStatsDTO("1", 21)))) val response = simpleHttpClient.send( quickRequest.get(uri"http://localhost:$serverPort/myndla-api/v1/stats/favorites/article,multidisciplinary/123") ) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/ArenaTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/ArenaTest.scala index 231a88b849..2a86623d77 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/ArenaTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/ArenaTest.scala @@ -14,9 +14,9 @@ import no.ndla.common.CirceUtil import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.myndla.{ArenaGroup, MyNDLAUser, UserRole} import no.ndla.myndlaapi.model.arena.api -import no.ndla.myndlaapi.{model, *} -import no.ndla.myndlaapi.model.api.ArenaUser -import no.ndla.myndlaapi.model.arena.api.{NewCategory, PaginatedNewPostNotifications, PaginatedPosts} +import no.ndla.myndlaapi.* +import no.ndla.myndlaapi.model.api.ArenaUserDTO +import no.ndla.myndlaapi.model.arena.api.{NewCategoryDTO, PaginatedNewPostNotificationsDTO, PaginatedPostsDTO} import no.ndla.network.clients.FeideExtendedUserInfo import no.ndla.scalatestsuite.IntegrationSuite import org.mockito.ArgumentMatchers.{any, eq as eqTo} @@ -151,7 +151,7 @@ class ArenaTest parentCategoryId: Option[Long] = None ): Response[String] = { val newCategory = - api.NewCategory(title = title, description = description, visible = true, parentCategoryId = parentCategoryId) + api.NewCategoryDTO(title = title, description = description, visible = true, parentCategoryId = parentCategoryId) val inBody = newCategory.asJson.noSpaces val res = simpleHttpClient.send( quickRequest @@ -173,9 +173,9 @@ class ArenaTest token: String = "asd" ): Response[String] = { val newTopic = - api.NewTopic( + api.NewTopicDTO( title = title, - initialPost = api.NewPost(content = content, None), + initialPost = api.NewPostDTO(content = content, None), isLocked = Some(false), isPinned = Some(false) ) @@ -199,7 +199,7 @@ class ArenaTest token: String = "asd", toPostId: Option[Long] = None ): Response[String] = { - val newPost = api.NewPost(content = content, toPostId = toPostId) + val newPost = api.NewPostDTO(content = content, toPostId = toPostId) val inBody = newPost.asJson.noSpaces val res = simpleHttpClient.send( quickRequest @@ -226,10 +226,10 @@ class ArenaTest .readTimeout(10.seconds) ) - val categories = io.circe.parser.parse(fetchCategoriesResponse.body).flatMap(_.as[List[api.Category]]).toTry.get + val categories = io.circe.parser.parse(fetchCategoriesResponse.body).flatMap(_.as[List[api.CategoryDTO]]).toTry.get categories.size should be(1) categories.head should be( - api.Category( + api.CategoryDTO( 1, "title", "description", @@ -241,7 +241,7 @@ class ArenaTest parentCategoryId = None, categoryCount = 0, subcategories = List.empty, - breadcrumbs = List(api.CategoryBreadcrumb(1, "title")) + breadcrumbs = List(api.CategoryBreadcrumbDTO(1, "title")) ) ) } @@ -252,14 +252,14 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val top1 = createTopic("title1", "description1", categoryId) createTopic("title2", "description2", categoryId) createTopic("title3", "description3", categoryId) - val top1T = io.circe.parser.parse(top1.body).flatMap(_.as[api.Topic]).toTry + val top1T = io.circe.parser.parse(top1.body).flatMap(_.as[api.TopicDTO]).toTry val top1Id = top1T.get.id createPost("post1", top1Id) @@ -267,7 +267,7 @@ class ArenaTest createPost("post3", top1Id) createPost("post4", top1Id) - val expectedCategoryResult = api.CategoryWithTopics( + val expectedCategoryResult = api.CategoryWithTopicsDTO( id = 1, title = "title", description = "description", @@ -276,7 +276,7 @@ class ArenaTest topicPage = 1, topicPageSize = 10, topics = List( - api.Topic( + api.TopicDTO( id = 1, title = "title1", postCount = 5, @@ -288,7 +288,7 @@ class ArenaTest isPinned = false, voteCount = 0 ), - api.Topic( + api.TopicDTO( id = 2, title = "title2", postCount = 1, @@ -300,7 +300,7 @@ class ArenaTest isPinned = false, voteCount = 0 ), - api.Topic( + api.TopicDTO( id = 3, title = "title3", postCount = 1, @@ -319,7 +319,7 @@ class ArenaTest categoryCount = 0, subcategories = List.empty, parentCategoryId = None, - breadcrumbs = List(api.CategoryBreadcrumb(1, "title")) + breadcrumbs = List(api.CategoryBreadcrumbDTO(1, "title")) ) val categoryResp = simpleHttpClient.send( @@ -331,25 +331,25 @@ class ArenaTest categoryResp.code.code should be(200) - val resultTry = io.circe.parser.parse(categoryResp.body).flatMap(_.as[api.CategoryWithTopics]).toTry + val resultTry = io.circe.parser.parse(categoryResp.body).flatMap(_.as[api.CategoryWithTopicsDTO]).toTry resultTry should be(Success(expectedCategoryResult)) - val expectedTopic1Result = api.TopicWithPosts( + val expectedTopic1Result = api.TopicWithPostsDTO( id = 1, title = "title1", postCount = 5, - posts = api.PaginatedPosts( + posts = api.PaginatedPostsDTO( totalCount = 5, page = 1, pageSize = 10, items = List( - api.Post( + api.PostDTO( id = 1, content = "description1", created = someDate, updated = someDate, owner = Some( - ArenaUser( + ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -363,13 +363,13 @@ class ArenaTest upvotes = 0, upvoted = false ), - api.Post( + api.PostDTO( id = 4, content = "post1", created = someDate, updated = someDate, owner = Some( - model.api.ArenaUser( + model.api.ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -383,13 +383,13 @@ class ArenaTest upvotes = 0, upvoted = false ), - api.Post( + api.PostDTO( id = 5, content = "post2", created = someDate, updated = someDate, owner = Some( - model.api.ArenaUser( + model.api.ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -403,13 +403,13 @@ class ArenaTest upvotes = 0, upvoted = false ), - api.Post( + api.PostDTO( id = 6, content = "post3", created = someDate, updated = someDate, owner = Some( - model.api.ArenaUser( + model.api.ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -423,13 +423,13 @@ class ArenaTest upvotes = 0, upvoted = false ), - api.Post( + api.PostDTO( id = 7, content = "post4", created = someDate, updated = someDate, owner = Some( - model.api.ArenaUser( + model.api.ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -460,7 +460,7 @@ class ArenaTest .header("FeideAuthorization", s"Bearer asd") .readTimeout(10.seconds) ) - val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPosts]).toTry + val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry topic1ResultTry should be(Success(expectedTopic1Result)) topic1Resp.code.code should be(200) } @@ -471,12 +471,12 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val top1 = createTopic("title1", "description1", categoryId) - val top1T = io.circe.parser.parse(top1.body).flatMap(_.as[api.Topic]).toTry + val top1T = io.circe.parser.parse(top1.body).flatMap(_.as[api.TopicDTO]).toTry val top1Id = top1T.get.id createPost("post1", top1Id) @@ -501,14 +501,14 @@ class ArenaTest createPost("post20", top1Id) createPost("post21", top1Id) - def post(num: Long): api.Post = { - api.Post( + def post(num: Long): api.PostDTO = { + api.PostDTO( id = num + 1, content = s"post$num", created = someDate, updated = someDate, owner = Some( - model.api.ArenaUser( + model.api.ArenaUserDTO( id = 1, displayName = "", username = "email@ndla.no", @@ -525,11 +525,11 @@ class ArenaTest } { - val expectedTopic1Result = api.TopicWithPosts( + val expectedTopic1Result = api.TopicWithPostsDTO( id = 1, title = "title1", postCount = 22, - posts = api.PaginatedPosts( + posts = api.PaginatedPostsDTO( totalCount = 22, page = 2, pageSize = 10, @@ -561,17 +561,17 @@ class ArenaTest .header("FeideAuthorization", s"Bearer asd") .readTimeout(10.seconds) ) - val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPosts]).toTry + val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry topic1ResultTry should be(Success(expectedTopic1Result)) topic1Resp.code.code should be(200) } { - val expectedTopic1Result = api.TopicWithPosts( + val expectedTopic1Result = api.TopicWithPostsDTO( id = 1, title = "title1", postCount = 22, - posts = api.PaginatedPosts( + posts = api.PaginatedPostsDTO( totalCount = 22, page = 5, pageSize = 3, @@ -596,7 +596,7 @@ class ArenaTest .header("FeideAuthorization", s"Bearer asd") .readTimeout(10.seconds) ) - val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPosts]).toTry + val topic1ResultTry = io.circe.parser.parse(topic1Resp.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry topic1ResultTry should be(Success(expectedTopic1Result)) topic1Resp.code.code should be(200) } @@ -613,12 +613,12 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id // User 1 creates topic which should result in following own topic val createTopicRes = createTopic("title1", "description1", categoryId, token = user1Token) - val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.Topic]).toTry + val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.TopicDTO]).toTry val topicId = topicIdT.get.id // User 2 posts to user1s followed topic @@ -632,7 +632,7 @@ class ArenaTest .readTimeout(10.seconds) ) val notificationT = - io.circe.parser.parse(notificationsResp.body).flatMap(_.as[PaginatedNewPostNotifications]).toTry + io.circe.parser.parse(notificationsResp.body).flatMap(_.as[PaginatedNewPostNotificationsDTO]).toTry notificationT.get.items.size should be(1) val notif = notificationT.get.items.head notif.topicId should be(topicId) @@ -657,7 +657,7 @@ class ArenaTest .readTimeout(10.seconds) ) val notificationT = - io.circe.parser.parse(notificationsResp.body).flatMap(_.as[PaginatedNewPostNotifications]).toTry + io.circe.parser.parse(notificationsResp.body).flatMap(_.as[PaginatedNewPostNotificationsDTO]).toTry notificationT.get.items.size should be(1) val notif = notificationT.get.items.head notif.topicId should be(topicId) @@ -676,20 +676,20 @@ class ArenaTest when(myndlaApi.componentRegistry.userService.getInitialIsArenaGroups(any)).thenReturn(List(ArenaGroup.ADMIN)) when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val createTopicRes = createTopic("title1", "description1", categoryId, token = user1Token) - val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.Topic]).toTry + val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.TopicDTO]).toTry val topicId = topicIdT.get.id val post1 = createPost("noe innhold i topicen", topicId, token = user2Token) - val post1Try = io.circe.parser.parse(post1.body).flatMap(_.as[api.Post]).toTry + val post1Try = io.circe.parser.parse(post1.body).flatMap(_.as[api.PostDTO]).toTry val post2 = createPost("noe annet innhold", topicId, token = user1Token, toPostId = Some(post1Try.get.id)) - val post2Try = io.circe.parser.parse(post2.body).flatMap(_.as[api.Post]).toTry + val post2Try = io.circe.parser.parse(post2.body).flatMap(_.as[api.PostDTO]).toTry val post3 = createPost("Svar til noe annet innhold", topicId, token = user2Token, toPostId = Some(post2Try.get.id)) - val post3Try = io.circe.parser.parse(post3.body).flatMap(_.as[api.Post]).toTry + val post3Try = io.circe.parser.parse(post3.body).flatMap(_.as[api.PostDTO]).toTry val topic1 = simpleHttpClient.send( quickRequest @@ -697,13 +697,13 @@ class ArenaTest .header("FeideAuthorization", s"Bearer $user1Token") .readTimeout(10.seconds) ) - val topicTry = io.circe.parser.parse(topic1.body).flatMap(_.as[api.TopicWithPosts]).toTry.get + val topicTry = io.circe.parser.parse(topic1.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry.get topicTry.postCount should be(4) topicTry.posts.items.length should be(2) topicTry.posts.items.head.replies.length should be(0) topicTry.posts.items.last.replies.length should be(1) - topicTry.posts.items.last.replies.asInstanceOf[List[api.Post]].last.replies.last should be(post3Try.get) + topicTry.posts.items.last.replies.asInstanceOf[List[api.PostDTO]].last.replies.last should be(post3Try.get) } @@ -714,15 +714,15 @@ class ArenaTest when(myndlaApi.componentRegistry.userService.getInitialIsArenaGroups(any)).thenReturn(List(ArenaGroup.ADMIN)) when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val createTopicRes = createTopic("title1", "description1", categoryId, token = user1Token) - val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.Topic]).toTry + val topicIdT = io.circe.parser.parse(createTopicRes.body).flatMap(_.as[api.TopicDTO]).toTry val topicId = topicIdT.get.id val post1 = createPost("noe innhold i topicen", topicId, token = user1Token) - val post1Try = io.circe.parser.parse(post1.body).flatMap(_.as[api.Post]).toTry + val post1Try = io.circe.parser.parse(post1.body).flatMap(_.as[api.PostDTO]).toTry createPost("noe annet innhold", topicId, token = user1Token, toPostId = Some(post1Try.get.id)) val topic1 = simpleHttpClient.send( @@ -732,7 +732,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val topicTry = io.circe.parser.parse(topic1.body).flatMap(_.as[api.TopicWithPosts]).toTry.get + val topicTry = io.circe.parser.parse(topic1.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry.get topicTry.postCount should be(3) @@ -752,7 +752,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val topic2Try = io.circe.parser.parse(topic2.body).flatMap(_.as[api.TopicWithPosts]).toTry.get + val topic2Try = io.circe.parser.parse(topic2.body).flatMap(_.as[api.TopicWithPostsDTO]).toTry.get topic2Try.postCount should be(1) @@ -766,19 +766,19 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val topic = createTopic("Topic title", "Topic description", categoryId, token = userToken) - val topicT = io.circe.parser.parse(topic.body).flatMap(_.as[api.Topic]).toTry + val topicT = io.circe.parser.parse(topic.body).flatMap(_.as[api.TopicDTO]).toTry val topicId = topicT.get.id val ownPost = createPost("Innhold i posten", topicId, token = userToken) - val ownPostT = io.circe.parser.parse(ownPost.body).flatMap(_.as[api.Post]).toTry + val ownPostT = io.circe.parser.parse(ownPost.body).flatMap(_.as[api.PostDTO]).toTry val ownPostId = ownPostT.get.id val otherPost = createPost("Innhold i posten", topicId, toPostId = Some(ownPostId)) - val otherPostT = CirceUtil.tryParseAs[api.Post](otherPost.body).get + val otherPostT = CirceUtil.tryParseAs[api.PostDTO](otherPost.body).get val otherPostId = otherPostT.id val upvoteOwnPost = simpleHttpClient.send( @@ -788,7 +788,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val upvoteOwnPostT = CirceUtil.tryParseAs[api.Post](upvoteOwnPost.body).get + val upvoteOwnPostT = CirceUtil.tryParseAs[api.PostDTO](upvoteOwnPost.body).get upvoteOwnPost.code.code should be(200) upvoteOwnPostT.upvotes should be(0) @@ -801,7 +801,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val firstUpvoteT = CirceUtil.tryParseAs[api.Post](firstUpvote.body).get + val firstUpvoteT = CirceUtil.tryParseAs[api.PostDTO](firstUpvote.body).get firstUpvote.code.code should be(200) firstUpvoteT.upvotes should be(1) @@ -823,7 +823,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val unUpvoteT = CirceUtil.tryParseAs[api.Post](unUpvote.body).get + val unUpvoteT = CirceUtil.tryParseAs[api.PostDTO](unUpvote.body).get unUpvote.code.code should be(200) unUpvoteT.upvotes should be(0) @@ -846,15 +846,15 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val createCategoryRes = createCategory("title", "description") - val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.Category]).toTry + val categoryIdT = io.circe.parser.parse(createCategoryRes.body).flatMap(_.as[api.CategoryDTO]).toTry val categoryId = categoryIdT.get.id val topic = createTopic("Topic title", "Topic description", categoryId, token = userOneToken) - val topicT = io.circe.parser.parse(topic.body).flatMap(_.as[api.Topic]).toTry + val topicT = io.circe.parser.parse(topic.body).flatMap(_.as[api.TopicDTO]).toTry val topicId = topicT.get.id val ownPost = createPost("Innhold i posten", topicId, token = userOneToken) - val ownPostT = io.circe.parser.parse(ownPost.body).flatMap(_.as[api.Post]).toTry + val ownPostT = io.circe.parser.parse(ownPost.body).flatMap(_.as[api.PostDTO]).toTry val ownPostId = ownPostT.get.id val flagPost = simpleHttpClient.send( @@ -874,7 +874,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val flaggedPosts = CirceUtil.unsafeParseAs[PaginatedPosts](flaggedPostsResponse.body) + val flaggedPosts = CirceUtil.unsafeParseAs[PaginatedPostsDTO](flaggedPostsResponse.body) flaggedPosts.totalCount should be(1) val p = flaggedPosts.items.head p.id should be(ownPostId) @@ -895,7 +895,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val flaggedPosts2 = CirceUtil.unsafeParseAs[PaginatedPosts](flaggedPostsResponse2.body) + val flaggedPosts2 = CirceUtil.unsafeParseAs[PaginatedPostsDTO](flaggedPostsResponse2.body) flaggedPosts2.totalCount should be(1) flaggedPosts2.items.head.flags.get.head.resolved.isDefined should be(true) } @@ -906,15 +906,15 @@ class ArenaTest when(myndlaApi.componentRegistry.clock.now()).thenReturn(someDate) val category1 = createCategory("title1", "description1", parentCategoryId = None) - val category1T = io.circe.parser.parse(category1.body).flatMap(_.as[api.Category]).toTry + val category1T = io.circe.parser.parse(category1.body).flatMap(_.as[api.CategoryDTO]).toTry val category1Id = category1T.get.id val category2 = createCategory("title2", "description2", parentCategoryId = Some(category1Id)) - val category2T = io.circe.parser.parse(category2.body).flatMap(_.as[api.Category]).toTry + val category2T = io.circe.parser.parse(category2.body).flatMap(_.as[api.CategoryDTO]).toTry val category2Id = category2T.get.id val category3 = createCategory("title3", "description3", parentCategoryId = Some(category2Id)) - val category3T = io.circe.parser.parse(category3.body).flatMap(_.as[api.Category]).toTry + val category3T = io.circe.parser.parse(category3.body).flatMap(_.as[api.CategoryDTO]).toTry val category3Id = category3T.get.id val intoItself = simpleHttpClient.send( @@ -922,7 +922,7 @@ class ArenaTest .put(uri"$myndlaApiArenaUrl/categories/$category1Id") .body( CirceUtil.toJsonString( - NewCategory( + NewCategoryDTO( title = "title1", description = "description1", visible = true, @@ -938,7 +938,7 @@ class ArenaTest .put(uri"$myndlaApiArenaUrl/categories/$category1Id") .body( CirceUtil.toJsonString( - NewCategory( + NewCategoryDTO( title = "title1", description = "description1", visible = true, @@ -954,7 +954,7 @@ class ArenaTest .put(uri"$myndlaApiArenaUrl/categories/$category1Id") .body( CirceUtil.toJsonString( - NewCategory( + NewCategoryDTO( title = "title1", description = "description1", visible = true, @@ -970,7 +970,7 @@ class ArenaTest .put(uri"$myndlaApiArenaUrl/categories/$category3Id") .body( CirceUtil.toJsonString( - NewCategory( + NewCategoryDTO( title = "title3", description = "description3", visible = true, @@ -988,7 +988,7 @@ class ArenaTest .readTimeout(10.seconds) ) - val categories = io.circe.parser.parse(fetchCategoriesResponse.body).flatMap(_.as[List[api.Category]]).toTry.get + val categories = io.circe.parser.parse(fetchCategoriesResponse.body).flatMap(_.as[List[api.CategoryDTO]]).toTry.get categories.size should be(1) categories.head.id should be(category1Id) categories.head.subcategories.map(_.id) should be(List(category2Id, category3Id)) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/CloneFolderTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/CloneFolderTest.scala index 824bb9f667..115d20b651 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/CloneFolderTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/CloneFolderTest.scala @@ -15,7 +15,7 @@ import no.ndla.common.model.domain.ResourceType import no.ndla.common.model.domain.myndla.FolderStatus import no.ndla.myndlaapi.model.api import no.ndla.myndlaapi.model.domain -import no.ndla.myndlaapi.model.api.{Breadcrumb, Folder} +import no.ndla.myndlaapi.model.api.{BreadcrumbDTO, FolderDTO} import no.ndla.myndlaapi.model.domain.{NewFolderData, ResourceDocument} import no.ndla.myndlaapi.{ComponentRegistry, MainClass, MyNdlaApiProperties, UnitSuite} import no.ndla.network.clients.FeideExtendedUserInfo @@ -111,12 +111,12 @@ class CloneFolderTest } // id is autogenerated in database, so we need to replace it to something constant in order to compare objects - def replaceIdRecursively(folder: Folder, newId: String): Folder = { + def replaceIdRecursively(folder: FolderDTO, newId: String): FolderDTO = { val updatedId = newId val updatedParentId = folder.parentId.map(_ => newId) val updatedBreadcrumbs = folder.breadcrumbs.map(_.copy(id = newId)) val updatedResources = folder.resources.map(_.copy(id = newId)) - val updatedSubfolders = folder.subfolders.map { case child: Folder => replaceIdRecursively(child, newId) } + val updatedSubfolders = folder.subfolders.map { case child: FolderDTO => replaceIdRecursively(child, newId) } folder.copy( id = updatedId, @@ -171,12 +171,13 @@ class CloneFolderTest val customId = "someid" val parentId = Some(customId) - val parentChild1 = api.Folder( + val parentChild1 = api.FolderDTO( id = customId, name = "p_child1", status = "private", parentId = parentId, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent"), Breadcrumb(id = customId, name = "p_child1")), + breadcrumbs = + List(BreadcrumbDTO(id = customId, name = "parent"), BreadcrumbDTO(id = customId, name = "p_child1")), subfolders = List.empty, resources = List.empty, rank = 1, @@ -187,12 +188,13 @@ class CloneFolderTest owner = None ) - val parentChild2 = api.Folder( + val parentChild2 = api.FolderDTO( id = customId, name = "p_child2", status = "private", parentId = parentId, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent"), Breadcrumb(id = customId, name = "p_child2")), + breadcrumbs = + List(BreadcrumbDTO(id = customId, name = "parent"), BreadcrumbDTO(id = customId, name = "p_child2")), subfolders = List.empty, resources = List.empty, rank = 2, @@ -203,7 +205,7 @@ class CloneFolderTest owner = None ) - val parentChild3 = api.Resource( + val parentChild3 = api.ResourceDTO( id = customId, resourceType = ResourceType.Article, path = "/path", @@ -213,12 +215,12 @@ class CloneFolderTest rank = Some(1) ) - val expectedFolder = api.Folder( + val expectedFolder = api.FolderDTO( id = customId, name = "parent", status = "private", parentId = None, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent")), + breadcrumbs = List(BreadcrumbDTO(id = customId, name = "parent")), subfolders = List(parentChild1, parentChild2), resources = List(parentChild3), rank = 1, @@ -243,7 +245,7 @@ class CloneFolderTest destinationFoldersAfter.get.length should be(1) val bod = response.body - val deserialized = CirceUtil.unsafeParseAs[api.Folder](bod) + val deserialized = CirceUtil.unsafeParseAs[api.FolderDTO](bod) val result = replaceIdRecursively(deserialized, customId) result should be(expectedFolder) } @@ -281,12 +283,13 @@ class CloneFolderTest ) folderRepository.insertFolder(feideId, folderData = childrenFolderThatShouldNotBeCloned).get.id - val parentChild1 = api.Folder( + val parentChild1 = api.FolderDTO( id = customId, name = "p_child1", status = "private", parentId = parentId, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent"), Breadcrumb(id = customId, name = "p_child1")), + breadcrumbs = + List(BreadcrumbDTO(id = customId, name = "parent"), BreadcrumbDTO(id = customId, name = "p_child1")), subfolders = List.empty, resources = List.empty, rank = 1, @@ -297,12 +300,13 @@ class CloneFolderTest owner = None ) - val parentChild2 = api.Folder( + val parentChild2 = api.FolderDTO( id = customId, name = "p_child2", status = "private", parentId = parentId, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent"), Breadcrumb(id = customId, name = "p_child2")), + breadcrumbs = + List(BreadcrumbDTO(id = customId, name = "parent"), BreadcrumbDTO(id = customId, name = "p_child2")), subfolders = List.empty, resources = List.empty, rank = 2, @@ -313,7 +317,7 @@ class CloneFolderTest owner = None ) - val parentChild3 = api.Resource( + val parentChild3 = api.ResourceDTO( id = customId, resourceType = ResourceType.Article, path = "/path", @@ -323,12 +327,12 @@ class CloneFolderTest rank = Some(1) ) - val expectedFolder = api.Folder( + val expectedFolder = api.FolderDTO( id = customId, name = "parent", status = "private", parentId = None, - breadcrumbs = List(Breadcrumb(id = customId, name = "parent")), + breadcrumbs = List(BreadcrumbDTO(id = customId, name = "parent")), subfolders = List(parentChild1, parentChild2), resources = List(parentChild3), rank = 1, @@ -353,7 +357,7 @@ class CloneFolderTest val destinationFoldersAfter = folderRepository.foldersWithFeideAndParentID(None, destinationFeideId) destinationFoldersAfter.get.length should be(1) - val deserialized = CirceUtil.unsafeParseAs[api.Folder](response.body) + val deserialized = CirceUtil.unsafeParseAs[api.FolderDTO](response.body) val result = replaceIdRecursively(deserialized, customId) result should be(expectedFolder) } @@ -376,15 +380,15 @@ class CloneFolderTest ) val destinationFolderId = folderRepository.insertFolder(destinationFeideId, folderData = destinationFolder).get.id - val parentChild1 = api.Folder( + val parentChild1 = api.FolderDTO( id = customId, name = "p_child1", status = "private", parentId = parentId, breadcrumbs = List( - Breadcrumb(id = customId, name = destinationFolder.name), - Breadcrumb(id = customId, name = "parent"), - Breadcrumb(id = customId, name = "p_child1") + BreadcrumbDTO(id = customId, name = destinationFolder.name), + BreadcrumbDTO(id = customId, name = "parent"), + BreadcrumbDTO(id = customId, name = "p_child1") ), subfolders = List.empty, resources = List.empty, @@ -396,15 +400,15 @@ class CloneFolderTest owner = None ) - val parentChild2 = api.Folder( + val parentChild2 = api.FolderDTO( id = customId, name = "p_child2", status = "private", parentId = parentId, breadcrumbs = List( - Breadcrumb(id = customId, name = destinationFolder.name), - Breadcrumb(id = customId, name = "parent"), - Breadcrumb(id = customId, name = "p_child2") + BreadcrumbDTO(id = customId, name = destinationFolder.name), + BreadcrumbDTO(id = customId, name = "parent"), + BreadcrumbDTO(id = customId, name = "p_child2") ), subfolders = List.empty, resources = List.empty, @@ -416,7 +420,7 @@ class CloneFolderTest owner = None ) - val parentChild3 = api.Resource( + val parentChild3 = api.ResourceDTO( id = customId, resourceType = ResourceType.Article, path = "/path", @@ -426,14 +430,14 @@ class CloneFolderTest rank = Some(1) ) - val parent = api.Folder( + val parent = api.FolderDTO( id = customId, name = "parent", status = "private", parentId = parentId, breadcrumbs = List( - Breadcrumb(id = customId, name = destinationFolder.name), - Breadcrumb(id = customId, name = "parent") + BreadcrumbDTO(id = customId, name = destinationFolder.name), + BreadcrumbDTO(id = customId, name = "parent") ), subfolders = List(parentChild1, parentChild2), resources = List(parentChild3), @@ -455,7 +459,7 @@ class CloneFolderTest .header("FeideAuthorization", s"Bearer asd") ) - val deserialized = CirceUtil.unsafeParseAs[api.Folder](response.body) + val deserialized = CirceUtil.unsafeParseAs[api.FolderDTO](response.body) val result = replaceIdRecursively(deserialized, customId) result should be(parent) } @@ -540,7 +544,7 @@ class CloneFolderTest .body("""{"status":"shared"}""") ) - val result = CirceUtil.unsafeParseAs[api.Folder](response.body) + val result = CirceUtil.unsafeParseAs[api.FolderDTO](response.body) result.shared should be(Some(shareTime)) } @@ -657,7 +661,7 @@ class CloneFolderTest .body("""{"name":"newname1"}""") ) - val result = CirceUtil.unsafeParseAs[api.Folder](response.body) + val result = CirceUtil.unsafeParseAs[api.FolderDTO](response.body) result.updated should not be result.created result.updated should be(updated) } diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/FolderTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/FolderTest.scala index b8f604e401..8e9273ff65 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/FolderTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/e2e/FolderTest.scala @@ -11,7 +11,7 @@ package no.ndla.myndlaapi.e2e import no.ndla.common.CirceUtil import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.myndla.FolderStatus -import no.ndla.myndlaapi.model.api.Folder +import no.ndla.myndlaapi.model.api.FolderDTO import no.ndla.myndlaapi.model.api import no.ndla.myndlaapi.{ComponentRegistry, MainClass, MyNdlaApiProperties, UnitSuite} import no.ndla.network.clients.FeideExtendedUserInfo @@ -106,12 +106,12 @@ class FolderTest } // id is autogenerated in database, so we need to replace it to something constant in order to compare objects - def replaceIdRecursively(folder: Folder, newId: String): Folder = { + def replaceIdRecursively(folder: FolderDTO, newId: String): FolderDTO = { val updatedId = newId val updatedParentId = folder.parentId.map(_ => newId) val updatedBreadcrumbs = folder.breadcrumbs.map(_.copy(id = newId)) val updatedResources = folder.resources.map(_.copy(id = newId)) - val updatedSubfolders = folder.subfolders.map { case child: Folder => replaceIdRecursively(child, newId) } + val updatedSubfolders = folder.subfolders.map { case child: FolderDTO => replaceIdRecursively(child, newId) } folder.copy( id = updatedId, @@ -122,9 +122,9 @@ class FolderTest ) } - def createFolder(feideId: String, name: String): api.Folder = { + def createFolder(feideId: String, name: String): api.FolderDTO = { import io.circe.generic.auto.* - val newFolderData = api.NewFolder( + val newFolderData = api.NewFolderDTO( name = name, status = Some(FolderStatus.SHARED.toString), parentId = None, @@ -142,10 +142,10 @@ class FolderTest if (!newFolder.isSuccess) fail(s"Failed to create folder $name failed with code ${newFolder.code} and body:\n${newFolder.body}") - CirceUtil.unsafeParseAs[api.Folder](newFolder.body) + CirceUtil.unsafeParseAs[api.FolderDTO](newFolder.body) } - def getFolders(feideId: String): api.UserFolder = { + def getFolders(feideId: String): api.UserFolderDTO = { import io.circe.generic.auto.* val folders = simpleHttpClient.send( quickRequest @@ -155,7 +155,7 @@ class FolderTest if (!folders.isSuccess) fail(s"Fetching all folders for $feideId failed with code ${folders.code} and body:\n${folders.body}") - CirceUtil.unsafeParseAs[api.UserFolder](folders.body) + CirceUtil.unsafeParseAs[api.UserFolderDTO](folders.body) } def saveFolder(feideId: String, folderId: String): Unit = { @@ -173,7 +173,7 @@ class FolderTest def sortFolders(feideId: String, idsInOrder: List[String], sortShared: Boolean = false): Unit = { import io.circe.generic.auto.* - val sortData = api.FolderSortRequest( + val sortData = api.FolderSortRequestDTO( sortedIds = idsInOrder.map(UUID.fromString) ) val body = CirceUtil.toJsonString(sortData) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/ConfigServiceTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/ConfigServiceTest.scala index eb45ba73e3..35d44d51c2 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/ConfigServiceTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/ConfigServiceTest.scala @@ -9,7 +9,7 @@ package no.ndla.myndlaapi.service import no.ndla.common.errors.{AccessDeniedException, ValidationException} -import no.ndla.common.model.api.config.ConfigMetaValue +import no.ndla.common.model.api.config.ConfigMetaValueDTO import no.ndla.common.model.domain.config.{BooleanValue, ConfigKey, ConfigMeta} import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.network.tapir.auth.Permission.{LEARNINGPATH_API_ADMIN, LEARNINGPATH_API_PUBLISH} @@ -42,7 +42,7 @@ class ConfigServiceTest extends UnitTestSuite with TestEnvironment { .thenReturn(Success(testConfigMeta)) val Failure(ex) = service.updateConfig( ConfigKey.LearningpathWriteRestricted, - ConfigMetaValue(true), + ConfigMetaValueDTO(true), TokenUser("Kari", Set(LEARNINGPATH_API_PUBLISH), None) ) ex.isInstanceOf[AccessDeniedException] should be(true) @@ -53,7 +53,7 @@ class ConfigServiceTest extends UnitTestSuite with TestEnvironment { .thenReturn(Success(testConfigMeta)) val Success(_) = service.updateConfig( ConfigKey.LearningpathWriteRestricted, - ConfigMetaValue(true), + ConfigMetaValueDTO(true), TokenUser("Kari", Set(LEARNINGPATH_API_ADMIN), None) ) } @@ -63,7 +63,7 @@ class ConfigServiceTest extends UnitTestSuite with TestEnvironment { .thenReturn(Success(testConfigMeta)) val Failure(ex) = service.updateConfig( ConfigKey.LearningpathWriteRestricted, - ConfigMetaValue(List("123")), + ConfigMetaValueDTO(List("123")), TokenUser("Kari", Set(LEARNINGPATH_API_ADMIN), None) ) @@ -75,7 +75,7 @@ class ConfigServiceTest extends UnitTestSuite with TestEnvironment { .thenReturn(Success(testConfigMeta)) val res = service.updateConfig( ConfigKey.LearningpathWriteRestricted, - ConfigMetaValue(true), + ConfigMetaValueDTO(true), TokenUser("Kari", Set(LEARNINGPATH_API_ADMIN), None) ) res.isSuccess should be(true) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderConverterServiceTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderConverterServiceTest.scala index f69c570af5..e0935fd824 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderConverterServiceTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderConverterServiceTest.scala @@ -9,14 +9,13 @@ package no.ndla.myndlaapi.service import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.myndla.{MyNDLAGroup as ApiGroup, MyNDLAUser as ApiUser, UpdatedMyNDLAUser} +import no.ndla.common.model.api.myndla.{MyNDLAGroupDTO, MyNDLAUserDTO, UpdatedMyNDLAUserDTO} import no.ndla.common.model.domain.ResourceType import no.ndla.common.model.domain.myndla.{FolderStatus, MyNDLAGroup, MyNDLAUser, UserRole} -import no.ndla.myndlaapi.model.api -import no.ndla.myndlaapi.{TestData, TestEnvironment} -import no.ndla.myndlaapi.model.domain -import no.ndla.myndlaapi.model.api.{Folder, NewFolder, UpdatedFolder} +import no.ndla.myndlaapi.model.api.{FolderDTO, NewFolderDTO, UpdatedFolderDTO} +import no.ndla.myndlaapi.model.{api, domain} import no.ndla.myndlaapi.model.domain.{NewFolderData, Resource, ResourceDocument} +import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.scalatestsuite.UnitTestSuite import org.mockito.Mockito.when @@ -32,20 +31,20 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { when(clock.now()).thenReturn(shared) val folderUUID = UUID.randomUUID() - val newFolder1 = NewFolder( + val newFolder1 = NewFolderDTO( name = "kenkaku", parentId = Some(folderUUID.toString), status = Some("private"), description = None ) - val newFolder2 = NewFolder( + val newFolder2 = NewFolderDTO( name = "kenkaku", parentId = Some(folderUUID.toString), status = Some("shared"), description = Some("descc") ) val newFolder3 = - NewFolder( + NewFolderDTO( name = "kenkaku", parentId = Some(folderUUID.toString), status = Some("ikkeesksisterendestatus"), @@ -149,7 +148,7 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { description = Some("mainFolder"), user = None ) - val apiResource = api.Resource( + val apiResource = api.ResourceDTO( id = resourceUUID.toString, resourceType = ResourceType.Concept, tags = List("a", "b", "c"), @@ -158,16 +157,16 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { resourceId = "1", rank = None ) - val apiData1 = Folder( + val apiData1 = FolderDTO( id = subFolder1UUID.toString, name = "folderData1", status = "private", resources = List(apiResource), subfolders = List(), breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder"), - api.Breadcrumb(id = subFolder3UUID.toString, name = "folderData3"), - api.Breadcrumb(id = subFolder1UUID.toString, name = "folderData1") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder"), + api.BreadcrumbDTO(id = subFolder3UUID.toString, name = "folderData3"), + api.BreadcrumbDTO(id = subFolder1UUID.toString, name = "folderData1") ), parentId = Some(subFolder3UUID.toString), rank = 1, @@ -177,15 +176,15 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { description = Some("folderData1"), owner = None ) - val apiData2 = api.Folder( + val apiData2 = api.FolderDTO( id = subFolder2UUID.toString, name = "folderData2", status = "shared", resources = List.empty, subfolders = List.empty, breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder"), - api.Breadcrumb(id = subFolder2UUID.toString, name = "folderData2") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder"), + api.BreadcrumbDTO(id = subFolder2UUID.toString, name = "folderData2") ), parentId = Some(mainFolderUUID.toString), rank = 1, @@ -195,15 +194,15 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { description = Some("folderData2"), owner = None ) - val apiData3 = api.Folder( + val apiData3 = api.FolderDTO( id = subFolder3UUID.toString, name = "folderData3", status = "private", subfolders = List(apiData1), resources = List(), breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder"), - api.Breadcrumb(id = subFolder3UUID.toString, name = "folderData3") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder"), + api.BreadcrumbDTO(id = subFolder3UUID.toString, name = "folderData3") ), parentId = Some(mainFolderUUID.toString), rank = 1, @@ -213,14 +212,14 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { description = Some("folderData3"), owner = None ) - val expected = api.Folder( + val expected = api.FolderDTO( id = mainFolderUUID.toString, name = "mainFolder", status = "shared", subfolders = List(apiData2, apiData3), resources = List(apiResource), breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder") ), parentId = None, rank = 1, @@ -234,7 +233,7 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { val Success(result) = service.toApiFolder( mainFolder, - List(api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder")), + List(api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder")), None, true ) @@ -264,10 +263,10 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { user = None ) val updatedWithData = - UpdatedFolder(name = Some("newNamae"), status = Some("shared"), description = Some("halla")) - val updatedWithoutData = UpdatedFolder(name = None, status = None, description = None) + UpdatedFolderDTO(name = Some("newNamae"), status = Some("shared"), description = Some("halla")) + val updatedWithoutData = UpdatedFolderDTO(name = None, status = None, description = None) val updatedWithGarbageData = - UpdatedFolder( + UpdatedFolderDTO( name = Some("huehueuheasdasd+++"), status = Some("det å joike er noe kult"), description = Some("jog ska visa deg garbage jog") @@ -313,8 +312,8 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { ) val existingShared = existingBase.copy(status = FolderStatus.SHARED, shared = Some(sharedBefore)) val existingPrivate = existingBase.copy(status = FolderStatus.PRIVATE, shared = None) - val updatedShared = UpdatedFolder(name = None, status = Some("shared"), description = None) - val updatedPrivate = UpdatedFolder(name = None, status = Some("private"), description = None) + val updatedShared = UpdatedFolderDTO(name = None, status = Some("shared"), description = None) + val updatedPrivate = UpdatedFolderDTO(name = None, status = Some("private"), description = None) val expected1 = existingBase.copy(status = FolderStatus.SHARED, shared = Some(sharedBefore)) val expected2 = existingBase.copy(status = FolderStatus.PRIVATE, shared = None) val expected3 = existingBase.copy(status = FolderStatus.SHARED, shared = Some(sharedNow)) @@ -347,7 +346,7 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { connection = None ) val expected = - api.Resource( + api.ResourceDTO( id = folderUUID.toString, resourceType = ResourceType.Article, path = "/subject/1/topic/1/resource/4", @@ -364,14 +363,14 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { val created = NDLADate.now() when(clock.now()).thenReturn(created) val newResource1 = - api.NewResource( + api.NewResourceDTO( resourceType = ResourceType.Audio, path = "/subject/1/topic/1/resource/4", tags = Some(List("a", "b")), resourceId = "1" ) val newResource2 = - api.NewResource( + api.NewResourceDTO( resourceType = ResourceType.Audio, path = "/subject/1/topic/1/resource/4", tags = None, @@ -434,7 +433,7 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { arenaGroups = List.empty ) val expectedUserData = - ApiUser( + MyNDLAUserDTO( id = 42, feideId = "feide", username = "example@email.com", @@ -443,7 +442,7 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { favoriteSubjects = Seq("a", "b"), role = "student", organization = "oslo", - groups = Seq(ApiGroup(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), + groups = Seq(MyNDLAGroupDTO(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), arenaEnabled = false, shareName = false, arenaGroups = List.empty @@ -476,16 +475,16 @@ class FolderConverterServiceTest extends UnitTestSuite with TestEnvironment { arenaGroups = List.empty ) val updatedUserData1 = - UpdatedMyNDLAUser(favoriteSubjects = None, arenaEnabled = None, shareName = None, arenaGroups = None) + UpdatedMyNDLAUserDTO(favoriteSubjects = None, arenaEnabled = None, shareName = None, arenaGroups = None) val updatedUserData2 = - UpdatedMyNDLAUser( + UpdatedMyNDLAUserDTO( favoriteSubjects = Some(Seq.empty), arenaEnabled = None, shareName = None, arenaGroups = None ) val updatedUserData3 = - UpdatedMyNDLAUser( + UpdatedMyNDLAUserDTO( favoriteSubjects = Some(Seq("x", "y", "z")), arenaEnabled = None, shareName = None, diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderReadServiceTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderReadServiceTest.scala index 978a9d41e4..383a8babb9 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderReadServiceTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderReadServiceTest.scala @@ -15,7 +15,7 @@ import no.ndla.myndlaapi.TestData.{emptyApiFolder, emptyDomainFolder, emptyDomai import no.ndla.myndlaapi.model.api import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.myndlaapi.model.domain -import no.ndla.myndlaapi.model.api.{Folder, Owner, ResourceStats} +import no.ndla.myndlaapi.model.api.{FolderDTO, OwnerDTO, ResourceStatsDTO} import no.ndla.myndlaapi.model.domain.Resource import no.ndla.scalatestsuite.UnitTestSuite import org.mockito.ArgumentMatchers.{any, eq as eqTo} @@ -109,14 +109,14 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { connection = None ) - val expected = Folder( + val expected = FolderDTO( id = mainFolderUUID.toString, name = "mainFolder", status = "private", - breadcrumbs = List(api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder")), + breadcrumbs = List(api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder")), parentId = None, resources = List( - api.Resource( + api.ResourceDTO( id = resource1UUID.toString, resourceType = ResourceType.Article, tags = List.empty, @@ -127,15 +127,15 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { ) ), subfolders = List( - api.Folder( + api.FolderDTO( id = subFolder1UUID.toString, name = "subFolder1", status = "private", subfolders = List.empty, resources = List.empty, breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder"), - api.Breadcrumb(id = subFolder1UUID.toString, name = "subFolder1") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder"), + api.BreadcrumbDTO(id = subFolder1UUID.toString, name = "subFolder1") ), parentId = Some(mainFolderUUID.toString), rank = 1, @@ -145,15 +145,15 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { description = None, owner = None ), - api.Folder( + api.FolderDTO( id = subFolder2UUID.toString, name = "subFolder2", status = "private", resources = List.empty, subfolders = List.empty, breadcrumbs = List( - api.Breadcrumb(id = mainFolderUUID.toString, name = "mainFolder"), - api.Breadcrumb(id = subFolder2UUID.toString, name = "subFolder2") + api.BreadcrumbDTO(id = mainFolderUUID.toString, name = "mainFolder"), + api.BreadcrumbDTO(id = subFolder2UUID.toString, name = "subFolder2") ), parentId = Some(mainFolderUUID.toString), rank = 1, @@ -225,7 +225,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = favoriteUUID.toString, name = "favorite", status = "private", - breadcrumbs = List(api.Breadcrumb(id = favoriteUUID.toString, name = "favorite")) + breadcrumbs = List(api.BreadcrumbDTO(id = favoriteUUID.toString, name = "favorite")) ) when(feideApiClient.getFeideID(Some("token"))).thenReturn(Success(feideId)) @@ -252,7 +252,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = favoriteUUID.toString, name = "favorite", status = "private", - breadcrumbs = List(api.Breadcrumb(id = favoriteUUID.toString, name = "favorite")) + breadcrumbs = List(api.BreadcrumbDTO(id = favoriteUUID.toString, name = "favorite")) ) val user = emptyMyNDLAUser.copy(id = 1996, shareName = true, displayName = "hallois") @@ -264,8 +264,8 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = folderId.toString, name = "SharedFolder", status = "shared", - breadcrumbs = List(api.Breadcrumb(id = folderId.toString, name = "SharedFolder")), - owner = Some(Owner(name = user.displayName)) + breadcrumbs = List(api.BreadcrumbDTO(id = folderId.toString, name = "SharedFolder")), + owner = Some(OwnerDTO(name = user.displayName)) ) when(feideApiClient.getFeideID(Some("token"))).thenReturn(Success(feideId)) @@ -330,7 +330,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = folderUUID.toString, name = "", status = "shared", - breadcrumbs = List(api.Breadcrumb(id = folderUUID.toString, name = "")) + breadcrumbs = List(api.BreadcrumbDTO(id = folderUUID.toString, name = "")) ) when( @@ -376,8 +376,8 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = folderUUID.toString, name = "", status = "shared", - breadcrumbs = List(api.Breadcrumb(id = folderUUID.toString, name = "")), - owner = Some(Owner("Feide")) + breadcrumbs = List(api.BreadcrumbDTO(id = folderUUID.toString, name = "")), + owner = Some(OwnerDTO("Feide")) ) when( @@ -417,14 +417,14 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { .thenReturn(List((1, "article"), (2, "learningpath"), (3, "video"))) service.getStats.get should be( - api.Stats( + api.StatsDTO( 5, 10, 20, 10, 15, 5, - List(ResourceStats("article", 1), ResourceStats("learningpath", 2), ResourceStats("video", 3)), + List(ResourceStatsDTO("article", 1), ResourceStatsDTO("learningpath", 2), ResourceStatsDTO("video", 3)), Map("article" -> 1, "learningpath" -> 2, "video" -> 3) ) ) @@ -439,7 +439,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = folderUUID.toString, name = "", status = "private", - breadcrumbs = List(api.Breadcrumb(id = folderUUID.toString, name = "")) + breadcrumbs = List(api.BreadcrumbDTO(id = folderUUID.toString, name = "")) ) when(feideApiClient.getFeideID(Some(feideId))).thenReturn(Success(feideId)) @@ -478,7 +478,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { resources = List(resource) ) - val apiResource = api.Resource( + val apiResource = api.ResourceDTO( id = resourceUUID.toString, resourceType = ResourceType.Article, path = "/path", @@ -491,7 +491,7 @@ class FolderReadServiceTest extends UnitTestSuite with TestEnvironment { id = folderUUID.toString, name = "", status = "shared", - breadcrumbs = List(api.Breadcrumb(id = folderUUID.toString, name = "")), + breadcrumbs = List(api.BreadcrumbDTO(id = folderUUID.toString, name = "")), resources = List(apiResource) ) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderWriteServiceTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderWriteServiceTest.scala index 81dd53cedb..0938ffd6ab 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderWriteServiceTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/FolderWriteServiceTest.scala @@ -17,7 +17,7 @@ import no.ndla.myndlaapi.model.api import no.ndla.myndlaapi.model.domain.FolderSortObject.FolderSorting import no.ndla.myndlaapi.{TestData, TestEnvironment} import no.ndla.myndlaapi.model.domain -import no.ndla.myndlaapi.model.api.{Folder, FolderSortRequest, NewFolder, NewResource} +import no.ndla.myndlaapi.model.api.{FolderDTO, FolderSortRequestDTO, NewFolderDTO, NewResourceDTO} import no.ndla.myndlaapi.model.domain.{FolderAndDirectChildren, FolderResource, Resource, SavedSharedFolder} import no.ndla.scalatestsuite.UnitTestSuite import org.mockito.ArgumentMatchers.{any, eq as eqTo} @@ -292,7 +292,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val resourceId = UUID.randomUUID() val resourcePath = "/subject/1/topic/2/resource/3" val newResource = - NewResource(resourceType = ResourceType.Article, path = resourcePath, tags = None, resourceId = "1") + NewResourceDTO(resourceType = ResourceType.Article, path = resourcePath, tags = None, resourceId = "1") val resource = Resource( id = resourceId, @@ -344,7 +344,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { any )(any) verify(folderRepository, times(1)).createFolderResourceConnection(eqTo(folderId), eqTo(resourceId), any, any)(any) - verify(folderConverterService, times(0)).mergeResource(any, any[NewResource]) + verify(folderConverterService, times(0)).mergeResource(any, any[NewResourceDTO]) verify(folderRepository, times(0)).updateResource(any)(any) } @@ -359,7 +359,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val resourceId = UUID.randomUUID() val resourcePath = "/subject/1/topic/2/resource/3" val newResource = - NewResource(resourceType = ResourceType.Article, path = resourcePath, tags = None, resourceId = "1") + NewResourceDTO(resourceType = ResourceType.Article, path = resourcePath, tags = None, resourceId = "1") val resource = Resource( id = resourceId, @@ -499,7 +499,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { test("that folder is not created if depth limit is reached") { val feideId = "FEIDE" val parentId = UUID.randomUUID() - val newFolder = NewFolder(name = "asd", parentId = Some(parentId.toString), status = None, description = None) + val newFolder = NewFolderDTO(name = "asd", parentId = Some(parentId.toString), status = None, description = None) when(feideApiClient.getFeideID(any)).thenReturn(Success(feideId)) when(userService.getOrCreateMyNDLAUserIfNotExist(any, any, any)(any)).thenReturn(Success(emptyMyNDLAUser)) @@ -526,7 +526,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val feideId = "FEIDE" val folderId = UUID.randomUUID() val parentId = UUID.randomUUID() - val newFolder = NewFolder(name = "asd", parentId = Some(parentId.toString), status = None, description = None) + val newFolder = NewFolderDTO(name = "asd", parentId = Some(parentId.toString), status = None, description = None) val domainFolder = domain.Folder( id = folderId, feideId = feideId, @@ -542,7 +542,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { description = None, user = None ) - val apiFolder = Folder( + val apiFolder = FolderDTO( id = folderId.toString, name = "asd", status = "private", @@ -585,7 +585,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val feideId = "FEIDE" val folderId = UUID.randomUUID() val parentId = UUID.randomUUID() - val newFolder = NewFolder(name = "asd", parentId = Some(parentId.toString), status = None, description = None) + val newFolder = NewFolderDTO(name = "asd", parentId = Some(parentId.toString), status = None, description = None) val domainFolder = domain.Folder( id = folderId, feideId = feideId, @@ -646,7 +646,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val feideId = "FEIDE" val folderId = UUID.randomUUID() val parentId = UUID.randomUUID() - val updateFolder = api.UpdatedFolder(name = Some("asd"), status = None, description = None) + val updateFolder = api.UpdatedFolderDTO(name = Some("asd"), status = None, description = None) val existingFolder = domain.Folder( id = folderId, @@ -709,7 +709,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val feideId = "FEIDE" val folderId = UUID.randomUUID() val parentId = UUID.randomUUID() - val updateFolder = api.UpdatedFolder(name = None, status = Some("shared"), description = None) + val updateFolder = api.UpdatedFolderDTO(name = None, status = Some("shared"), description = None) val existingFolder = domain.Folder( id = folderId, @@ -742,7 +742,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { description = None, user = None ) - val expectedFolder = api.Folder( + val expectedFolder = api.FolderDTO( id = folderId.toString, name = "noe unikt", status = "shared", @@ -817,7 +817,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { feideId = feideId ) - val sortRequest = FolderSortRequest( + val sortRequest = FolderSortRequestDTO( sortedIds = List( child1.id, child3.id, @@ -851,7 +851,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { test("that changeStatusToSharedIfParentIsShared actually changes the status if parent is shared") { val newFolder = - NewFolder( + NewFolderDTO( name = "folder", parentId = Some("string"), status = Some(FolderStatus.PRIVATE.toString), @@ -873,7 +873,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { user = None ) val expectedFolder = - NewFolder( + NewFolderDTO( name = "folder", parentId = Some("string"), status = Some(FolderStatus.SHARED.toString), @@ -887,7 +887,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { test("that changeStatusToSharedIfParentIsShared does not alter the status if during cloning or parent is None") { val newFolder = - NewFolder( + NewFolderDTO( name = "folder", parentId = Some("string"), status = Some(FolderStatus.PRIVATE.toString), @@ -909,7 +909,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { user = None ) val expectedFolder = - NewFolder( + NewFolderDTO( name = "folder", parentId = Some("string"), status = Some(FolderStatus.PRIVATE.toString), @@ -966,7 +966,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { val myNDLAUser = emptyMyNDLAUser.copy(userRole = UserRole.STUDENT) when(userService.getOrCreateMyNDLAUserIfNotExist(any, any, any)(any)).thenReturn(Success(myNDLAUser)) - val updatedFolder = api.UpdatedFolder(name = None, status = Some("shared"), description = None) + val updatedFolder = api.UpdatedFolderDTO(name = None, status = Some("shared"), description = None) val Failure(result) = service.isOperationAllowedOrAccessDenied("feideid", Some("accesstoken"), updatedFolder) result.getMessage should be("You do not have necessary permissions to share folders.") } @@ -978,7 +978,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { when(userService.getOrCreateMyNDLAUserIfNotExist(any, any, any)(any)).thenReturn(Success(myNDLAUser)) when(configService.isMyNDLAWriteRestricted).thenReturn(Success(true)) - val updatedFolder = api.UpdatedFolder(name = Some("asd"), status = None, description = None) + val updatedFolder = api.UpdatedFolderDTO(name = Some("asd"), status = None, description = None) val Failure(result) = service.isOperationAllowedOrAccessDenied("feideid", Some("accesstoken"), updatedFolder) result.getMessage should be("You do not have write access while write restriction is active.") } @@ -988,7 +988,7 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { when(userService.getOrCreateMyNDLAUserIfNotExist(any, any, any)(any)).thenReturn(Success(myNDLAUser)) when(configService.isMyNDLAWriteRestricted).thenReturn(Success(false)) - val updatedFolder = api.UpdatedFolder(name = Some("asd"), status = None, description = None) + val updatedFolder = api.UpdatedFolderDTO(name = Some("asd"), status = None, description = None) val result = service.isOperationAllowedOrAccessDenied("feideid", Some("accesstoken"), updatedFolder) result.isSuccess should be(true) } @@ -1000,8 +1000,8 @@ class FolderWriteServiceTest extends UnitTestSuite with TestEnvironment { when(userService.getOrCreateMyNDLAUserIfNotExist(any, any, any)(any)).thenReturn(Success(myNDLAUser)) when(configService.isMyNDLAWriteRestricted).thenReturn(Success(true)) - val folderWithUpdatedName = api.UpdatedFolder(name = Some("asd"), status = None, description = None) - val folderWithUpdatedStatus = api.UpdatedFolder(name = None, status = Some("shared"), description = None) + val folderWithUpdatedName = api.UpdatedFolderDTO(name = Some("asd"), status = None, description = None) + val folderWithUpdatedStatus = api.UpdatedFolderDTO(name = None, status = Some("shared"), description = None) val result1 = service.isOperationAllowedOrAccessDenied("feideid", Some("accesstoken"), folderWithUpdatedName) val result2 = service.isOperationAllowedOrAccessDenied("feideid", Some("accesstoken"), folderWithUpdatedStatus) result1.isSuccess should be(true) diff --git a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/UserServiceTest.scala b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/UserServiceTest.scala index 0380ad43e0..9c451068a4 100644 --- a/myndla-api/src/test/scala/no/ndla/myndlaapi/service/UserServiceTest.scala +++ b/myndla-api/src/test/scala/no/ndla/myndlaapi/service/UserServiceTest.scala @@ -10,7 +10,7 @@ package no.ndla.myndlaapi.service import no.ndla.common.errors.NotFoundException import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.myndla.{MyNDLAGroup as ApiGroup, MyNDLAUser as ApiUser, UpdatedMyNDLAUser} +import no.ndla.common.model.api.myndla.{MyNDLAGroupDTO, MyNDLAUserDTO, UpdatedMyNDLAUserDTO} import no.ndla.common.model.domain.myndla.{MyNDLAGroup, MyNDLAUser, MyNDLAUserDocument, UserRole} import no.ndla.myndlaapi.TestData.emptyMyNDLAUser import no.ndla.myndlaapi.TestEnvironment @@ -58,7 +58,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { arenaGroups = List.empty ) val updatedUserData = - UpdatedMyNDLAUser( + UpdatedMyNDLAUserDTO( favoriteSubjects = Some(Seq("r", "e")), arenaEnabled = None, shareName = Some(true), @@ -86,7 +86,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { shareName = true, arenaGroups = List.empty ) - val expected = ApiUser( + val expected = MyNDLAUserDTO( id = 42, feideId = "feide", username = "example@email.com", @@ -95,7 +95,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { favoriteSubjects = Seq("r", "e"), role = "student", organization = "oslo", - groups = Seq(ApiGroup(id = "id", displayName = "oslo", isPrimarySchool = false, parentId = None)), + groups = Seq(MyNDLAGroupDTO(id = "id", displayName = "oslo", isPrimarySchool = false, parentId = None)), arenaEnabled = false, shareName = true, arenaGroups = List.empty @@ -120,7 +120,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { test("That updateUserData fails if user does not exist") { val feideId = "feide" val updatedUserData = - UpdatedMyNDLAUser( + UpdatedMyNDLAUserDTO( favoriteSubjects = Some(Seq("r", "e")), arenaEnabled = None, shareName = None, @@ -183,7 +183,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { shareName = false, arenaGroups = List.empty ) - val apiUserData = ApiUser( + val apiUserData = MyNDLAUserDTO( id = 42, feideId = "feide", username = "example@email.com", @@ -192,7 +192,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { favoriteSubjects = Seq("r", "e"), role = "student", organization = "oslo", - groups = Seq(ApiGroup(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), + groups = Seq(MyNDLAGroupDTO(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), arenaEnabled = false, shareName = false, arenaGroups = List.empty @@ -257,7 +257,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { shareName = false, arenaGroups = List.empty ) - val apiUserData = ApiUser( + val apiUserData = MyNDLAUserDTO( id = 42, feideId = "feide", username = "example@email.com", @@ -266,7 +266,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { favoriteSubjects = Seq("r", "e"), role = "student", organization = "oslo", - groups = Seq(ApiGroup(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), + groups = Seq(MyNDLAGroupDTO(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), arenaEnabled = false, shareName = false, arenaGroups = List.empty @@ -334,7 +334,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { eduPersonPrincipalName = "example@email.com", mail = Some(Seq("example@email.com")) ) - val apiUserData = ApiUser( + val apiUserData = MyNDLAUserDTO( id = 42, feideId = "feide", username = "example@email.com", @@ -343,7 +343,7 @@ class UserServiceTest extends UnitTestSuite with TestEnvironment { favoriteSubjects = Seq("r", "e"), role = "student", organization = "oslo", - groups = Seq(ApiGroup(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), + groups = Seq(MyNDLAGroupDTO(id = "id", displayName = "oslo", isPrimarySchool = true, parentId = None)), arenaEnabled = false, shareName = false, arenaGroups = List.empty diff --git a/network/src/main/scala/no/ndla/network/clients/MyNDLAApiClient.scala b/network/src/main/scala/no/ndla/network/clients/MyNDLAApiClient.scala index c7a2cf5b55..8474681d14 100644 --- a/network/src/main/scala/no/ndla/network/clients/MyNDLAApiClient.scala +++ b/network/src/main/scala/no/ndla/network/clients/MyNDLAApiClient.scala @@ -8,8 +8,8 @@ package no.ndla.network.clients import no.ndla.common.configuration.HasBaseProps -import no.ndla.common.model.api.{MyNDLABundle, SingleResourceStats} -import no.ndla.common.model.api.config.ConfigMetaRestricted +import no.ndla.common.model.api.{MyNDLABundleDTO, SingleResourceStatsDTO} +import no.ndla.common.model.api.config.ConfigMetaRestrictedDTO import no.ndla.common.model.domain.ResourceType import no.ndla.common.model.domain.config.ConfigKey import no.ndla.common.model.api.myndla as api @@ -28,9 +28,9 @@ trait MyNDLAApiClient { private val statsEndpoint = s"http://${props.MyNDLAApiHost}/myndla-api/v1/stats" private val userEndpoint = uri"http://${props.MyNDLAApiHost}/myndla-api/v1/users" - def getUserWithFeideToken(feideToken: String): Try[api.MyNDLAUser] = { + def getUserWithFeideToken(feideToken: String): Try[api.MyNDLAUserDTO] = { val req = quickRequest.get(userEndpoint) - ndlaClient.fetchWithForwardedFeideAuth[api.MyNDLAUser](req, Some(feideToken)) + ndlaClient.fetchWithForwardedFeideAuth[api.MyNDLAUserDTO](req, Some(feideToken)) } def isWriteRestricted: Try[Boolean] = { @@ -44,21 +44,21 @@ trait MyNDLAApiClient { }) } - def getStatsFor(id: String, resourceTypes: List[ResourceType]): Try[List[SingleResourceStats]] = { + def getStatsFor(id: String, resourceTypes: List[ResourceType]): Try[List[SingleResourceStatsDTO]] = { val url = uri"$statsEndpoint/favorites/${resourceTypes.map(_.toString).mkString(",")}/$id" val req = quickRequest.get(url) - ndlaClient.fetch[List[SingleResourceStats]](req) + ndlaClient.fetch[List[SingleResourceStatsDTO]](req) } - def getMyNDLABundle: Try[MyNDLABundle] = { + def getMyNDLABundle: Try[MyNDLABundleDTO] = { val url = uri"$statsEndpoint/favorites" val req = quickRequest.get(url) val res = ndlaClient.fetch[Map[String, Map[String, Long]]](req) - res.map(favMap => MyNDLABundle(favMap)) + res.map(favMap => MyNDLABundleDTO(favMap)) } - private def doRequest(httpRequest: NdlaRequest): Try[ConfigMetaRestricted] = { - ndlaClient.fetchWithForwardedAuth[ConfigMetaRestricted](httpRequest, None) + private def doRequest(httpRequest: NdlaRequest): Try[ConfigMetaRestrictedDTO] = { + ndlaClient.fetchWithForwardedAuth[ConfigMetaRestrictedDTO](httpRequest, None) } } } diff --git a/network/src/main/scala/no/ndla/network/model/CombinedUser.scala b/network/src/main/scala/no/ndla/network/model/CombinedUser.scala index c4ec6b43b5..a174e30742 100644 --- a/network/src/main/scala/no/ndla/network/model/CombinedUser.scala +++ b/network/src/main/scala/no/ndla/network/model/CombinedUser.scala @@ -8,32 +8,32 @@ package no.ndla.network.model -import no.ndla.common.model.api.myndla.MyNDLAUser +import no.ndla.common.model.api.myndla.MyNDLAUserDTO import no.ndla.network.tapir.auth.TokenUser sealed trait CombinedUser { val tokenUser: Option[TokenUser] - val myndlaUser: Option[MyNDLAUser] + val myndlaUser: Option[MyNDLAUserDTO] } -case class OptionalCombinedUser(tokenUser: Option[TokenUser], myndlaUser: Option[MyNDLAUser]) extends CombinedUser +case class OptionalCombinedUser(tokenUser: Option[TokenUser], myndlaUser: Option[MyNDLAUserDTO]) extends CombinedUser trait CombinedUserRequired extends CombinedUser { def id: String } -case class CombinedUserWithTokenUser(user: TokenUser, myndlaUser: Option[MyNDLAUser]) extends CombinedUserRequired { +case class CombinedUserWithTokenUser(user: TokenUser, myndlaUser: Option[MyNDLAUserDTO]) extends CombinedUserRequired { override def id: FeideID = user.id val tokenUser: Option[TokenUser] = Some(user) } -case class CombinedUserWithMyNDLAUser(tokenUser: Option[TokenUser], user: MyNDLAUser) extends CombinedUserRequired { - override def id: String = user.feideId - val myndlaUser: Option[MyNDLAUser] = Some(user) +case class CombinedUserWithMyNDLAUser(tokenUser: Option[TokenUser], user: MyNDLAUserDTO) extends CombinedUserRequired { + override def id: String = user.feideId + val myndlaUser: Option[MyNDLAUserDTO] = Some(user) } -case class CombinedUserWithBoth(user: TokenUser, ndlaUser: MyNDLAUser) extends CombinedUserRequired { - override def id: String = user.id - val tokenUser: Option[TokenUser] = Some(user) - val myndlaUser: Option[MyNDLAUser] = Some(ndlaUser) +case class CombinedUserWithBoth(user: TokenUser, ndlaUser: MyNDLAUserDTO) extends CombinedUserRequired { + override def id: String = user.id + val tokenUser: Option[TokenUser] = Some(user) + val myndlaUser: Option[MyNDLAUserDTO] = Some(ndlaUser) } diff --git a/network/src/main/scala/no/ndla/network/tapir/TapirController.scala b/network/src/main/scala/no/ndla/network/tapir/TapirController.scala index b0f829fa43..71f20310e8 100644 --- a/network/src/main/scala/no/ndla/network/tapir/TapirController.scala +++ b/network/src/main/scala/no/ndla/network/tapir/TapirController.scala @@ -11,7 +11,7 @@ import com.typesafe.scalalogging.StrictLogging import io.circe.{Decoder, Encoder} import no.ndla.common.Clock import no.ndla.common.configuration.HasBaseProps -import no.ndla.common.model.api.myndla.MyNDLAUser +import no.ndla.common.model.api.myndla.MyNDLAUserDTO import no.ndla.common.model.domain.myndla.auth.AuthUtility import no.ndla.network.clients.MyNDLAApiClient import no.ndla.network.model.{ @@ -80,9 +80,9 @@ trait TapirController extends TapirErrorHandling { } def withOptionalMyNDLAUser[F[_]] - : PartialServerEndpoint[Option[String], Option[MyNDLAUser], I, AllErrors, O, R, F] = { + : PartialServerEndpoint[Option[String], Option[MyNDLAUserDTO], I, AllErrors, O, R, F] = { val newEndpoint = self.securityIn(AuthUtility.feideOauth()) - val authFunc: Option[String] => Either[AllErrors, Option[MyNDLAUser]] = (maybeToken: Option[String]) => { + val authFunc: Option[String] => Either[AllErrors, Option[MyNDLAUserDTO]] = (maybeToken: Option[String]) => { maybeToken match { case None => Right(None) case Some(token) => diff --git a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/controller/OEmbedProxyController.scala b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/controller/OEmbedProxyController.scala index b8ff986731..f23d1fd5eb 100644 --- a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/controller/OEmbedProxyController.scala +++ b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/controller/OEmbedProxyController.scala @@ -36,7 +36,7 @@ trait OEmbedProxyController { .in(query[Option[String]]("maxwidth").description("The maximum width of the embedded resource")) .in(query[Option[String]]("maxheight").description("The maximum height of the embedded resource")) .errorOut(errorOutputsFor(400, 401, 403, 404, 410, 422, 502)) - .out(jsonBody[OEmbed]) + .out(jsonBody[OEmbedDTO]) .serverLogicPure { case (url, maxWidth, maxHeight) => oEmbedService.get(url, maxWidth, maxHeight) match { case Success(oembed) => oembed.asRight diff --git a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbed.scala b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedDTO.scala similarity index 93% rename from oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbed.scala rename to oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedDTO.scala index ca3a7084d7..410dc1809e 100644 --- a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbed.scala +++ b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedDTO.scala @@ -14,7 +14,7 @@ import sttp.tapir.Schema.annotations.description // format: off @description("oEmbed information for an url.") -case class OEmbed( +case class OEmbedDTO( @description("The resource type") `type`: String, @description("The oEmbed version number. This must be 1.0.") version: String, @description("A text title, describing the resource.") title: Option[String], @@ -34,7 +34,7 @@ case class OEmbed( ) // format: on -object OEmbed { - implicit val encoder: Encoder[OEmbed] = deriveEncoder - implicit val decoder: Decoder[OEmbed] = deriveDecoder +object OEmbedDTO { + implicit val encoder: Encoder[OEmbedDTO] = deriveEncoder + implicit val decoder: Decoder[OEmbedDTO] = deriveDecoder } diff --git a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedProvider.scala b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedProvider.scala index 977084ca5a..13959cddfe 100644 --- a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedProvider.scala +++ b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/model/OEmbedProvider.scala @@ -17,7 +17,7 @@ case class OEmbedProvider( providerUrl: String, endpoints: List[OEmbedEndpoint], urlParser: String => String = identity, - postProcessor: (String, OEmbed) => OEmbed = (_: String, o: OEmbed) => o + postProcessor: (String, OEmbedDTO) => OEmbedDTO = (_: String, o: OEmbedDTO) => o ) { def supports(url: String): Boolean = { diff --git a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedConverterService.scala b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedConverterService.scala index 5211fbcfb7..dc2c4e49ac 100644 --- a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedConverterService.scala +++ b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedConverterService.scala @@ -8,13 +8,13 @@ package no.ndla.oembedproxy.service import io.lemonlabs.uri.Url -import no.ndla.oembedproxy.model.OEmbed +import no.ndla.oembedproxy.model.OEmbedDTO import io.lemonlabs.uri.typesafe.dsl._ import org.jsoup.Jsoup object OEmbedConverterService { - def addYoutubeTimestampIfdefinedInRequest(requestUrl: String, oembed: OEmbed): OEmbed = { + def addYoutubeTimestampIfdefinedInRequest(requestUrl: String, oembed: OEmbedDTO): OEmbedDTO = { val paramTypesToTransfer = List("start", "time_continue", "t", "end", "rel") val queryParamsToTransfer = requestUrl.query.filterNames(pn => paramTypesToTransfer.contains(pn)).params diff --git a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedServiceComponent.scala b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedServiceComponent.scala index 744fc36633..c3e5a31447 100644 --- a/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedServiceComponent.scala +++ b/oembed-proxy/src/main/scala/no/ndla/oembedproxy/service/OEmbedServiceComponent.scala @@ -11,7 +11,7 @@ package no.ndla.oembedproxy.service import com.typesafe.scalalogging.StrictLogging import no.ndla.network.NdlaClient import no.ndla.network.model.HttpRequestException -import no.ndla.oembedproxy.model.{InvalidUrlException, OEmbed, OEmbedProvider, ProviderNotSupportedException} +import no.ndla.oembedproxy.model.{InvalidUrlException, OEmbedDTO, OEmbedProvider, ProviderNotSupportedException} import org.log4s.MDC import sttp.client3.quick.* import sttp.model.HttpVersion @@ -41,9 +41,9 @@ trait OEmbedServiceComponent { maxWidth: Option[String], maxHeight: Option[String], retryCount: Int - ): Try[OEmbed] = { + ): Try[OEmbedDTO] = { val uri = uri"${provider.requestUrl(url, maxWidth, maxHeight)}" - ndlaClient.fetch[OEmbed]( + ndlaClient.fetch[OEmbedDTO]( quickRequest .get(uri) .followRedirects(true) @@ -68,7 +68,7 @@ trait OEmbedServiceComponent { } } - def get(url: String, maxWidth: Option[String], maxHeight: Option[String]): Try[OEmbed] = { + def get(url: String, maxWidth: Option[String], maxHeight: Option[String]): Try[OEmbedDTO] = { io.lemonlabs.uri.Uri.parseTry(url) match { case Failure(_) => Failure(InvalidUrlException(s"$url does not seem to be a valid url.")) case Success(_) => diff --git a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/controller/OEmbedProxyControllerTest.scala b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/controller/OEmbedProxyControllerTest.scala index 7bc6029d5a..0599e2f72d 100644 --- a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/controller/OEmbedProxyControllerTest.scala +++ b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/controller/OEmbedProxyControllerTest.scala @@ -9,7 +9,7 @@ package no.ndla.oembedproxy.controller import no.ndla.network.model.HttpRequestException -import no.ndla.oembedproxy.model.OEmbed +import no.ndla.oembedproxy.model.OEmbedDTO import no.ndla.oembedproxy.{TestEnvironment, UnitSuite} import no.ndla.tapirtesting.TapirControllerTest import org.mockito.ArgumentMatchers.{any, anyString} @@ -23,7 +23,7 @@ import scala.util.{Failure, Success} class OEmbedProxyControllerTest extends UnitSuite with TestEnvironment with TapirControllerTest { val controller: OEmbedProxyController = new OEmbedProxyController - val oembed: OEmbed = OEmbed( + val oembed: OEmbedDTO = OEmbedDTO( `type` = "rich", version = "1.0", title = Some("Title"), diff --git a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedConverterServiceTest.scala b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedConverterServiceTest.scala index 207d790fff..f23886f5fb 100644 --- a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedConverterServiceTest.scala +++ b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedConverterServiceTest.scala @@ -7,7 +7,7 @@ package no.ndla.oembedproxy.service -import no.ndla.oembedproxy.model.OEmbed +import no.ndla.oembedproxy.model.OEmbedDTO import no.ndla.oembedproxy.{TestEnvironment, UnitSuite} class OEmbedConverterServiceTest extends UnitSuite with TestEnvironment { @@ -22,7 +22,7 @@ class OEmbedConverterServiceTest extends UnitSuite with TestEnvironment { "https://www.youtube.com/watch?start=43&end=58&v=vZCsuV7Rb_w" val requestUrlWithtoutTimestamp = "https://www.youtube.com/watch?v=vZCsuV7Rb_w" - val oembed = OEmbed( + val oembed = OEmbedDTO( "video", "1.0", Some("ESS® expandable sand screen"), @@ -75,7 +75,7 @@ class OEmbedConverterServiceTest extends UnitSuite with TestEnvironment { test("That rel=0 also is added to youtube url if defined in request") { val requestUrl = "https://www.youtube.com/watch?v=vZCsuV7Rb_w&rel=0&time_continue=5&meh=1" - val oembed = OEmbed( + val oembed = OEmbedDTO( "video", "1.0", Some("ESS® expandable sand screen"), diff --git a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedServiceTest.scala b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedServiceTest.scala index f587e4118c..bc471d5feb 100644 --- a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedServiceTest.scala +++ b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/OEmbedServiceTest.scala @@ -40,7 +40,7 @@ class OEmbedServiceTest extends UnitSuite with TestEnvironment { ) ) - val OEmbedResponse: OEmbed = OEmbed( + val OEmbedResponse: OEmbedDTO = OEmbedDTO( "rich", "1.0", Some("A Confectioner in the UK"), @@ -73,7 +73,7 @@ class OEmbedServiceTest extends UnitSuite with TestEnvironment { } test("That get returns a failure with HttpRequestException when receiving http error") { - when(ndlaClient.fetch[OEmbed](any[NdlaRequest])(any)) + when(ndlaClient.fetch[OEmbedDTO](any[NdlaRequest])(any)) .thenReturn(Failure(new HttpRequestException("An error occured"))) val oembedTry = oEmbedService.get("https://www.youtube.com/abc", None, None) oembedTry.isFailure should be(true) @@ -81,7 +81,7 @@ class OEmbedServiceTest extends UnitSuite with TestEnvironment { } test("That get returns a Success with an oEmbed when http call is successful") { - when(ndlaClient.fetch[OEmbed](any[NdlaRequest])(any)) + when(ndlaClient.fetch[OEmbedDTO](any[NdlaRequest])(any)) .thenReturn(Success(OEmbedResponse)) val oembedTry = oEmbedService.get("https://ndla.no/abc", None, None) oembedTry.isSuccess should be(true) diff --git a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/ProviderServiceTest.scala b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/ProviderServiceTest.scala index b8b77a7654..0b1059d257 100644 --- a/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/ProviderServiceTest.scala +++ b/oembed-proxy/src/test/scala/no/ndla/oembedproxy/service/ProviderServiceTest.scala @@ -43,7 +43,7 @@ class ProviderServiceTest extends UnitSuite with TestEnvironment { test("That loadProvidersFromRequest fails on invalid url/bad response") { val invalidUrl = "invalidUrl123" - when(ndlaClient.fetch[OEmbed](any[NdlaRequest])(any)) + when(ndlaClient.fetch[OEmbedDTO](any[NdlaRequest])(any)) .thenReturn(Failure(new HttpRequestException("An error occured"))) intercept[DoNotUpdateMemoizeException] { providerService.loadProvidersFromRequest(quickRequest.get(uri"$invalidUrl")) diff --git a/project/articleapi.scala b/project/articleapi.scala index 22bf33d823..c5aff98369 100644 --- a/project/articleapi.scala +++ b/project/articleapi.scala @@ -32,15 +32,14 @@ object articleapi extends Module { "no.ndla.common.model.domain.Availability" ), exports = Seq( - "ArticleV2", - "ArticleSearchParams", - "ArticleSummaryV2", + "ArticleV2DTO", + "ArticleSearchParamsDTO", + "ArticleSummaryV2DTO", "Availability", - "SearchResultV2", - "TagsSearchResult", - "ArticleDump", - "ValidationError", - "ArticleIds" + "SearchResultV2DTO", + "TagsSearchResultDTO", + "ArticleDumpDTO", + "ArticleIdsDTO" ) ) diff --git a/project/audioapi.scala b/project/audioapi.scala index 716f544e7c..3298bf8505 100644 --- a/project/audioapi.scala +++ b/project/audioapi.scala @@ -29,19 +29,19 @@ object audioapi extends Module { lazy val tsSettings: Seq[Def.Setting[?]] = typescriptSettings( imports = Seq("no.ndla.audioapi.model.api._"), exports = Seq( - "Audio", - "AudioSummarySearchResult", - "NewAudioMetaInformation", - "NewSeries", - "SearchParams", - "Series", - "SeriesSummary", - "AudioSummary", - "TagsSearchResult", - "AudioMetaInformation", - "UpdatedAudioMetaInformation", - "SeriesSummarySearchResult", - "SeriesSearchParams" + "AudioDTO", + "AudioSummarySearchResultDTO", + "NewAudioMetaInformationDTO", + "NewSeriesDTO", + "SearchParamsDTO", + "SeriesDTO", + "SeriesSummaryDTO", + "AudioSummaryDTO", + "TagsSearchResultDTO", + "AudioMetaInformationDTO", + "UpdatedAudioMetaInformationDTO", + "SeriesSummarySearchResultDTO", + "SeriesSearchParamsDTO" ) ) diff --git a/project/conceptapi.scala b/project/conceptapi.scala index 1928fac040..ef2413f2f6 100644 --- a/project/conceptapi.scala +++ b/project/conceptapi.scala @@ -28,16 +28,15 @@ object conceptapi extends Module { lazy val tsSettings: Seq[Def.Setting[?]] = typescriptSettings( imports = Seq("no.ndla.conceptapi.model.api._", "no.ndla.conceptapi.model.api.TSTypes._"), exports = Seq( - "Concept", - "ConceptSearchParams", - "ConceptSearchResult", - "ConceptSummary", - "DraftConceptSearchParams", - "NewConcept", - "SubjectTags", - "TagsSearchResult", - "UpdatedConcept", - "ValidationError" + "ConceptDTO", + "ConceptSearchParamsDTO", + "ConceptSearchResultDTO", + "ConceptSummaryDTO", + "DraftConceptSearchParamsDTO", + "NewConceptDTO", + "SubjectTagsDTO", + "TagsSearchResultDTO", + "UpdatedConceptDTO" ) ) diff --git a/project/draftapi.scala b/project/draftapi.scala index d5ae842bba..c01cb32e10 100644 --- a/project/draftapi.scala +++ b/project/draftapi.scala @@ -34,17 +34,17 @@ object draftapi extends Module { "no.ndla.common.model.domain.Availability" ), exports = Seq( - "Article", + "ArticleDTO", "Availability", - "NewArticle", - "SearchResult", - "GrepCodesSearchResult", - "TagsSearchResult", - "UpdatedArticle", - "UpdatedUserData", - "UploadedFile", - "UserData", - "ArticleSearchParams" + "NewArticleDTO", + "SearchResultDTO", + "GrepCodesSearchResultDTO", + "TagsSearchResultDTO", + "UpdatedArticleDTO", + "UpdatedUserDataDTO", + "UploadedFileDTO", + "UserDataDTO", + "ArticleSearchParamsDTO" ) ) diff --git a/project/frontpageapi.scala b/project/frontpageapi.scala index 39acab9098..fc2be0c673 100644 --- a/project/frontpageapi.scala +++ b/project/frontpageapi.scala @@ -23,14 +23,14 @@ object frontpageapi extends Module { lazy val tsSettings: Seq[Def.Setting[?]] = typescriptSettings( imports = Seq("no.ndla.frontpageapi.model.api._", "no.ndla.network.tapir._"), exports = Seq( - "no.ndla.common.model.api.FrontPage", - "no.ndla.common.model.api.MenuData", - "no.ndla.common.model.api.Menu", - "FilmFrontPageData", - "NewOrUpdatedFilmFrontPageData", - "SubjectPageData", - "NewSubjectFrontPageData", - "UpdatedSubjectFrontPageData", + "no.ndla.common.model.api.FrontPageDTO", + "no.ndla.common.model.api.MenuDataDTO", + "no.ndla.common.model.api.MenuDTO", + "FilmFrontPageDataDTO", + "NewOrUpdatedFilmFrontPageDataDTO", + "SubjectPageDataDTO", + "NewSubjectFrontPageDataDTO", + "UpdatedSubjectFrontPageDataDTO", "ErrorBody" ) ) diff --git a/project/imageapi.scala b/project/imageapi.scala index 5c0eb1eef6..6ada702e66 100644 --- a/project/imageapi.scala +++ b/project/imageapi.scala @@ -32,20 +32,19 @@ object imageapi extends Module { lazy val tsSettings: Seq[Def.Setting[?]] = typescriptSettings( imports = Seq( "no.ndla.imageapi.model.api._", - "no.ndla.imageapi.model.api.UpdateImageMetaInformation._" + "no.ndla.imageapi.model.api.UpdateImageMetaInformationDTO._" ), exports = Seq( - "Image", - "ImageMetaInformationV2", - "ImageMetaInformationV3", - "ImageMetaSummary", - "NewImageMetaInformationV2", - "SearchParams", - "SearchResult", - "SearchResultV3", - "TagsSearchResult", - "UpdateImageMetaInformation", - "ValidationError" + "ImageDTO", + "ImageMetaInformationV2DTO", + "ImageMetaInformationV3DTO", + "ImageMetaSummaryDTO", + "NewImageMetaInformationV2DTO", + "SearchParamsDTO", + "SearchResultDTO", + "SearchResultV3DTO", + "TagsSearchResultDTO", + "UpdateImageMetaInformationDTO" ) ) diff --git a/project/learningpathapi.scala b/project/learningpathapi.scala index 62657e8d2d..fb1d2a6c00 100644 --- a/project/learningpathapi.scala +++ b/project/learningpathapi.scala @@ -32,20 +32,20 @@ object learningpathapi extends Module { "no.ndla.common.model.api.config._" ), exports = Seq( - "Author", - "LearningPathStatus", - "LearningPathSummaryV2", - "LearningPathTagsSummary", - "LearningPathV2", - "LearningStepContainerSummary", - "LearningStepSeqNo", - "LearningStepStatus", - "LearningStepSummaryV2", - "LearningStepV2", - "License", - "SearchResultV2", - "ConfigMetaRestricted", - "config.ConfigMeta" + "AuthorDTO", + "LearningPathStatusDTO", + "LearningPathSummaryV2DTO", + "LearningPathTagsSummaryDTO", + "LearningPathV2DTO", + "LearningStepContainerSummaryDTO", + "LearningStepSeqNoDTO", + "LearningStepStatusDTO", + "LearningStepSummaryV2DTO", + "LearningStepV2DTO", + "LicenseDTO", + "SearchResultV2DTO", + "ConfigMetaRestrictedDTO", + "config.ConfigMetaDTO" ) ) diff --git a/project/myndlaapi.scala b/project/myndlaapi.scala index eaea020e3c..b0d28cfb38 100644 --- a/project/myndlaapi.scala +++ b/project/myndlaapi.scala @@ -30,38 +30,38 @@ object myndlaapi extends Module { "no.ndla.myndlaapi.model.arena.api._" ), exports = Seq( - "ConfigMetaRestricted", - "no.ndla.common.model.api.myndla.MyNDLAUser", - "no.ndla.common.model.api.myndla.UpdatedMyNDLAUser", + "ConfigMetaRestrictedDTO", + "no.ndla.common.model.api.myndla.MyNDLAUserDTO", + "no.ndla.common.model.api.myndla.UpdatedMyNDLAUserDTO", "no.ndla.common.model.domain.ResourceType", - "config.ConfigMeta", - "Folder", - "FolderData", - "NewFolder", - "UpdatedFolder", - "NewResource", - "UpdatedResource", - "ArenaUser", - "PaginatedArenaUsers", + "config.ConfigMetaDTO", + "FolderDTO", + "FolderDataDTO", + "NewFolderDTO", + "UpdatedFolderDTO", + "NewResourceDTO", + "UpdatedResourceDTO", + "ArenaUserDTO", + "PaginatedArenaUsersDTO", "no.ndla.common.model.domain.myndla.ArenaGroup", - "Category", - "CategoryWithTopics", - "Flag", - "NewCategory", - "NewPost", - "NewPostNotification", - "NewFlag", - "NewTopic", - "Topic", - "TopicWithPosts", - "PaginatedTopics", - "PaginatedPosts", - "PaginatedNewPostNotifications", - "Post", - "PostWrapper", - "Stats", - "SingleResourceStats", - "UserFolder" + "CategoryDTO", + "CategoryWithTopicsDTO", + "FlagDTO", + "NewCategoryDTO", + "NewPostDTO", + "NewPostNotificationDTO", + "NewFlagDTO", + "NewTopicDTO", + "TopicDTO", + "TopicWithPostsDTO", + "PaginatedTopicsDTO", + "PaginatedPostsDTO", + "PaginatedNewPostNotificationsDTO", + "PostDTO", + "PostWrapperDTO", + "StatsDTO", + "SingleResourceStatsDTO", + "UserFolderDTO" ) ) diff --git a/project/searchapi.scala b/project/searchapi.scala index 249b3f5ba3..5191b2582a 100644 --- a/project/searchapi.scala +++ b/project/searchapi.scala @@ -27,24 +27,23 @@ object searchapi extends Module { "no.ndla.searchapi.controller.parameters._" ), exports = Seq( - "ApiTaxonomyContext", - "ArticleResult", - "AudioResult", - "GroupSearchResult", - "ImageResult", - "LearningpathResult", - "MultiSearchResult", - "ArticleResults", - "AudioResults", - "ImageResults", - "LearningpathResults", - "SearchError", - "SearchParams", - "DraftSearchParams", - "SubjectAggregations", - "SubjectAggsInput", - "GrepSearchInput", - "grep.GrepSearchResults" + "ApiTaxonomyContextDTO", + "ArticleResultDTO", + "AudioResultDTO", + "GroupSearchResultDTO", + "ImageResultDTO", + "LearningpathResultDTO", + "MultiSearchResultDTO", + "ArticleResultsDTO", + "AudioResultsDTO", + "ImageResultsDTO", + "LearningpathResultsDTO", + "SearchParamsDTO", + "DraftSearchParamsDTO", + "SubjectAggregationsDTO", + "SubjectAggsInputDTO", + "GrepSearchInputDTO", + "grep.GrepSearchResultsDTO" ) ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/SearchController.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/SearchController.scala index d9d0937e1d..ba813b0b7c 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/controller/SearchController.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/controller/SearchController.scala @@ -21,11 +21,16 @@ import no.ndla.network.tapir.Parameters.feideHeader import no.ndla.network.tapir.{AllErrors, DynamicHeaders, NonEmptyString, TapirController} import no.ndla.network.tapir.TapirUtil.errorOutputsFor import no.ndla.network.tapir.auth.Permission.DRAFT_API_WRITE -import no.ndla.searchapi.controller.parameters.{DraftSearchParams, GrepSearchInput, SearchParams, SubjectAggsInput} +import no.ndla.searchapi.controller.parameters.{ + DraftSearchParamsDTO, + GrepSearchInputDTO, + SearchParamsDTO, + SubjectAggsInputDTO +} import no.ndla.searchapi.Props import no.ndla.searchapi.integration.SearchApiClient -import no.ndla.searchapi.model.api.grep.GrepSearchResults -import no.ndla.searchapi.model.api.{ErrorHandling, GroupSearchResult, MultiSearchResult, SubjectAggregations} +import no.ndla.searchapi.model.api.grep.GrepSearchResultsDTO +import no.ndla.searchapi.model.api.{ErrorHandling, GroupSearchResultDTO, MultiSearchResultDTO, SubjectAggregationsDTO} import no.ndla.searchapi.model.domain.{LearningResourceType, Sort} import no.ndla.searchapi.model.search.SearchType import no.ndla.searchapi.model.search.settings.{MultiDraftSearchSettings, SearchSettings} @@ -169,8 +174,8 @@ trait SearchController { .summary("List subjects with aggregated data about their contents") .description("List subjects with aggregated data about their contents") .in("subjects") - .in(jsonBody[SubjectAggsInput]) - .out(jsonBody[SubjectAggregations]) + .in(jsonBody[SubjectAggsInputDTO]) + .out(jsonBody[SubjectAggregationsDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => input => @@ -202,7 +207,7 @@ trait SearchController { .in(embedId) .in(filterInactive) .in(feideHeader) - .out(jsonBody[Seq[GroupSearchResult]]) + .out(jsonBody[Seq[GroupSearchResultDTO]]) .errorOut(errorOutputsFor(401, 403)) .serverLogicPure { case ( @@ -263,7 +268,7 @@ trait SearchController { } } - private def searchInGroup(group: String, settings: SearchSettings): Try[GroupSearchResult] = { + private def searchInGroup(group: String, settings: SearchSettings): Try[GroupSearchResultDTO] = { multiSearchService .matchingQuery(settings) .map(res => searchConverterService.toApiGroupMultiSearchResult(group, res)) @@ -275,7 +280,7 @@ trait SearchController { private def groupSearch( settings: SearchSettings, includeMissingResourceTypeGroup: Boolean - ): Either[AllErrors, Seq[GroupSearchResult]] = { + ): Either[AllErrors, Seq[GroupSearchResultDTO]] = { val numMissingRtThreads = if (includeMissingResourceTypeGroup) 1 else 0 val numGroups = settings.resourceTypes.size + settings.learningResourceTypes.size + numMissingRtThreads if (numGroups >= 1) { @@ -342,8 +347,8 @@ trait SearchController { * A Try with scroll result, or the return of the orFunction (Usually a try with a search result). */ private def scrollWithOr[T <: SearchService](scrollId: Option[String], language: String, scroller: T)( - orFunction: => Try[(MultiSearchResult, DynamicHeaders)] - ): Try[(MultiSearchResult, DynamicHeaders)] = { + orFunction: => Try[(MultiSearchResultDTO, DynamicHeaders)] + ): Try[(MultiSearchResultDTO, DynamicHeaders)] = { scrollId match { case Some(scroll) if !InitialScrollContextKeywords.contains(scroll) => for { @@ -359,7 +364,7 @@ trait SearchController { .summary("Find learning resources") .description("Shows all learning resources. You can search too.") .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[MultiSearchResult]) + .out(jsonBody[MultiSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .in(pageNo) .in(pageSize) @@ -452,9 +457,9 @@ trait SearchController { .summary("Find learning resources") .description("Shows all learning resources. You can search too.") .errorOut(errorOutputsFor(400)) - .out(jsonBody[MultiSearchResult]) + .out(jsonBody[MultiSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) - .in(jsonBody[Option[SearchParams]].schema(SearchParams.schema.asOption)) + .in(jsonBody[Option[SearchParamsDTO]].schema(SearchParamsDTO.schema.asOption)) .in(feideHeader) .serverLogicPure { case (searchParams, feideToken) => getAvailability(feideToken) @@ -520,14 +525,14 @@ trait SearchController { .in("editorial") .in(queryParams) .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[MultiSearchResult]) + .out(jsonBody[MultiSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => { implicit queryParams => val searchParams = Some( - DraftSearchParams( + DraftSearchParamsDTO( page = intParamOrNone("page"), pageSize = intParamOrNone("page-size"), articleTypes = stringListParam("article-types").some, @@ -580,9 +585,9 @@ trait SearchController { .summary("Find draft learning resources") .description("Shows all draft learning resources. You can search too.") .in("editorial") - .in(jsonBody[Option[DraftSearchParams]].schema(DraftSearchParams.schema.asOption)) + .in(jsonBody[Option[DraftSearchParamsDTO]].schema(DraftSearchParamsDTO.schema.asOption)) .errorOut(errorOutputsFor(400, 401, 403)) - .out(jsonBody[MultiSearchResult]) + .out(jsonBody[MultiSearchResultDTO]) .out(EndpointOutput.derived[DynamicHeaders]) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => searchParams => @@ -600,8 +605,8 @@ trait SearchController { .summary("Search for grep codes") .description("Search for grep codes") .in("grep") - .in(jsonBody[GrepSearchInput]) - .out(jsonBody[GrepSearchResults]) + .in(jsonBody[GrepSearchInputDTO]) + .out(jsonBody[GrepSearchResultsDTO]) .errorOut(errorOutputsFor(400, 401, 403)) .requirePermission(DRAFT_API_WRITE) .serverLogicPure { _ => input => grepSearchService.searchGreps(input) } @@ -628,7 +633,7 @@ trait SearchController { } } - def asSettings(p: Option[SearchParams], availability: List[Availability]): SearchSettings = { + def asSettings(p: Option[SearchParamsDTO], availability: List[Availability]): SearchSettings = { p match { case None => SearchSettings.default case Some(params) => @@ -662,7 +667,7 @@ trait SearchController { } - def asDraftSettings(p: Option[DraftSearchParams]): MultiDraftSearchSettings = { + def asDraftSettings(p: Option[DraftSearchParamsDTO]): MultiDraftSearchSettings = { p match { case None => MultiDraftSearchSettings.default case Some(params) => diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParams.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParams.scala deleted file mode 100644 index 57b300f26a..0000000000 --- a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParams.scala +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Part of NDLA search-api - * Copyright (C) 2024 NDLA - * - * See LICENSE - */ - -package no.ndla.searchapi.controller.parameters - -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import io.circe.{Decoder, Encoder} -import no.ndla.common.model.NDLADate -import no.ndla.network.tapir.NonEmptyString -import no.ndla.searchapi.model.domain.Sort -import no.ndla.searchapi.model.search.SearchType -import sttp.tapir.Schema -import sttp.tapir.Schema.annotations.description - - // format: off - case class DraftSearchParams( - @description("The page number of the search hits to display.") - page: Option[Int], - - @description(s"The number of search hits to display for each page.") - pageSize: Option[Int], - - @description("A list of article-types the search should be filtered by.") - articleTypes: Option[List[String]], - - @description("A list of context-types the learning resources should be filtered by.") - contextTypes: Option[List[String]], - - @description("The ISO 639-1 language code describing language.") - language: Option[String], - - @description("Return only learning resources that have one of the provided ids.") - ids: Option[List[Long]], - - @description("Return only learning resources of specific type(s).") - resourceTypes: Option[List[String]], - - @description("Return only results with provided license.") - license: Option[String], - - @description("Return only results with content matching the specified query.") - query: Option[NonEmptyString], - - @description("Return only results with notes matching the specified note-query.") - noteQuery: Option[NonEmptyString], - - @description("The sorting used on results.") - sort: Option[Sort], - - @description("Fallback to existing language if language is specified.") - fallback: Option[Boolean], - - @description("A comma separated list of subjects the learning resources should be filtered by.") - subjects: Option[List[String]], - - @description("A list of ISO 639-1 language codes that the learning resource can be available in.") - languageFilter: Option[List[String]], - - @description( - """A list of relevances the learning resources should be filtered by. - |If subjects are specified the learning resource must have specified relevances in relation to a specified subject. - |If levels are specified the learning resource must have specified relevances in relation to a specified level.""".stripMargin) - relevance: Option[List[String]], - - - @description( - s"""A unique string obtained from a search you want to keep scrolling in. To obtain one from a search, provide one of the following values: ["0", "initial", "start", "first"]. - |When scrolling, the parameters from the initial search is used, except in the case of 'language' and 'fallback'. - |This value may change between scrolls. Always use the one in the latest scroll result. - |""".stripMargin) - scrollId: Option[String], - - @description("List of statuses to filter by. A draft only needs to have one of the available statuses to be included in result (OR).") - draftStatus: Option[List[String]], - - @description( - s"""List of users to filter by. - |The value to search for is the user-id from Auth0. - |UpdatedBy on article and user in editorial-notes are searched.""".stripMargin) - users: Option[List[String]], - - @description("A list of codes from GREP API the resources should be filtered by.") - grepCodes: Option[List[String]], - - @description("List of index-paths that should be term-aggregated and returned in result.") - aggregatePaths: Option[List[String]], - - @description("Return only results with embed data-resource the specified resource. Can specify multiple with a comma separated list to filter for one of the embed types.") - embedResource: Option[List[String]], - - @description("Return only results with embed data-resource_id, data-videoid or data-url with the specified id.") - embedId: Option[String], - - @description("Whether or not to include the 'other' status field when filtering with 'status' param.") - includeOtherStatuses: Option[Boolean], - - @description("Return only results having next revision after this date.") - revisionDateFrom: Option[NDLADate], - - @description("Return only results having next revision before this date.") - revisionDateTo: Option[NDLADate], - - @description("Set to true to avoid including hits from the revision history log.") - excludeRevisionLog: Option[Boolean], - - @description("List of responsible ids to filter by (OR filter).") - responsibleIds: Option[List[String]], - - @description("Filter out inactive taxonomy contexts.") - filterInactive: Option[Boolean], - - @description("Set to true to only return prioritized articles") - prioritized: Option[Boolean], - - @description("List of priority-levels to filter by.") - priority: Option[List[String]], - - @description("A list of parent topics the learning resources should be filtered by.") - topics: Option[List[String]], - - @description("Return only results having published date after this date.") - publishedDateFrom: Option[NDLADate], - - @description("Return only results having published date before this date.") - publishedDateTo: Option[NDLADate], - - @description("Types of hits to appear in the result") - resultTypes: Option[List[SearchType]] - ) -// format: on - -object DraftSearchParams { - implicit val encoder: Encoder[DraftSearchParams] = deriveEncoder - implicit val decoder: Decoder[DraftSearchParams] = deriveDecoder - implicit val schema: Schema[DraftSearchParams] = Schema.derived[DraftSearchParams] -} diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParamsDTO.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParamsDTO.scala new file mode 100644 index 0000000000..ced0e87ab2 --- /dev/null +++ b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/DraftSearchParamsDTO.scala @@ -0,0 +1,109 @@ +/* + * Part of NDLA search-api + * Copyright (C) 2024 NDLA + * + * See LICENSE + */ + +package no.ndla.searchapi.controller.parameters + +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import io.circe.{Decoder, Encoder} +import no.ndla.common.model.NDLADate +import no.ndla.network.tapir.NonEmptyString +import no.ndla.searchapi.model.domain.Sort +import no.ndla.searchapi.model.search.SearchType +import sttp.tapir.Schema +import sttp.tapir.Schema.annotations.description + +case class DraftSearchParamsDTO( + @description("The page number of the search hits to display.") + page: Option[Int], + @description(s"The number of search hits to display for each page.") + pageSize: Option[Int], + @description("A list of article-types the search should be filtered by.") + articleTypes: Option[List[String]], + @description("A list of context-types the learning resources should be filtered by.") + contextTypes: Option[List[String]], + @description("The ISO 639-1 language code describing language.") + language: Option[String], + @description("Return only learning resources that have one of the provided ids.") + ids: Option[List[Long]], + @description("Return only learning resources of specific type(s).") + resourceTypes: Option[List[String]], + @description("Return only results with provided license.") + license: Option[String], + @description("Return only results with content matching the specified query.") + query: Option[NonEmptyString], + @description("Return only results with notes matching the specified note-query.") + noteQuery: Option[NonEmptyString], + @description("The sorting used on results.") + sort: Option[Sort], + @description("Fallback to existing language if language is specified.") + fallback: Option[Boolean], + @description("A comma separated list of subjects the learning resources should be filtered by.") + subjects: Option[List[String]], + @description("A list of ISO 639-1 language codes that the learning resource can be available in.") + languageFilter: Option[List[String]], + @description( + """A list of relevances the learning resources should be filtered by. + |If subjects are specified the learning resource must have specified relevances in relation to a specified subject. + |If levels are specified the learning resource must have specified relevances in relation to a specified level.""".stripMargin + ) + relevance: Option[List[String]], + @description( + s"""A unique string obtained from a search you want to keep scrolling in. To obtain one from a search, provide one of the following values: ["0", "initial", "start", "first"]. + |When scrolling, the parameters from the initial search is used, except in the case of 'language' and 'fallback'. + |This value may change between scrolls. Always use the one in the latest scroll result. + |""".stripMargin + ) + scrollId: Option[String], + @description( + "List of statuses to filter by. A draft only needs to have one of the available statuses to be included in result (OR)." + ) + draftStatus: Option[List[String]], + @description(s"""List of users to filter by. + |The value to search for is the user-id from Auth0. + |UpdatedBy on article and user in editorial-notes are searched.""".stripMargin) + users: Option[List[String]], + @description("A list of codes from GREP API the resources should be filtered by.") + grepCodes: Option[List[String]], + @description("List of index-paths that should be term-aggregated and returned in result.") + aggregatePaths: Option[List[String]], + @description( + "Return only results with embed data-resource the specified resource. Can specify multiple with a comma separated list to filter for one of the embed types." + ) + embedResource: Option[List[String]], + @description("Return only results with embed data-resource_id, data-videoid or data-url with the specified id.") + embedId: Option[String], + @description("Whether or not to include the 'other' status field when filtering with 'status' param.") + includeOtherStatuses: Option[Boolean], + @description("Return only results having next revision after this date.") + revisionDateFrom: Option[NDLADate], + @description("Return only results having next revision before this date.") + revisionDateTo: Option[NDLADate], + @description("Set to true to avoid including hits from the revision history log.") + excludeRevisionLog: Option[Boolean], + @description("List of responsible ids to filter by (OR filter).") + responsibleIds: Option[List[String]], + @description("Filter out inactive taxonomy contexts.") + filterInactive: Option[Boolean], + @description("Set to true to only return prioritized articles") + prioritized: Option[Boolean], + @description("List of priority-levels to filter by.") + priority: Option[List[String]], + @description("A list of parent topics the learning resources should be filtered by.") + topics: Option[List[String]], + @description("Return only results having published date after this date.") + publishedDateFrom: Option[NDLADate], + @description("Return only results having published date before this date.") + publishedDateTo: Option[NDLADate], + @description("Types of hits to appear in the result") + resultTypes: Option[List[SearchType]] +) + +object DraftSearchParamsDTO { + implicit val encoder: Encoder[DraftSearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[DraftSearchParamsDTO] = deriveDecoder + implicit val schema: Schema[DraftSearchParamsDTO] = Schema.derived[DraftSearchParamsDTO] +} diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInput.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInputDTO.scala similarity index 79% rename from search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInput.scala rename to search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInputDTO.scala index fae25ad114..a3f46f89ce 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInput.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/GrepSearchInputDTO.scala @@ -11,35 +11,28 @@ package no.ndla.searchapi.controller.parameters import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import no.ndla.network.tapir.NonEmptyString -import no.ndla.searchapi.model.api.grep.GrepSort +import no.ndla.searchapi.model.api.grep.GrepSortDTO import sttp.tapir.Schema.annotations.description -// format: off @description("Input parameters to subject aggregations endpoint") -case class GrepSearchInput( +case class GrepSearchInputDTO( @description("A comma separated list of prefixes that should be returned in the search.") prefixFilter: Option[List[String]], - @description("A comma separated list of codes that should be returned in the search.") codes: Option[List[String]], - @description("A query to filter the query by.") query: Option[NonEmptyString], - @description("The page number of the search hits to display.") page: Option[Int], - @description(s"The number of search hits to display for each page.") pageSize: Option[Int], - @description("The sort order of the search hits.") - sort: Option[GrepSort], - + sort: Option[GrepSortDTO], @description("The ISO 639-1 language code describing language used in query-params") language: Option[String] ) -object GrepSearchInput { - implicit val encoder: Encoder[GrepSearchInput] = deriveEncoder - implicit val decoder: Decoder[GrepSearchInput] = deriveDecoder +object GrepSearchInputDTO { + implicit val encoder: Encoder[GrepSearchInputDTO] = deriveEncoder + implicit val decoder: Decoder[GrepSearchInputDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParams.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParamsDTO.scala similarity index 83% rename from search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParams.scala rename to search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParamsDTO.scala index 528e37339a..e05506c8ce 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParams.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SearchParamsDTO.scala @@ -16,81 +16,66 @@ import no.ndla.searchapi.model.domain.Sort import sttp.tapir.Schema import sttp.tapir.Schema.annotations.description -// format: off -case class SearchParams ( +case class SearchParamsDTO( @description("The page number of the search hits to display.") page: Option[Int], - @description(s"The number of search hits to display for each page.") pageSize: Option[Int], - @description("A list of article-types the search should be filtered by.") articleTypes: Option[List[String]], - @description( s"""A unique string obtained from a search you want to keep scrolling in. To obtain one from a search, provide one of the following values: ["0", "initial", "start", "first"]. |When scrolling, the parameters from the initial search is used, except in the case of 'language' and 'fallback'. |This value may change between scrolls. Always use the one in the latest scroll result. - |""".stripMargin) + |""".stripMargin + ) scrollId: Option[String], - @description("Return only results with content matching the specified query.") query: Option[NonEmptyString], - @description("Fallback to existing language if language is specified.") fallback: Option[Boolean], - @description("The ISO 639-1 language code describing language.") language: Option[String], - @description("Return only results with provided license.") license: Option[String], - @description("The sorting used on results.") sort: Option[Sort], - @description("Return only learning resources that have one of the provided ids.") ids: Option[List[Long]], - @description("A comma separated list of subjects the learning resources should be filtered by.") subjects: Option[List[String]], - @description("Return only learning resources of specific type(s).") resourceTypes: Option[List[String]], - @description("A list of context-types the learning resources should be filtered by.") contextTypes: Option[List[String]], - @description( """A list of relevances the learning resources should be filtered by. |If subjects are specified the learning resource must have specified relevances in relation to a specified subject. - |If levels are specified the learning resource must have specified relevances in relation to a specified level.""".stripMargin) + |If levels are specified the learning resource must have specified relevances in relation to a specified level.""".stripMargin + ) relevance: Option[List[String]], - @description("A list of ISO 639-1 language codes that the learning resource can be available in.") languageFilter: Option[List[String]], - @description("A list of codes from GREP API the resources should be filtered by.") grepCodes: Option[List[String]], - @description("List of index-paths that should be term-aggregated and returned in result.") aggregatePaths: Option[List[String]], - - @description("Return only results with embed data-resource the specified resource. Can specify multiple with a comma separated list to filter for one of the embed types.") + @description( + "Return only results with embed data-resource the specified resource. Can specify multiple with a comma separated list to filter for one of the embed types." + ) embedResource: Option[List[String]], - @description("Return only results with embed data-resource_id, data-videoid or data-url with the specified id.") embedId: Option[String], - @description("Filter out inactive taxonomy contexts.") - filterInactive: Option[Boolean], + filterInactive: Option[Boolean] ) -object SearchParams { - implicit val encoder: Encoder[SearchParams] = deriveEncoder - implicit val decoder: Decoder[SearchParams] = deriveDecoder - implicit val schema: Schema[SearchParams] = Schema.derived[SearchParams] +object SearchParamsDTO { + implicit val encoder: Encoder[SearchParamsDTO] = deriveEncoder + implicit val decoder: Decoder[SearchParamsDTO] = deriveDecoder + implicit val schema: Schema[SearchParamsDTO] = Schema.derived[SearchParamsDTO] import com.scalatsi.dsl.* - implicit val tsType: TSIType[SearchParams] = TSType.fromCaseClass[SearchParams] - "sort" + ("sort", TSString | TSUndefined) + implicit val tsType: TSIType[SearchParamsDTO] = + TSType.fromCaseClass[SearchParamsDTO] - "sort" + ("sort", TSString | TSUndefined) } diff --git a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInput.scala b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInputDTO.scala similarity index 71% rename from search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInput.scala rename to search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInputDTO.scala index a4a4b59aea..a702958cc8 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInput.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/controller/parameters/SubjectAggsInputDTO.scala @@ -13,12 +13,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Input parameters to subject aggregations endpoint") -case class SubjectAggsInput( +case class SubjectAggsInputDTO( @description("A comma separated list of subjects the learning resources should be filtered by.") subjects: Option[List[String]] ) -object SubjectAggsInput { - implicit val encoder: Encoder[SubjectAggsInput] = deriveEncoder - implicit val decoder: Decoder[SubjectAggsInput] = deriveDecoder +object SubjectAggsInputDTO { + implicit val encoder: Encoder[SubjectAggsInputDTO] = deriveEncoder + implicit val decoder: Decoder[SubjectAggsInputDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContext.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContextDTO.scala similarity index 84% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContext.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContextDTO.scala index 3fa796a5f5..e779fb188c 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContext.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/ApiTaxonomyContextDTO.scala @@ -12,7 +12,7 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import sttp.tapir.Schema.annotations.description @description("Taxonomy context for the resource") -case class ApiTaxonomyContext( +case class ApiTaxonomyContextDTO( @description("Id of the taxonomy object.") publicId: String, @description("Name of the root node this context is in.") root: String, @description("Id of the root node this context is in.") rootId: String, @@ -22,14 +22,14 @@ case class ApiTaxonomyContext( @description("Breadcrumbs of path to the resource in this context.") breadcrumbs: List[String], @description("Unique id of this context.") contextId: String, @description("Type in this context.") contextType: String, - @description("Resource-types of this context.") resourceTypes: List[TaxonomyResourceType], + @description("Resource-types of this context.") resourceTypes: List[TaxonomyResourceTypeDTO], @description("Language for this context.") language: String, @description("Whether this context is the primary connection") isPrimary: Boolean, @description("Whether this context is active") isActive: Boolean, @description("Unique url for this context.") url: String ) -object ApiTaxonomyContext { - implicit val encoder: Encoder[ApiTaxonomyContext] = deriveEncoder - implicit val decoder: Decoder[ApiTaxonomyContext] = deriveDecoder +object ApiTaxonomyContextDTO { + implicit val encoder: Encoder[ApiTaxonomyContextDTO] = deriveEncoder + implicit val decoder: Decoder[ApiTaxonomyContextDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResultDTO.scala similarity index 80% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResultDTO.scala index 116f4ae85a..f4f64a7fbe 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/ArticleResultDTO.scala @@ -7,14 +7,14 @@ package no.ndla.searchapi.model.api -import no.ndla.searchapi.model.api.article.ArticleIntroduction +import no.ndla.searchapi.model.api.article.ArticleIntroductionDTO import sttp.tapir.Schema.annotations.description @description("Search result for article api") -case class ArticleResult( +case class ArticleResultDTO( @description("The unique id of this article") id: Long, - @description("The title of the article") title: TitleWithHtml, - @description("The introduction of the article") introduction: Option[ArticleIntroduction], + @description("The title of the article") title: TitleWithHtmlDTO, + @description("The introduction of the article") introduction: Option[ArticleIntroductionDTO], @description("The type of the article") articleType: String, @description("List of supported languages") supportedLanguages: Seq[String] ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResultDTO.scala similarity index 82% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResultDTO.scala index c77e92c4ea..ae64b47e4a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/AudioResultDTO.scala @@ -10,9 +10,9 @@ package no.ndla.searchapi.model.api import sttp.tapir.Schema.annotations.description @description("Search result for audio api") -case class AudioResult( +case class AudioResultDTO( @description("The unique id of this audio") id: Long, - @description("The title of this audio") title: Title, + @description("The title of this audio") title: TitleDTO, @description("A direct link to the audio") url: String, @description("List of supported languages") supportedLanguages: Seq[String] ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsible.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsibleDTO.scala similarity index 72% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsible.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsibleDTO.scala index 34d1b57e68..1aaadc033d 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsible.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/DraftResponsibleDTO.scala @@ -13,12 +13,12 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about the responsible") -case class DraftResponsible( +case class DraftResponsibleDTO( @description("NDLA ID of responsible editor") responsibleId: String, @description("Date of when the responsible editor was last updated") lastUpdated: NDLADate ) -object DraftResponsible { - implicit val encoder: Encoder[DraftResponsible] = deriveEncoder - implicit val decoder: Decoder[DraftResponsible] = deriveDecoder +object DraftResponsibleDTO { + implicit val encoder: Encoder[DraftResponsibleDTO] = deriveEncoder + implicit val decoder: Decoder[DraftResponsibleDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResultDTO.scala similarity index 71% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResultDTO.scala index 9b8d8ceece..98b58c3fff 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/GroupSearchResultDTO.scala @@ -9,22 +9,22 @@ package no.ndla.searchapi.model.api import io.circe.{Decoder, Encoder} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import no.ndla.search.api.MultiSearchTermsAggregation +import no.ndla.search.api.MultiSearchTermsAggregationDTO import sttp.tapir.Schema.annotations.description @description("Search result for group search") -case class GroupSearchResult( +case class GroupSearchResultDTO( @description("The total number of resources matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[MultiSearchSummary], - @description("The suggestions for other searches") suggestions: Seq[MultiSearchSuggestion], - @description("The aggregated fields if specified in query") aggregations: Seq[MultiSearchTermsAggregation], + @description("The search results") results: Seq[MultiSearchSummaryDTO], + @description("The suggestions for other searches") suggestions: Seq[MultiSearchSuggestionDTO], + @description("The aggregated fields if specified in query") aggregations: Seq[MultiSearchTermsAggregationDTO], @description("Type of resources in this object") resourceType: String ) -object GroupSearchResult { - implicit val encoder: Encoder[GroupSearchResult] = deriveEncoder - implicit val decoder: Decoder[GroupSearchResult] = deriveDecoder +object GroupSearchResultDTO { + implicit val encoder: Encoder[GroupSearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[GroupSearchResultDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltText.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltTextDTO.scala similarity index 93% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltText.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltTextDTO.scala index 74fafa8f7b..db12b15900 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltText.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageAltTextDTO.scala @@ -10,7 +10,7 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("Title of resource") -case class ImageAltText( +case class ImageAltTextDTO( @description("The freetext alttext of the image") altText: String, @description("ISO 639-1 code that represents the language used in alttext") language: String ) extends WithLanguage diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResultDTO.scala similarity index 85% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResultDTO.scala index 35a9f35afb..9f1f2107f9 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/ImageResultDTO.scala @@ -10,10 +10,10 @@ package no.ndla.searchapi.model.api import sttp.tapir.Schema.annotations.description @description("Search result for image api") -case class ImageResult( +case class ImageResultDTO( @description("The unique id of this image") id: Long, - @description("The title of this image") title: Title, - @description("The alt text of this image") altText: ImageAltText, + @description("The title of this image") title: TitleDTO, + @description("The alt text of this image") altText: ImageAltTextDTO, @description("A direct link to the image") previewUrl: String, @description("A link to get meta data related to the image") metaUrl: String, @description("List of supported languages") supportedLanguages: Seq[String] diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroduction.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroductionDTO.scala similarity index 92% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroduction.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroductionDTO.scala index 5247d8d574..8b0c9df125 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroduction.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningPathIntroductionDTO.scala @@ -10,7 +10,7 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("Introduction of learningPath") -case class LearningPathIntroduction( +case class LearningPathIntroductionDTO( @description("The freetext introduction of the learningpath") introduction: String, @description("ISO 639-1 code that represents the language used in introduction") language: String ) extends WithLanguage diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResultDTO.scala similarity index 75% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResultDTO.scala index 40ee90d373..10bde36e4b 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/LearningpathResultDTO.scala @@ -10,9 +10,9 @@ package no.ndla.searchapi.model.api import sttp.tapir.Schema.annotations.description @description("Search result for learningpath api") -case class LearningpathResult( +case class LearningpathResultDTO( @description("The unique id of this learningpath") id: Long, - @description("The title of the learningpath") title: Title, - @description("The introduction of the learningpath") introduction: LearningPathIntroduction, + @description("The title of the learningpath") title: TitleDTO, + @description("The introduction of the learningpath") introduction: LearningPathIntroductionDTO, @description("List of supported languages") supportedLanguages: Seq[String] ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescription.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescriptionDTO.scala similarity index 75% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescription.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescriptionDTO.scala index 55924a4ef7..bca31f6231 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescription.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaDescriptionDTO.scala @@ -13,14 +13,14 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("Meta description of the resource") -case class MetaDescription( +case class MetaDescriptionDTO( @description("The meta description") metaDescription: String, @description( "The ISO 639-1 language code describing which article translation this meta description belongs to" ) language: String ) extends WithLanguage -object MetaDescription { - implicit val encoder: Encoder[MetaDescription] = deriveEncoder - implicit val decoder: Decoder[MetaDescription] = deriveDecoder +object MetaDescriptionDTO { + implicit val encoder: Encoder[MetaDescriptionDTO] = deriveEncoder + implicit val decoder: Decoder[MetaDescriptionDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImage.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImageDTO.scala similarity index 81% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImage.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImageDTO.scala index f3bc67b9dd..ebb702485a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImage.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/MetaImageDTO.scala @@ -12,7 +12,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("Meta image of the resource") -case class MetaImage( +case class MetaImageDTO( @description("The meta image id") url: String, @description("The meta image alt text") alt: String, @description("The ISO 639-1 language code describing which translation this meta image belongs to") language: String @@ -21,7 +21,7 @@ case class MetaImage( override def isEmpty: Boolean = url.isEmpty || alt.isEmpty } -object MetaImage { - implicit val encoder: Encoder[MetaImage] = deriveEncoder - implicit val decoder: Decoder[MetaImage] = deriveDecoder +object MetaImageDTO { + implicit val encoder: Encoder[MetaImageDTO] = deriveEncoder + implicit val decoder: Decoder[MetaImageDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResultDTO.scala similarity index 69% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResultDTO.scala index 49b2d44516..8aeaaf815a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchResultDTO.scala @@ -9,21 +9,21 @@ package no.ndla.searchapi.model.api import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.search.api.MultiSearchTermsAggregation +import no.ndla.search.api.MultiSearchTermsAggregationDTO import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class MultiSearchResult( +case class MultiSearchResultDTO( @description("The total number of resources matching this query") totalCount: Long, @description("For which page results are shown from") page: Option[Int], @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[MultiSearchSummary], - @description("The suggestions for other searches") suggestions: Seq[MultiSearchSuggestion], - @description("The aggregated fields if specified in query") aggregations: Seq[MultiSearchTermsAggregation] + @description("The search results") results: Seq[MultiSearchSummaryDTO], + @description("The suggestions for other searches") suggestions: Seq[MultiSearchSuggestionDTO], + @description("The aggregated fields if specified in query") aggregations: Seq[MultiSearchTermsAggregationDTO] ) -object MultiSearchResult { - implicit val encoder: Encoder[MultiSearchResult] = deriveEncoder - implicit val decoder: Decoder[MultiSearchResult] = deriveDecoder +object MultiSearchResultDTO { + implicit val encoder: Encoder[MultiSearchResultDTO] = deriveEncoder + implicit val decoder: Decoder[MultiSearchResultDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestion.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestionDTO.scala similarity index 59% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestion.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestionDTO.scala index 6e0e0d8b35..3e7e3bd89c 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestion.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSuggestionDTO.scala @@ -12,36 +12,36 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about search-suggestions") -case class MultiSearchSuggestion( +case class MultiSearchSuggestionDTO( @description("The name of the field suggested for") name: String, - @description("The list of suggestions for given field") suggestions: Seq[SearchSuggestion] + @description("The list of suggestions for given field") suggestions: Seq[SearchSuggestionDTO] ) -object MultiSearchSuggestion { - implicit val encoder: Encoder[MultiSearchSuggestion] = deriveEncoder - implicit val decoder: Decoder[MultiSearchSuggestion] = deriveDecoder +object MultiSearchSuggestionDTO { + implicit val encoder: Encoder[MultiSearchSuggestionDTO] = deriveEncoder + implicit val decoder: Decoder[MultiSearchSuggestionDTO] = deriveDecoder } @description("Search suggestion for query-text") -case class SearchSuggestion( +case class SearchSuggestionDTO( @description("The search query suggestions are made for") text: String, @description("The offset in the search query") offset: Int, @description("The position index in the search query") length: Int, - @description("The list of suggest options for the field") options: Seq[SuggestOption] + @description("The list of suggest options for the field") options: Seq[SuggestOptionDTO] ) -object SearchSuggestion { - implicit val encoder: Encoder[SearchSuggestion] = deriveEncoder - implicit val decoder: Decoder[SearchSuggestion] = deriveDecoder +object SearchSuggestionDTO { + implicit val encoder: Encoder[SearchSuggestionDTO] = deriveEncoder + implicit val decoder: Decoder[SearchSuggestionDTO] = deriveDecoder } @description("Search suggestion options for the terms in the query") -case class SuggestOption( +case class SuggestOptionDTO( @description("The suggested text") text: String, @description("The score of the suggestion") score: Double ) -object SuggestOption { - implicit val encoder: Encoder[SuggestOption] = deriveEncoder - implicit val decoder: Decoder[SuggestOption] = deriveDecoder +object SuggestOptionDTO { + implicit val encoder: Encoder[SuggestOptionDTO] = deriveEncoder + implicit val decoder: Decoder[SuggestOptionDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummary.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummary.scala deleted file mode 100644 index a9a095e7a0..0000000000 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummary.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Part of NDLA search-api - * Copyright (C) 2018 NDLA - * - * See LICENSE - */ - -package no.ndla.searchapi.model.api - -import io.circe.{Decoder, Encoder} -import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} -import no.ndla.common.model.NDLADate -import no.ndla.common.model.api.draft.Comment -import no.ndla.searchapi.model.domain.LearningResourceType -import no.ndla.searchapi.model.search.SearchType -import sttp.tapir.Schema.annotations.description - -@description("Object describing matched field with matching words emphasized") -case class HighlightedField( - @description("Field that matched") field: String, - @description("List of segments that matched in `field`") matches: Seq[String] -) - -object HighlightedField { - implicit val encoder: Encoder[HighlightedField] = deriveEncoder - implicit val decoder: Decoder[HighlightedField] = deriveDecoder -} - -// format: off -@description("Short summary of information about the resource") -case class MultiSearchSummary( - @description("The unique id of the resource") id: Long, - @description("The title of the resource") title: TitleWithHtml, - @description("The meta description of the resource") metaDescription: MetaDescription, - @description("The meta image for the resource") metaImage: Option[MetaImage], - @description("Url pointing to the resource") url: String, - @description("Contexts of the resource") contexts: List[ApiTaxonomyContext], - @description("Languages the resource exists in") supportedLanguages: Seq[String], - @description("Learning resource type") learningResourceType: LearningResourceType, - @description("Status information of the resource") status: Option[Status], - @description("Traits for the resource") traits: List[String], - @description("Relevance score. The higher the score, the better the document matches your search criteria.") score: Float, - @description("List of objects describing matched field with matching words emphasized") highlights: List[HighlightedField], - @description("The taxonomy paths for the resource") paths: List[String], - @description("The time and date of last update") lastUpdated: NDLADate, - @description("Describes the license of the resource") license: Option[String], - @description("A list of revisions planned for the article") revisions: Seq[RevisionMeta], - @description("Responsible field") responsible: Option[DraftResponsible], - @description("Information about comments attached to the article") comments: Option[Seq[Comment]], - @description("If the article should be prioritized" ) prioritized: Option[Boolean], - @description("If the article should be prioritized. Possible values are prioritized, on-hold, unspecified") priority: Option[String], - @description("A combined resource type name if a standard article, otherwise the article type name") resourceTypeName: Option[String], - @description("Name of the parent topic if exists") parentTopicName: Option[String], - @description("Name of the primary context root if exists") primaryRootName: Option[String], - @description("When the article was last published") published: Option[NDLADate], - @description("Number of times favorited in MyNDLA") favorited: Option[Long], - @description("Type of the resource") resultType: SearchType, - @description("Subject ids for the resource, if a concept") conceptSubjectIds: Option[List[String]] -) -// format: on - -object MultiSearchSummary { - implicit val encoder: Encoder[MultiSearchSummary] = deriveEncoder - implicit val decoder: Decoder[MultiSearchSummary] = deriveDecoder -} diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummaryDTO.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummaryDTO.scala new file mode 100644 index 0000000000..82e702d84e --- /dev/null +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/MultiSearchSummaryDTO.scala @@ -0,0 +1,65 @@ +/* + * Part of NDLA search-api + * Copyright (C) 2018 NDLA + * + * See LICENSE + */ + +package no.ndla.searchapi.model.api + +import io.circe.{Decoder, Encoder} +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} +import no.ndla.common.model.NDLADate +import no.ndla.common.model.api.draft.CommentDTO +import no.ndla.searchapi.model.domain.LearningResourceType +import no.ndla.searchapi.model.search.SearchType +import sttp.tapir.Schema.annotations.description + +@description("Object describing matched field with matching words emphasized") +case class HighlightedFieldDTO( + @description("Field that matched") field: String, + @description("List of segments that matched in `field`") matches: Seq[String] +) + +object HighlightedFieldDTO { + implicit val encoder: Encoder[HighlightedFieldDTO] = deriveEncoder + implicit val decoder: Decoder[HighlightedFieldDTO] = deriveDecoder +} + +// format: off +@description("Short summary of information about the resource") +case class MultiSearchSummaryDTO( + @description("The unique id of the resource") id: Long, + @description("The title of the resource") title: TitleWithHtmlDTO, + @description("The meta description of the resource") metaDescription: MetaDescriptionDTO, + @description("The meta image for the resource") metaImage: Option[MetaImageDTO], + @description("Url pointing to the resource") url: String, + @description("Contexts of the resource") contexts: List[ApiTaxonomyContextDTO], + @description("Languages the resource exists in") supportedLanguages: Seq[String], + @description("Learning resource type") learningResourceType: LearningResourceType, + @description("Status information of the resource") status: Option[StatusDTO], + @description("Traits for the resource") traits: List[String], + @description("Relevance score. The higher the score, the better the document matches your search criteria.") score: Float, + @description("List of objects describing matched field with matching words emphasized") highlights: List[HighlightedFieldDTO], + @description("The taxonomy paths for the resource") paths: List[String], + @description("The time and date of last update") lastUpdated: NDLADate, + @description("Describes the license of the resource") license: Option[String], + @description("A list of revisions planned for the article") revisions: Seq[RevisionMetaDTO], + @description("Responsible field") responsible: Option[DraftResponsibleDTO], + @description("Information about comments attached to the article") comments: Option[Seq[CommentDTO]], + @description("If the article should be prioritized" ) prioritized: Option[Boolean], + @description("If the article should be prioritized. Possible values are prioritized, on-hold, unspecified") priority: Option[String], + @description("A combined resource type name if a standard article, otherwise the article type name") resourceTypeName: Option[String], + @description("Name of the parent topic if exists") parentTopicName: Option[String], + @description("Name of the primary context root if exists") primaryRootName: Option[String], + @description("When the article was last published") published: Option[NDLADate], + @description("Number of times favorited in MyNDLA") favorited: Option[Long], + @description("Type of the resource") resultType: SearchType, + @description("Subject ids for the resource, if a concept") conceptSubjectIds: Option[List[String]] +) +// format: on + +object MultiSearchSummaryDTO { + implicit val encoder: Encoder[MultiSearchSummaryDTO] = deriveEncoder + implicit val decoder: Decoder[MultiSearchSummaryDTO] = deriveDecoder +} diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMeta.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMetaDTO.scala similarity index 77% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMeta.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMetaDTO.scala index 5d1145a944..982612dd04 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMeta.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/RevisionMetaDTO.scala @@ -13,13 +13,13 @@ import no.ndla.common.model.NDLADate import sttp.tapir.Schema.annotations.description @description("Information about the editorial notes") -case class RevisionMeta( +case class RevisionMetaDTO( @description("A date on which the article would need to be revised") revisionDate: NDLADate, @description("Notes to keep track of what needs to happen before revision") note: String, @description("Status of a revision, either 'revised' or 'needs-revision'") status: String ) -object RevisionMeta { - implicit val encoder: Encoder[RevisionMeta] = deriveEncoder - implicit val decoder: Decoder[RevisionMeta] = deriveDecoder +object RevisionMetaDTO { + implicit val encoder: Encoder[RevisionMetaDTO] = deriveEncoder + implicit val decoder: Decoder[RevisionMetaDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultDTO.scala similarity index 94% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultDTO.scala index ac40543613..cd79acfd3a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultDTO.scala @@ -10,7 +10,7 @@ package no.ndla.searchapi.model.api import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class SearchResult[T]( +case class SearchResultDTO[T]( @description("The total number of articles matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResults.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultsDTO.scala similarity index 79% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResults.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultsDTO.scala index c4b656fafb..96db34db56 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResults.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/SearchResultsDTO.scala @@ -9,50 +9,44 @@ package no.ndla.searchapi.model.api import sttp.tapir.Schema.annotations.description -sealed trait SearchResults +sealed trait SearchResultsDTO @description("Search result for article api") -case class ArticleResults( +case class ArticleResultsDTO( @description("The type of search results (articles)") `type`: String, @description("The language of the search results") language: String, @description("The total number of articles matching this query") totalCount: Long, @description("The page from which results are shown from") page: Int, @description("The number of results per page") pageSize: Int, - @description("The actual search results") results: Seq[ArticleResult] -) extends SearchResults + @description("The actual search results") results: Seq[ArticleResultDTO] +) extends SearchResultsDTO @description("Search result for learningpath api") -case class LearningpathResults( +case class LearningpathResultsDTO( @description("The type of search results (learningpaths)") `type`: String, @description("The language of the search results") language: String, @description("The total number of learningpaths matching this query") totalCount: Long, @description("The page from which results are shown from") page: Int, @description("The number of results per page") pageSize: Int, - @description("The actual search results") results: Seq[LearningpathResult] -) extends SearchResults + @description("The actual search results") results: Seq[LearningpathResultDTO] +) extends SearchResultsDTO @description("Search result for image api") -case class ImageResults( +case class ImageResultsDTO( @description("The type of search results (images)") `type`: String, @description("The language of the search results") language: String, @description("The total number of images matching this query") totalCount: Long, @description("The page from which results are shown from") page: Int, @description("The number of results per page") pageSize: Int, - @description("The actual search results") results: Seq[ImageResult] -) extends SearchResults + @description("The actual search results") results: Seq[ImageResultDTO] +) extends SearchResultsDTO @description("Search result for audio api") -case class AudioResults( +case class AudioResultsDTO( @description("The type of search results (audios)") `type`: String, @description("The language of the search results") language: String, @description("The total number of audios matching this query") totalCount: Long, @description("The page from which results are shown from") page: Int, @description("The number of results per page") pageSize: Int, - @description("The actual search results") results: Seq[AudioResult] -) extends SearchResults - -@description("Description of an error when communicating with an api") -case class SearchError( - @description("The api where the error occurred") `type`: String, - @description("An error message describing the error") errorMsg: String -) extends SearchResults + @description("The actual search results") results: Seq[AudioResultDTO] +) extends SearchResultsDTO diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/Status.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/StatusDTO.scala similarity index 75% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/Status.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/StatusDTO.scala index f260b154b0..d4e67a8f39 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/Status.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/StatusDTO.scala @@ -12,12 +12,12 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Status information of the resource") -case class Status( +case class StatusDTO( @description("The current status of the resource") current: String, @description("Previous statuses this resource has been in") other: Seq[String] ) -object Status { - implicit val encoder: Encoder[Status] = deriveEncoder - implicit val decoder: Decoder[Status] = deriveDecoder +object StatusDTO { + implicit val encoder: Encoder[StatusDTO] = deriveEncoder + implicit val decoder: Decoder[StatusDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregations.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregationsDTO.scala similarity index 68% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregations.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregationsDTO.scala index b1d8c0c6a1..3f9bd289ed 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregations.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/SubjectAggregationsDTO.scala @@ -13,18 +13,18 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Result of subject aggregations") -case class SubjectAggregations( - subjects: List[SubjectAggregation] +case class SubjectAggregationsDTO( + subjects: List[SubjectAggregationDTO] ) -object SubjectAggregations { - implicit val encoder: Encoder[SubjectAggregations] = deriveEncoder - implicit val decoder: Decoder[SubjectAggregations] = deriveDecoder +object SubjectAggregationsDTO { + implicit val encoder: Encoder[SubjectAggregationsDTO] = deriveEncoder + implicit val decoder: Decoder[SubjectAggregationsDTO] = deriveDecoder } @description("Aggregations for a single subject'") -case class SubjectAggregation( +case class SubjectAggregationDTO( @description("Id of the aggregated subject") subjectId: String, @description("Number of resources in subject") @@ -39,7 +39,7 @@ case class SubjectAggregation( favoritedCount: Long ) -object SubjectAggregation { - implicit val encoder: Encoder[SubjectAggregation] = deriveEncoder - implicit val decoder: Decoder[SubjectAggregation] = deriveDecoder +object SubjectAggregationDTO { + implicit val encoder: Encoder[SubjectAggregationDTO] = deriveEncoder + implicit val decoder: Decoder[SubjectAggregationDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceType.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceTypeDTO.scala similarity index 71% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceType.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceTypeDTO.scala index 979f544108..39436bb6a3 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceType.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/TaxonomyResourceTypeDTO.scala @@ -12,13 +12,13 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import sttp.tapir.Schema.annotations.description @description("Taxonomy resource type") -case class TaxonomyResourceType( +case class TaxonomyResourceTypeDTO( @description("Id of the taoxonomy resource type") id: String, @description("Name of the taoxonomy resource type") name: String, @description("The ISO 639-1 language code for the resource type") language: String ) -object TaxonomyResourceType { - implicit val encoder: Encoder[TaxonomyResourceType] = deriveEncoder - implicit val decoder: Decoder[TaxonomyResourceType] = deriveDecoder +object TaxonomyResourceTypeDTO { + implicit val encoder: Encoder[TaxonomyResourceTypeDTO] = deriveEncoder + implicit val decoder: Decoder[TaxonomyResourceTypeDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/Title.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleDTO.scala similarity index 80% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/Title.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/TitleDTO.scala index 3da3b056c7..28734539ba 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/Title.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleDTO.scala @@ -13,7 +13,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("Title of resource") -case class Title( +case class TitleDTO( @description("The freetext title of the resource") title: String, @description("ISO 639-1 code that represents the language used in title") language: String ) extends LanguageField[String] { @@ -21,7 +21,7 @@ case class Title( override def isEmpty: Boolean = title.isEmpty } -object Title { - implicit val encoder: Encoder[Title] = deriveEncoder - implicit val decoder: Decoder[Title] = deriveDecoder +object TitleDTO { + implicit val encoder: Encoder[TitleDTO] = deriveEncoder + implicit val decoder: Decoder[TitleDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtml.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtmlDTO.scala similarity index 79% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtml.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtmlDTO.scala index e9a310babf..fe9605adfe 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtml.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/TitleWithHtmlDTO.scala @@ -13,7 +13,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("Title of resource") -case class TitleWithHtml( +case class TitleWithHtmlDTO( @description("The freetext title of the resource") title: String, @description("The freetext html-version title of the article") htmlTitle: String, @description("ISO 639-1 code that represents the language used in title") language: String @@ -22,7 +22,7 @@ case class TitleWithHtml( override def isEmpty: Boolean = title.isEmpty } -object TitleWithHtml { - implicit val encoder: Encoder[TitleWithHtml] = deriveEncoder - implicit val decoder: Decoder[TitleWithHtml] = deriveDecoder +object TitleWithHtmlDTO { + implicit val encoder: Encoder[TitleWithHtmlDTO] = deriveEncoder + implicit val decoder: Decoder[TitleWithHtmlDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroduction.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroductionDTO.scala similarity index 94% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroduction.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroductionDTO.scala index f11eea955f..368fb169ea 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroduction.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleIntroductionDTO.scala @@ -11,7 +11,7 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("Description of the article introduction") -case class ArticleIntroduction( +case class ArticleIntroductionDTO( @description("The introduction content") introduction: String, @description("The html-version introduction content") htmlIntroduction: String, @description( diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImage.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImageDTO.scala similarity index 95% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImage.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImageDTO.scala index 39f2d0dd7b..922e4c9287 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImage.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/ArticleMetaImageDTO.scala @@ -11,7 +11,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("Meta description of the article") -case class ArticleMetaImage( +case class ArticleMetaImageDTO( @description("The meta image url") url: String, @description("The alt text for the meta image") alt: String, @description( diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElement.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElementDTO.scala similarity index 95% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElement.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElementDTO.scala index a64343293e..2fc5ce5db8 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElement.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/article/VisualElementDTO.scala @@ -11,7 +11,7 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("Description of a visual element") -case class VisualElement( +case class VisualElementDTO( @description( "Html containing the visual element. May contain any legal html element, including the embed-tag" ) visualElement: String, diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResultDTO.scala similarity index 59% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResult.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResultDTO.scala index 2d11ce2a7c..53a1eb945e 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepResultDTO.scala @@ -10,16 +10,16 @@ package no.ndla.searchapi.model.api.grep import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.searchapi.model.api.Title +import no.ndla.searchapi.model.api.TitleDTO import sttp.tapir.Schema.annotations.description @description("Information about a single grep search result entry") -case class GrepResult( +case class GrepResultDTO( @description("The grep code") code: String, - @description("The greps title") title: Title + @description("The greps title") title: TitleDTO ) -object GrepResult { - implicit val encoder: Encoder[GrepResult] = deriveEncoder - implicit val decoder: Decoder[GrepResult] = deriveDecoder +object GrepResultDTO { + implicit val encoder: Encoder[GrepResultDTO] = deriveEncoder + implicit val decoder: Decoder[GrepResultDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResults.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResultsDTO.scala similarity index 69% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResults.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResultsDTO.scala index beeff98678..e25ff2be9c 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResults.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSearchResultsDTO.scala @@ -13,15 +13,15 @@ import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description @description("Information about search-results") -case class GrepSearchResults( +case class GrepSearchResultsDTO( @description("The total number of resources matching this query") totalCount: Long, @description("For which page results are shown from") page: Int, @description("The number of results per page") pageSize: Int, @description("The chosen search language") language: String, - @description("The search results") results: Seq[GrepResult] + @description("The search results") results: Seq[GrepResultDTO] ) -object GrepSearchResults { - implicit val encoder: Encoder[GrepSearchResults] = deriveEncoder - implicit val decoder: Decoder[GrepSearchResults] = deriveDecoder +object GrepSearchResultsDTO { + implicit val encoder: Encoder[GrepSearchResultsDTO] = deriveEncoder + implicit val decoder: Decoder[GrepSearchResultsDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSort.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSort.scala deleted file mode 100644 index af58421a96..0000000000 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSort.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Part of NDLA search-api - * Copyright (C) 2024 NDLA - * - * See LICENSE - * - */ - -package no.ndla.searchapi.model.api.grep - -import com.scalatsi.TypescriptType.{TSLiteralString, TSUnion} -import com.scalatsi.{TSNamedType, TSType} -import enumeratum.* -import sttp.tapir.Codec.PlainCodec -import sttp.tapir.Schema -import sttp.tapir.codec.enumeratum.* - -sealed abstract class GrepSort(override val entryName: String) extends EnumEntry -object GrepSort extends Enum[GrepSort] with CirceEnum[GrepSort] { - val values: IndexedSeq[GrepSort] = findValues - val all: Seq[String] = values.map(_.entryName) - - case object ByRelevanceDesc extends GrepSort("-relevance") - case object ByRelevanceAsc extends GrepSort("relevance") - case object ByTitleDesc extends GrepSort("-title") - case object ByTitleAsc extends GrepSort("title") - case object ByCodeDesc extends GrepSort("-code") - case object ByCodeAsc extends GrepSort("code") - - implicit val schema: Schema[GrepSort] = schemaForEnumEntry[GrepSort] - implicit val codec: PlainCodec[GrepSort] = plainCodecEnumEntry[GrepSort] - implicit val enumTsType: TSNamedType[GrepSort] = - TSType.alias[GrepSort]("GrepSort", TSUnion(all.map(s => TSLiteralString(s)))) - -} diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSortDTO.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSortDTO.scala new file mode 100644 index 0000000000..9d4ebaae4b --- /dev/null +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/grep/GrepSortDTO.scala @@ -0,0 +1,35 @@ +/* + * Part of NDLA search-api + * Copyright (C) 2024 NDLA + * + * See LICENSE + * + */ + +package no.ndla.searchapi.model.api.grep + +import com.scalatsi.TypescriptType.{TSLiteralString, TSUnion} +import com.scalatsi.{TSNamedType, TSType} +import enumeratum.* +import sttp.tapir.Codec.PlainCodec +import sttp.tapir.Schema +import sttp.tapir.codec.enumeratum.* + +sealed abstract class GrepSortDTO(override val entryName: String) extends EnumEntry +object GrepSortDTO extends Enum[GrepSortDTO] with CirceEnum[GrepSortDTO] { + val values: IndexedSeq[GrepSortDTO] = findValues + val all: Seq[String] = values.map(_.entryName) + + case object ByRelevanceDesc extends GrepSortDTO("-relevance") + case object ByRelevanceAsc extends GrepSortDTO("relevance") + case object ByTitleDesc extends GrepSortDTO("-title") + case object ByTitleAsc extends GrepSortDTO("title") + case object ByCodeDesc extends GrepSortDTO("-code") + case object ByCodeAsc extends GrepSortDTO("code") + + implicit val schema: Schema[GrepSortDTO] = schemaForEnumEntry[GrepSortDTO] + implicit val codec: PlainCodec[GrepSortDTO] = plainCodecEnumEntry[GrepSortDTO] + implicit val enumTsType: TSNamedType[GrepSortDTO] = + TSType.alias[GrepSortDTO]("GrepSort", TSUnion(all.map(s => TSLiteralString(s)))) + +} diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Copyright.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/CopyrightDTO.scala similarity index 56% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Copyright.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/CopyrightDTO.scala index 2aea20e4ca..cd923c8e3c 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Copyright.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/CopyrightDTO.scala @@ -9,16 +9,16 @@ package no.ndla.searchapi.model.api.learningpath import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} -import no.ndla.common.model.api.{Author, License} +import no.ndla.common.model.api.{AuthorDTO, LicenseDTO} import sttp.tapir.Schema.annotations.description @description("Description of copyright information") -case class Copyright( - @description("Describes the license of the learningpath") license: License, - @description("List of authors") contributors: Seq[Author] +case class CopyrightDTO( + @description("Describes the license of the learningpath") license: LicenseDTO, + @description("List of authors") contributors: Seq[AuthorDTO] ) -object Copyright { - implicit val encoder: Encoder[Copyright] = deriveEncoder - implicit val decoder: Decoder[Copyright] = deriveDecoder +object CopyrightDTO { + implicit val encoder: Encoder[CopyrightDTO] = deriveEncoder + implicit val decoder: Decoder[CopyrightDTO] = deriveDecoder } diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Description.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/DescriptionDTO.scala similarity index 95% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Description.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/DescriptionDTO.scala index 5c38189d5b..892c59264d 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Description.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/DescriptionDTO.scala @@ -11,7 +11,7 @@ import no.ndla.language.model.LanguageField import sttp.tapir.Schema.annotations.description @description("The description of the learningpath") -case class Description( +case class DescriptionDTO( @description("The description to the learningpath.") description: String, @description("ISO 639-1 code that represents the language used in introduction") language: String ) extends LanguageField[String] { diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Introduction.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/IntroductionDTO.scala similarity index 94% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Introduction.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/IntroductionDTO.scala index 383d0d707f..8e2156c7e7 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/Introduction.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/IntroductionDTO.scala @@ -11,7 +11,7 @@ import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description @description("The introduction of the learningpath") -case class Introduction( +case class IntroductionDTO( @description("The introduction to the learningpath. Basic HTML allowed") introduction: String, @description("ISO 639-1 code that represents the language used in introduction") language: String ) extends WithLanguage diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTags.scala b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTagsDTO.scala similarity index 92% rename from search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTags.scala rename to search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTagsDTO.scala index 89bdf3c1c9..9dac52cab2 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTags.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/api/learningpath/LearningPathTagsDTO.scala @@ -10,7 +10,7 @@ package no.ndla.searchapi.model.api.learningpath import no.ndla.language.model.WithLanguage import sttp.tapir.Schema.annotations.description -case class LearningPathTags( +case class LearningPathTagsDTO( @description("The searchable tags. Must be plain text") tags: Seq[String], @description("ISO 639-1 code that represents the language used in tag") language: String ) extends WithLanguage diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/domain/IndexingBundle.scala b/search-api/src/main/scala/no/ndla/searchapi/model/domain/IndexingBundle.scala index 0e5988f80b..9d4b82a02a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/domain/IndexingBundle.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/domain/IndexingBundle.scala @@ -7,7 +7,7 @@ package no.ndla.searchapi.model.domain -import no.ndla.common.model.api.MyNDLABundle +import no.ndla.common.model.api.MyNDLABundleDTO import no.ndla.searchapi.model.grep.GrepBundle import no.ndla.searchapi.model.taxonomy.TaxonomyBundle @@ -15,5 +15,5 @@ import no.ndla.searchapi.model.taxonomy.TaxonomyBundle case class IndexingBundle( grepBundle: Option[GrepBundle], taxonomyBundle: Option[TaxonomyBundle], - myndlaBundle: Option[MyNDLABundle] + myndlaBundle: Option[MyNDLABundleDTO] ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/domain/SearchResult.scala b/search-api/src/main/scala/no/ndla/searchapi/model/domain/SearchResult.scala index 36bc25ffe1..2f8e0d4e21 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/domain/SearchResult.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/domain/SearchResult.scala @@ -7,15 +7,15 @@ package no.ndla.searchapi.model.domain import no.ndla.search.model.domain.TermAggregation -import no.ndla.searchapi.model.api.{MultiSearchSuggestion, MultiSearchSummary} +import no.ndla.searchapi.model.api.{MultiSearchSuggestionDTO, MultiSearchSummaryDTO} case class SearchResult( totalCount: Long, page: Option[Int], pageSize: Int, language: String, - results: Seq[MultiSearchSummary], - suggestions: Seq[MultiSearchSuggestion], + results: Seq[MultiSearchSummaryDTO], + suggestions: Seq[MultiSearchSuggestionDTO], aggregations: Seq[TermAggregation], scrollId: Option[String] = None ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableConcept.scala b/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableConcept.scala index 224ac96bd7..74562e69b2 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableConcept.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableConcept.scala @@ -13,7 +13,7 @@ import no.ndla.common.model.NDLADate import no.ndla.common.model.domain.Responsible import no.ndla.common.model.domain.concept.{Concept, ConceptMetaImage} import no.ndla.search.model.{SearchableLanguageList, SearchableLanguageValues} -import no.ndla.searchapi.model.api.Status +import no.ndla.searchapi.model.api.StatusDTO import no.ndla.searchapi.model.domain.LearningResourceType case class SearchableConcept( @@ -26,7 +26,7 @@ case class SearchableConcept( tags: SearchableLanguageList, subjectIds: List[String], lastUpdated: NDLADate, - draftStatus: Status, + draftStatus: StatusDTO, users: List[String], updatedBy: Seq[String], license: Option[String], diff --git a/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableLearningPath.scala b/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableLearningPath.scala index e29512f209..449f0da782 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableLearningPath.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/model/search/SearchableLearningPath.scala @@ -11,7 +11,7 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import no.ndla.common.model.NDLADate import no.ndla.search.model.{SearchableLanguageList, SearchableLanguageValues} -import no.ndla.searchapi.model.api.learningpath.Copyright +import no.ndla.searchapi.model.api.learningpath.CopyrightDTO import no.ndla.searchapi.model.domain.LearningResourceType case class SearchableLearningPath( @@ -28,7 +28,7 @@ case class SearchableLearningPath( tags: SearchableLanguageList, learningsteps: List[SearchableLearningStep], license: String, - copyright: Copyright, + copyright: CopyrightDTO, isBasedOn: Option[Long], supportedLanguages: List[String], authors: List[String], diff --git a/search-api/src/main/scala/no/ndla/searchapi/service/ConverterService.scala b/search-api/src/main/scala/no/ndla/searchapi/service/ConverterService.scala index 1bff81baae..cd7cb45c36 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/service/ConverterService.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/service/ConverterService.scala @@ -11,8 +11,8 @@ import io.lemonlabs.uri.typesafe.dsl.* import no.ndla.network.ApplicationUrl import no.ndla.searchapi.Props import no.ndla.searchapi.model.api -import no.ndla.searchapi.model.api.LearningPathIntroduction -import no.ndla.searchapi.model.api.article.ArticleIntroduction +import no.ndla.searchapi.model.api.LearningPathIntroductionDTO +import no.ndla.searchapi.model.api.article.ArticleIntroductionDTO import no.ndla.searchapi.model.domain.* trait ConverterService { @@ -22,7 +22,7 @@ trait ConverterService { class ConverterService { import props.Domain - def searchResultToApiModel(searchResults: ApiSearchResults): api.SearchResults = { + def searchResultToApiModel(searchResults: ApiSearchResults): api.SearchResultsDTO = { searchResults match { case a: ArticleApiSearchResults => articleSearchResultsToApi(a) case l: LearningpathApiSearchResults => learningpathSearchResultsToApi(l) @@ -31,8 +31,8 @@ trait ConverterService { } } - private def articleSearchResultsToApi(articles: ArticleApiSearchResults): api.ArticleResults = { - api.ArticleResults( + private def articleSearchResultsToApi(articles: ArticleApiSearchResults): api.ArticleResultsDTO = { + api.ArticleResultsDTO( "articles", articles.language, articles.totalCount, @@ -42,18 +42,20 @@ trait ConverterService { ) } - private def articleSearchResultToApi(article: ArticleApiSearchResult): api.ArticleResult = { - api.ArticleResult( + private def articleSearchResultToApi(article: ArticleApiSearchResult): api.ArticleResultDTO = { + api.ArticleResultDTO( article.id, - api.TitleWithHtml(article.title.title, article.title.htmlTitle, article.title.language), - article.introduction.map(i => ArticleIntroduction(i.introduction, i.htmlIntroduction, i.language)), + api.TitleWithHtmlDTO(article.title.title, article.title.htmlTitle, article.title.language), + article.introduction.map(i => ArticleIntroductionDTO(i.introduction, i.htmlIntroduction, i.language)), article.articleType, article.supportedLanguages ) } - private def learningpathSearchResultsToApi(learningpaths: LearningpathApiSearchResults): api.LearningpathResults = { - api.LearningpathResults( + private def learningpathSearchResultsToApi( + learningpaths: LearningpathApiSearchResults + ): api.LearningpathResultsDTO = { + api.LearningpathResultsDTO( "learningpaths", learningpaths.language, learningpaths.totalCount, @@ -63,17 +65,17 @@ trait ConverterService { ) } - private def learningpathSearchResultToApi(learningpath: LearningpathApiSearchResult): api.LearningpathResult = { - api.LearningpathResult( + private def learningpathSearchResultToApi(learningpath: LearningpathApiSearchResult): api.LearningpathResultDTO = { + api.LearningpathResultDTO( learningpath.id, - api.Title(learningpath.title.title, learningpath.title.language), - LearningPathIntroduction(learningpath.introduction.introduction, learningpath.introduction.language), + api.TitleDTO(learningpath.title.title, learningpath.title.language), + LearningPathIntroductionDTO(learningpath.introduction.introduction, learningpath.introduction.language), learningpath.supportedLanguages ) } - private def imageSearchResultsToApi(images: ImageApiSearchResults): api.ImageResults = { - api.ImageResults( + private def imageSearchResultsToApi(images: ImageApiSearchResults): api.ImageResultsDTO = { + api.ImageResultsDTO( "images", images.language, images.totalCount, @@ -83,25 +85,25 @@ trait ConverterService { ) } - private def imageSearchResultToApi(image: ImageApiSearchResult): api.ImageResult = { + private def imageSearchResultToApi(image: ImageApiSearchResult): api.ImageResultDTO = { val scheme = ApplicationUrl.get.schemeOption.getOrElse("https://") val host = ApplicationUrl.get.hostOption.map(_.toString).getOrElse(Domain) val previewUrl = image.previewUrl.withHost(host).withScheme(scheme) val metaUrl = image.metaUrl.withHost(host).withScheme(scheme) - api.ImageResult( + api.ImageResultDTO( image.id.toLong, - api.Title(image.title.title, image.title.language), - api.ImageAltText(image.altText.alttext, image.altText.language), + api.TitleDTO(image.title.title, image.title.language), + api.ImageAltTextDTO(image.altText.alttext, image.altText.language), previewUrl.toString, metaUrl.toString, image.supportedLanguages ) } - private def audioSearchResultsToApi(audios: AudioApiSearchResults): api.AudioResults = { - api.AudioResults( + private def audioSearchResultsToApi(audios: AudioApiSearchResults): api.AudioResultsDTO = { + api.AudioResultsDTO( "audios", audios.language, audios.totalCount, @@ -111,14 +113,14 @@ trait ConverterService { ) } - private def audioSearchResultToApi(audio: AudioApiSearchResult): api.AudioResult = { + private def audioSearchResultToApi(audio: AudioApiSearchResult): api.AudioResultDTO = { val scheme = ApplicationUrl.get.schemeOption.getOrElse("https://") val host = ApplicationUrl.get.hostOption.map(_.toString).getOrElse(Domain) val url = audio.url.withHost(host).withScheme(scheme).toString - api.AudioResult( + api.AudioResultDTO( audio.id, - api.Title(audio.title.title, audio.title.language), + api.TitleDTO(audio.title.title, audio.title.language), url, audio.supportedLanguages ) diff --git a/search-api/src/main/scala/no/ndla/searchapi/service/search/GrepSearchService.scala b/search-api/src/main/scala/no/ndla/searchapi/service/search/GrepSearchService.scala index 9db8d8629f..71302f802a 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/service/search/GrepSearchService.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/service/search/GrepSearchService.scala @@ -23,10 +23,10 @@ import no.ndla.language.model.Iso639 import no.ndla.search.model.LanguageValue import no.ndla.search.{BaseIndexService, Elastic4sClient} import no.ndla.searchapi.Props -import no.ndla.searchapi.controller.parameters.GrepSearchInput -import no.ndla.searchapi.model.api.Title -import no.ndla.searchapi.model.api.grep.GrepSort.* -import no.ndla.searchapi.model.api.grep.{GrepResult, GrepSearchResults, GrepSort} +import no.ndla.searchapi.controller.parameters.GrepSearchInputDTO +import no.ndla.searchapi.model.api.TitleDTO +import no.ndla.searchapi.model.api.grep.GrepSortDTO.* +import no.ndla.searchapi.model.api.grep.{GrepResultDTO, GrepSearchResultsDTO, GrepSortDTO} import no.ndla.searchapi.model.search.{SearchType, SearchableGrepElement} import scala.util.{Success, Try} @@ -40,7 +40,7 @@ trait GrepSearchService { override val searchIndex: List[String] = List(SearchType.Grep).map(SearchIndex) override val indexServices: List[BaseIndexService] = List(grepIndexService) - def grepSortDefinition(maybeSort: Option[GrepSort], language: String): FieldSort = maybeSort match { + def grepSortDefinition(maybeSort: Option[GrepSortDTO], language: String): FieldSort = maybeSort match { case Some(ByRelevanceAsc) => sortField("_score", Asc, missingLast = false) case Some(ByRelevanceDesc) | None => sortField("_score", Desc, missingLast = false) case Some(ByTitleAsc) => defaultSort("defaultTitle", "title", Asc, language) @@ -49,7 +49,7 @@ trait GrepSearchService { case Some(ByCodeDesc) => sortField("code", Desc, missingLast = false) } - protected def buildQuery(input: GrepSearchInput, searchLanguage: String): Query = { + protected def buildQuery(input: GrepSearchInputDTO, searchLanguage: String): Query = { val query = input.query .map { q => val langQueryFunc = (fieldName: String, boost: Double) => @@ -80,18 +80,18 @@ trait GrepSearchService { query.filter(getFilters(input)) } - private def getFilters(input: GrepSearchInput): List[Query] = + private def getFilters(input: GrepSearchInputDTO): List[Query] = List( idsFilter(input), prefixFilter(input) ).flatten - private def idsFilter(input: GrepSearchInput): Option[Query] = input.codes match { + private def idsFilter(input: GrepSearchInputDTO): Option[Query] = input.codes match { case Some(ids) if ids.nonEmpty => termsQuery("code", ids).some case _ => None } - private def prefixFilter(input: GrepSearchInput): Option[Query] = input.prefixFilter match { + private def prefixFilter(input: GrepSearchInputDTO): Option[Query] = input.prefixFilter match { case Some(prefixes) if prefixes.nonEmpty => Some( boolQuery().should( @@ -101,7 +101,7 @@ trait GrepSearchService { case _ => None } - def searchGreps(input: GrepSearchInput): Try[GrepSearchResults] = { + def searchGreps(input: GrepSearchInputDTO): Try[GrepSearchResultsDTO] = { val searchLanguage = input.language match { case Some(lang) if Iso639.get(lang).isSuccess => lang case _ => AllLanguages @@ -122,7 +122,7 @@ trait GrepSearchService { e4sClient.execute(searchToExecute).flatMap { response => getGrepHits(response, searchLanguage).map { results => - GrepSearchResults( + GrepSearchResultsDTO( totalCount = response.result.totalHits, page = pagination.page, pageSize = searchPageSize, @@ -133,22 +133,22 @@ trait GrepSearchService { } } - def hitToResult(hit: SearchHit, language: String): Try[GrepResult] = { + def hitToResult(hit: SearchHit, language: String): Try[GrepResultDTO] = { val jsonString = hit.sourceAsString val searchable = CirceUtil.tryParseAs[SearchableGrepElement](jsonString).? val titleLv = findByLanguageOrBestEffort(searchable.title.languageValues, language) .getOrElse(LanguageValue(Language.DefaultLanguage, "")) - val title = Title(title = titleLv.value, language = titleLv.language) + val title = TitleDTO(title = titleLv.value, language = titleLv.language) Success( - GrepResult( + GrepResultDTO( code = searchable.code, title = title ) ) } - def getGrepHits(response: RequestSuccess[SearchResponse], language: String): Try[List[GrepResult]] = { + def getGrepHits(response: RequestSuccess[SearchResponse], language: String): Try[List[GrepResultDTO]] = { response.result.hits.hits.toList.traverse { hit => hitToResult(hit, language) } } } diff --git a/search-api/src/main/scala/no/ndla/searchapi/service/search/MultiDraftSearchService.scala b/search-api/src/main/scala/no/ndla/searchapi/service/search/MultiDraftSearchService.scala index 31689a9a93..a500ee18eb 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/service/search/MultiDraftSearchService.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/service/search/MultiDraftSearchService.scala @@ -23,7 +23,7 @@ import no.ndla.language.model.Iso639 import no.ndla.search.AggregationBuilder.{buildTermsAggregation, getAggregationsFromResult} import no.ndla.search.Elastic4sClient import no.ndla.searchapi.Props -import no.ndla.searchapi.model.api.{ErrorHandling, SubjectAggregation, SubjectAggregations} +import no.ndla.searchapi.model.api.{ErrorHandling, SubjectAggregationDTO, SubjectAggregationsDTO} import no.ndla.searchapi.model.domain.{LearningResourceType, SearchResult} import no.ndla.searchapi.model.search.SearchType import no.ndla.searchapi.model.search.settings.MultiDraftSearchSettings @@ -69,12 +69,12 @@ trait MultiDraftSearchService { } } - def aggregateSubjects(subjects: List[String]): Try[SubjectAggregations] = { + def aggregateSubjects(subjects: List[String]): Try[SubjectAggregationsDTO] = { val fiveYearsAgo = NDLADate.now().minusYears(5) val inOneYear = NDLADate.now().plusYears(1) val flowExcludeStatuses = List(DraftStatus.ARCHIVED, DraftStatus.PUBLISHED, DraftStatus.UNPUBLISHED) val flowStatuses = DraftStatus.values.filterNot(s => flowExcludeStatuses.contains(s)).toList - def aggregateSubject(subjectId: String): Try[SubjectAggregation] = for { + def aggregateSubject(subjectId: String): Try[SubjectAggregationDTO] = for { old <- filteredCountSearch( MultiDraftSearchSettings.default.copy( subjects = List(subjectId), @@ -100,7 +100,7 @@ trait MultiDraftSearchService { ) ) favorited <- aggregateFavorites(subjectId) - } yield SubjectAggregation( + } yield SubjectAggregationDTO( subjectId = subjectId, publishedArticleCount = publishedArticles, oldArticleCount = old, @@ -111,7 +111,7 @@ trait MultiDraftSearchService { subjects .traverse(subjectId => aggregateSubject(subjectId)) - .map(aggregations => SubjectAggregations(aggregations)) + .map(aggregations => SubjectAggregationsDTO(aggregations)) } private def getSearchIndexes(settings: MultiDraftSearchSettings): Try[List[String]] = { diff --git a/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchConverterService.scala b/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchConverterService.scala index bfe0453a8c..1911a4f80f 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchConverterService.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchConverterService.scala @@ -13,8 +13,8 @@ import com.typesafe.scalalogging.StrictLogging import no.ndla.common.CirceUtil import no.ndla.common.configuration.Constants.EmbedTagName import no.ndla.common.implicits.* -import no.ndla.common.model.api.draft.Comment -import no.ndla.common.model.api.{Author, License} +import no.ndla.common.model.api.draft.CommentDTO +import no.ndla.common.model.api.{AuthorDTO, LicenseDTO} import no.ndla.common.model.domain.article.Article import no.ndla.common.model.domain.concept.Concept import no.ndla.common.model.domain.draft.{Draft, RevisionStatus} @@ -290,9 +290,9 @@ trait SearchConverterService { val supportedLanguages = getSupportedLanguages(lp.title, lp.description).toList val defaultTitle = lp.title.sortBy(title => ISO639.languagePriority.reverse.indexOf(title.language)).lastOption - val license = api.learningpath.Copyright( + val license = api.learningpath.CopyrightDTO( asLearningPathApiLicense(lp.copyright.license), - lp.copyright.contributors.map(c => Author(c.`type`, c.name)) + lp.copyright.contributors.map(c => AuthorDTO(c.`type`, c.name)) ) Success( @@ -352,7 +352,7 @@ trait SearchConverterService { val users: Seq[String] = c.updatedBy ++ c.editorNotes.map(_.user) - val status = Status(c.status.current.toString, c.status.other.map(_.toString).toSeq) + val status = StatusDTO(c.status.current.toString, c.status.other.map(_.toString).toSeq) Success( SearchableConcept( @@ -547,10 +547,10 @@ trait SearchConverterService { } } - private def asLearningPathApiLicense(license: String): License = { + private def asLearningPathApiLicense(license: String): LicenseDTO = { getLicense(license) match { - case Some(l) => License(l.license.toString, Option(l.description), l.url) - case None => License(license, Some("Invalid license"), None) + case Some(l) => LicenseDTO(l.license.toString, Option(l.description), l.url) + case None => LicenseDTO(license, Some("Invalid license"), None) } } @@ -588,9 +588,9 @@ trait SearchConverterService { } } - private def getHighlights(highlights: Map[String, Seq[String]]): List[HighlightedField] = { + private def getHighlights(highlights: Map[String, Seq[String]]): List[HighlightedFieldDTO] = { highlights.map { case (field, matches) => - HighlightedField( + HighlightedFieldDTO( field = field, matches = matches ) @@ -605,39 +605,39 @@ trait SearchConverterService { contexts: List[SearchableTaxonomyContext], language: String, filterInactive: Boolean - ): List[ApiTaxonomyContext] = { + ): List[ApiTaxonomyContextDTO] = { val filtered = if (filterInactive) contexts.filter(c => c.isActive) else contexts filtered.sortBy(!_.isPrimary).map(c => searchableContextToApiContext(c, language)) } - def articleHitAsMultiSummary(hit: SearchHit, language: String, filterInactive: Boolean): MultiSearchSummary = { + def articleHitAsMultiSummary(hit: SearchHit, language: String, filterInactive: Boolean): MultiSearchSummaryDTO = { val searchableArticle = CirceUtil.unsafeParseAs[SearchableArticle](hit.sourceAsString) val contexts = filterContexts(searchableArticle.contexts, language, filterInactive) val titles = searchableArticle.domainObject.title.map(title => - api.TitleWithHtml(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) + api.TitleWithHtmlDTO(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) ) val introductions = searchableArticle.domainObject.introduction.map(intro => api.article - .ArticleIntroduction( + .ArticleIntroductionDTO( Jsoup.parseBodyFragment(intro.introduction).body().text(), intro.introduction, intro.language ) ) val metaDescriptions = - searchableArticle.metaDescription.languageValues.map(lv => api.MetaDescription(lv.value, lv.language)) + searchableArticle.metaDescription.languageValues.map(lv => api.MetaDescriptionDTO(lv.value, lv.language)) val visualElements = - searchableArticle.visualElement.languageValues.map(lv => api.article.VisualElement(lv.value, lv.language)) + searchableArticle.visualElement.languageValues.map(lv => api.article.VisualElementDTO(lv.value, lv.language)) val metaImages = searchableArticle.metaImage.map(image => { val metaImageUrl = s"${props.ExternalApiUrls("raw-image")}/${image.imageId}" - api.MetaImage(metaImageUrl, image.altText, image.language) + api.MetaImageDTO(metaImageUrl, image.altText, image.language) }) val title = - findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtml("", "", UnknownLanguage.toString)) + findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtmlDTO("", "", UnknownLanguage.toString)) val metaDescription = findByLanguageOrBestEffort(metaDescriptions, language).getOrElse( - api.MetaDescription("", UnknownLanguage.toString) + api.MetaDescriptionDTO("", UnknownLanguage.toString) ) val metaImage = findByLanguageOrBestEffort(metaImages, language) @@ -645,7 +645,7 @@ trait SearchConverterService { val url = s"${props.ExternalApiUrls("article-api")}/${searchableArticle.id}" - MultiSearchSummary( + MultiSearchSummaryDTO( id = searchableArticle.id, title = title, metaDescription = metaDescription, @@ -676,51 +676,51 @@ trait SearchConverterService { ) } - def draftHitAsMultiSummary(hit: SearchHit, language: String, filterInactive: Boolean): MultiSearchSummary = { + def draftHitAsMultiSummary(hit: SearchHit, language: String, filterInactive: Boolean): MultiSearchSummaryDTO = { val searchableDraft = CirceUtil.unsafeParseAs[SearchableDraft](hit.sourceAsString) val contexts = filterContexts(searchableDraft.contexts, language, filterInactive) val titles = searchableDraft.domainObject.title.map(title => - api.TitleWithHtml(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) + api.TitleWithHtmlDTO(Jsoup.parseBodyFragment(title.title).body().text(), title.title, title.language) ) val introductions = searchableDraft.domainObject.introduction.map(intro => api.article - .ArticleIntroduction( + .ArticleIntroductionDTO( Jsoup.parseBodyFragment(intro.introduction).body().text(), intro.introduction, intro.language ) ) val metaDescriptions = - searchableDraft.metaDescription.languageValues.map(lv => api.MetaDescription(lv.value, lv.language)) + searchableDraft.metaDescription.languageValues.map(lv => api.MetaDescriptionDTO(lv.value, lv.language)) val visualElements = - searchableDraft.visualElement.languageValues.map(lv => api.article.VisualElement(lv.value, lv.language)) + searchableDraft.visualElement.languageValues.map(lv => api.article.VisualElementDTO(lv.value, lv.language)) val metaImages = searchableDraft.domainObject.metaImage.map(image => { val metaImageUrl = s"${props.ExternalApiUrls("raw-image")}/${image.imageId}" - api.MetaImage(metaImageUrl, image.altText, image.language) + api.MetaImageDTO(metaImageUrl, image.altText, image.language) }) val title = - findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtml("", "", UnknownLanguage.toString)) + findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtmlDTO("", "", UnknownLanguage.toString)) val metaDescription = findByLanguageOrBestEffort(metaDescriptions, language).getOrElse( - api.MetaDescription("", UnknownLanguage.toString) + api.MetaDescriptionDTO("", UnknownLanguage.toString) ) val metaImage = findByLanguageOrBestEffort(metaImages, language) val supportedLanguages = getSupportedLanguages(titles, visualElements, introductions, metaDescriptions) val url = s"${props.ExternalApiUrls("draft-api")}/${searchableDraft.id}" val revisions = - searchableDraft.revisionMeta.map(m => api.RevisionMeta(m.revisionDate, m.note, m.status.entryName)) - val responsible = searchableDraft.responsible.map(r => api.DraftResponsible(r.responsibleId, r.lastUpdated)) + searchableDraft.revisionMeta.map(m => api.RevisionMetaDTO(m.revisionDate, m.note, m.status.entryName)) + val responsible = searchableDraft.responsible.map(r => api.DraftResponsibleDTO(r.responsibleId, r.lastUpdated)) val comments = searchableDraft.domainObject.comments.map(c => - Comment(c.id.toString, c.content, c.created, c.updated, c.isOpen, c.solved) + CommentDTO(c.id.toString, c.content, c.created, c.updated, c.isOpen, c.solved) ) val resourceTypeName = searchableDraft.resourceTypeName.getLanguageOrDefault(language) val parentTopicName = searchableDraft.parentTopicName.getLanguageOrDefault(language) val primaryRootName = searchableDraft.primaryRoot.getLanguageOrDefault(language) - MultiSearchSummary( + MultiSearchSummaryDTO( id = searchableDraft.id, title = title, metaDescription = metaDescription, @@ -729,7 +729,7 @@ trait SearchConverterService { contexts = contexts, supportedLanguages = supportedLanguages, learningResourceType = searchableDraft.learningResourceType, - status = Some(api.Status(searchableDraft.draftStatus.current, searchableDraft.draftStatus.other)), + status = Some(api.StatusDTO(searchableDraft.draftStatus.current, searchableDraft.draftStatus.other)), traits = searchableDraft.traits, score = hit.score, highlights = getHighlights(hit.highlight), @@ -751,35 +751,41 @@ trait SearchConverterService { ) } - def learningpathHitAsMultiSummary(hit: SearchHit, language: String, filterInactive: Boolean): MultiSearchSummary = { + def learningpathHitAsMultiSummary( + hit: SearchHit, + language: String, + filterInactive: Boolean + ): MultiSearchSummaryDTO = { val searchableLearningPath = CirceUtil.unsafeParseAs[SearchableLearningPath](hit.sourceAsString) val contexts = filterContexts(searchableLearningPath.contexts, language, filterInactive) val titles = - searchableLearningPath.title.languageValues.map(lv => api.TitleWithHtml(lv.value, lv.value, lv.language)) + searchableLearningPath.title.languageValues.map(lv => api.TitleWithHtmlDTO(lv.value, lv.value, lv.language)) val metaDescriptions = - searchableLearningPath.description.languageValues.map(lv => api.MetaDescription(lv.value, lv.language)) + searchableLearningPath.description.languageValues.map(lv => api.MetaDescriptionDTO(lv.value, lv.language)) val tags = - searchableLearningPath.tags.languageValues.map(lv => api.learningpath.LearningPathTags(lv.value, lv.language)) + searchableLearningPath.tags.languageValues.map(lv => + api.learningpath.LearningPathTagsDTO(lv.value, lv.language) + ) val supportedLanguages = getSupportedLanguages(titles, metaDescriptions, tags) val title = - findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtml("", "", UnknownLanguage.toString)) + findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtmlDTO("", "", UnknownLanguage.toString)) val metaDescription = findByLanguageOrBestEffort(metaDescriptions, language).getOrElse( - api.MetaDescription("", UnknownLanguage.toString) + api.MetaDescriptionDTO("", UnknownLanguage.toString) ) val url = s"${props.ExternalApiUrls("learningpath-api")}/${searchableLearningPath.id}" val metaImage = searchableLearningPath.coverPhotoId.map(id => - api.MetaImage( + api.MetaImageDTO( url = s"${props.ExternalApiUrls("raw-image")}/$id", alt = "", language = language ) ) - MultiSearchSummary( + MultiSearchSummaryDTO( id = searchableLearningPath.id, title = title, metaDescription = metaDescription, @@ -788,7 +794,7 @@ trait SearchConverterService { contexts = contexts, supportedLanguages = supportedLanguages, learningResourceType = LearningResourceType.LearningPath, - status = Some(api.Status(searchableLearningPath.status, Seq.empty)), + status = Some(api.StatusDTO(searchableLearningPath.status, Seq.empty)), traits = List.empty, score = hit.score, highlights = getHighlights(hit.highlight), @@ -810,31 +816,32 @@ trait SearchConverterService { ) } - def conceptHitAsMultiSummary(hit: SearchHit, language: String): MultiSearchSummary = { + def conceptHitAsMultiSummary(hit: SearchHit, language: String): MultiSearchSummaryDTO = { val searchableConcept = CirceUtil.unsafeParseAs[SearchableConcept](hit.sourceAsString) - val titles = searchableConcept.title.languageValues.map(lv => api.TitleWithHtml(lv.value, lv.value, lv.language)) + val titles = + searchableConcept.title.languageValues.map(lv => api.TitleWithHtmlDTO(lv.value, lv.value, lv.language)) - val content = searchableConcept.content.languageValues.map(lv => api.MetaDescription(lv.value, lv.language)) + val content = searchableConcept.content.languageValues.map(lv => api.MetaDescriptionDTO(lv.value, lv.language)) val tags = searchableConcept.tags.languageValues.map(lv => Tag(lv.value, lv.language)) val supportedLanguages = getSupportedLanguages(titles, content, tags) val title = - findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtml("", "", UnknownLanguage.toString)) + findByLanguageOrBestEffort(titles, language).getOrElse(api.TitleWithHtmlDTO("", "", UnknownLanguage.toString)) val url = s"${props.ExternalApiUrls("concept-api")}/${searchableConcept.id}" val metaImages = searchableConcept.domainObject.metaImage.map(image => { val metaImageUrl = s"${props.ExternalApiUrls("raw-image")}/${image.imageId}" - api.MetaImage(metaImageUrl, image.altText, image.language) + api.MetaImageDTO(metaImageUrl, image.altText, image.language) }) val metaImage = findByLanguageOrBestEffort(metaImages, language) - val responsible = searchableConcept.responsible.map(r => api.DraftResponsible(r.responsibleId, r.lastUpdated)) + val responsible = searchableConcept.responsible.map(r => api.DraftResponsibleDTO(r.responsibleId, r.lastUpdated)) val metaDescription = findByLanguageOrBestEffort(content, language).getOrElse( - api.MetaDescription("", UnknownLanguage.toString) + api.MetaDescriptionDTO("", UnknownLanguage.toString) ) - MultiSearchSummary( + MultiSearchSummaryDTO( id = searchableConcept.id, title = title, metaDescription = metaDescription, @@ -868,7 +875,7 @@ trait SearchConverterService { private def searchableContextToApiContext( context: SearchableTaxonomyContext, language: String - ): ApiTaxonomyContext = { + ): ApiTaxonomyContextDTO = { val subjectName = findByLanguageOrBestEffort(context.root.languageValues, language).map(_.value).getOrElse("") val breadcrumbs = findByLanguageOrBestEffort(context.breadcrumbs.languageValues, language) .map(_.value) @@ -878,12 +885,12 @@ trait SearchConverterService { val resourceTypes = context.resourceTypes.map(rt => { val name = findByLanguageOrBestEffort(rt.name.languageValues, language) .getOrElse(LanguageValue(UnknownLanguage.toString, "")) - TaxonomyResourceType(id = rt.id, name = name.value, language = name.language) + TaxonomyResourceTypeDTO(id = rt.id, name = name.value, language = name.language) }) val relevance = findByLanguageOrBestEffort(context.relevance.languageValues, language).map(_.value).getOrElse("") - ApiTaxonomyContext( + ApiTaxonomyContextDTO( publicId = context.publicId, root = subjectName, rootId = context.rootId, @@ -959,8 +966,8 @@ trait SearchConverterService { } } - def toApiMultiSearchResult(searchResult: domain.SearchResult): MultiSearchResult = - api.MultiSearchResult( + def toApiMultiSearchResult(searchResult: domain.SearchResult): MultiSearchResultDTO = + api.MultiSearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, @@ -970,8 +977,8 @@ trait SearchConverterService { searchResult.aggregations.map(toApiMultiTermsAggregation) ) - def toApiGroupMultiSearchResult(group: String, searchResult: domain.SearchResult): GroupSearchResult = - api.GroupSearchResult( + def toApiGroupMultiSearchResult(group: String, searchResult: domain.SearchResult): GroupSearchResultDTO = + api.GroupSearchResultDTO( searchResult.totalCount, searchResult.page, searchResult.pageSize, diff --git a/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchService.scala b/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchService.scala index e78e1381a5..23e099bc67 100644 --- a/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchService.scala +++ b/search-api/src/main/scala/no/ndla/searchapi/service/search/SearchService.scala @@ -25,10 +25,10 @@ import no.ndla.search.{BaseIndexService, Elastic4sClient, NdlaSearchException, S import no.ndla.searchapi.Props import no.ndla.searchapi.model.api.{ ErrorHandling, - MultiSearchSuggestion, - MultiSearchSummary, - SearchSuggestion, - SuggestOption + MultiSearchSuggestionDTO, + MultiSearchSummaryDTO, + SearchSuggestionDTO, + SuggestOptionDTO } import no.ndla.searchapi.model.domain.Sort.* import no.ndla.searchapi.model.domain.* @@ -55,7 +55,7 @@ trait SearchService { * @return * api-model summary of hit */ - private def hitToApiModel(hit: SearchHit, language: String, filterInactive: Boolean): Try[MultiSearchSummary] = { + private def hitToApiModel(hit: SearchHit, language: String, filterInactive: Boolean): Try[MultiSearchSummaryDTO] = { val indexName = hit.index.split("_").headOption.traverse(x => props.indexToSearchType(x)) indexName.flatMap { case Some(SearchType.Articles) => @@ -143,7 +143,7 @@ trait SearchService { response: SearchResponse, language: String, filterInactive: Boolean - ): Try[Seq[MultiSearchSummary]] = { + ): Try[Seq[MultiSearchSummaryDTO]] = { response.totalHits match { case count if count > 0 => val resultArray = response.hits.hits.toList @@ -181,15 +181,15 @@ trait SearchService { .text(query) } - protected def getSuggestions(response: SearchResponse): Seq[MultiSearchSuggestion] = { + protected def getSuggestions(response: SearchResponse): Seq[MultiSearchSuggestionDTO] = { response.suggestions.map { case (key, value) => - MultiSearchSuggestion(name = key, suggestions = getSuggestion(value)) + MultiSearchSuggestionDTO(name = key, suggestions = getSuggestion(value)) }.toSeq } - private def getSuggestion(results: Seq[SuggestionResult]): Seq[SearchSuggestion] = { + private def getSuggestion(results: Seq[SuggestionResult]): Seq[SearchSuggestionDTO] = { results.map(result => - SearchSuggestion( + SearchSuggestionDTO( text = result.text, offset = result.offset, length = result.length, @@ -198,10 +198,10 @@ trait SearchService { ) } - private def mapToSuggestOption(optionsMap: Map[String, Any]): SuggestOption = { + private def mapToSuggestOption(optionsMap: Map[String, Any]): SuggestOptionDTO = { val text = optionsMap.getOrElse("text", "") val score = optionsMap.getOrElse("score", 1) - SuggestOption( + SuggestOptionDTO( text.asInstanceOf[String], score.asInstanceOf[Double] ) diff --git a/search-api/src/test/scala/no/ndla/searchapi/TestData.scala b/search-api/src/test/scala/no/ndla/searchapi/TestData.scala index ef4b3aef2d..9667dff1b0 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/TestData.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/TestData.scala @@ -8,7 +8,7 @@ package no.ndla.searchapi import no.ndla.common.configuration.Constants.EmbedTagName -import no.ndla.common.model.api.MyNDLABundle +import no.ndla.common.model.api.MyNDLABundleDTO import no.ndla.common.model.domain.{ ArticleContent, ArticleMetaImage, @@ -1561,7 +1561,7 @@ object TestData { val taxonomyTestBundle: TaxonomyBundle = TaxonomyBundle(nodes = nodes) - val myndlaTestBundle: MyNDLABundle = MyNDLABundle(Map.empty) + val myndlaTestBundle: MyNDLABundleDTO = MyNDLABundleDTO(Map.empty) val emptyGrepBundle: GrepBundle = GrepBundle( kjerneelementer = List.empty, diff --git a/search-api/src/test/scala/no/ndla/searchapi/model/search/SearchableLearningPathTest.scala b/search-api/src/test/scala/no/ndla/searchapi/model/search/SearchableLearningPathTest.scala index f360e950c7..8a78daf21a 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/model/search/SearchableLearningPathTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/model/search/SearchableLearningPathTest.scala @@ -8,10 +8,10 @@ package no.ndla.searchapi.model.search import no.ndla.common.CirceUtil -import no.ndla.common.model.api.{Author, License} +import no.ndla.common.model.api.{AuthorDTO, LicenseDTO} import no.ndla.common.model.domain.learningpath.{LearningPathStatus, LearningPathVerificationStatus, StepType} import no.ndla.search.model.{LanguageValue, SearchableLanguageList, SearchableLanguageValues} -import no.ndla.searchapi.model.api.learningpath.Copyright +import no.ndla.searchapi.model.api.learningpath.CopyrightDTO import no.ndla.searchapi.{TestData, TestEnvironment, UnitSuite} import no.ndla.searchapi.TestData.* import no.ndla.searchapi.model.domain.LearningResourceType @@ -55,9 +55,9 @@ class SearchableLearningPathTest extends UnitSuite with TestEnvironment { defaultTitle = Some("Christian Tut"), tags = tags, learningsteps = learningsteps, - copyright = Copyright( - License("by-sa", Some("bysasaa"), None), - Seq(Author("Supplier", "Jonas"), Author("Originator", "Kakemonsteret")) + copyright = CopyrightDTO( + LicenseDTO("by-sa", Some("bysasaa"), None), + Seq(AuthorDTO("Supplier", "Jonas"), AuthorDTO("Originator", "Kakemonsteret")) ), isBasedOn = Some(1001), supportedLanguages = List("nb", "en", "nn"), diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/ConverterServiceTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/ConverterServiceTest.scala index d2bbe619c9..94b5865ea8 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/ConverterServiceTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/ConverterServiceTest.scala @@ -16,9 +16,9 @@ class ConverterServiceTest extends UnitSuite with TestEnvironment { override val converterService = new ConverterService test("searchResultToApiModel should return the api model of the corresponding input domain model") { - converterService.searchResultToApiModel(TestData.sampleArticleSearch).isInstanceOf[api.ArticleResults] - converterService.searchResultToApiModel(TestData.sampleLearningpath).isInstanceOf[api.LearningpathResults] - converterService.searchResultToApiModel(TestData.sampleImageSearch).isInstanceOf[api.ImageResults] - converterService.searchResultToApiModel(TestData.sampleAudio).isInstanceOf[api.AudioResults] + converterService.searchResultToApiModel(TestData.sampleArticleSearch).isInstanceOf[api.ArticleResultsDTO] + converterService.searchResultToApiModel(TestData.sampleLearningpath).isInstanceOf[api.LearningpathResultsDTO] + converterService.searchResultToApiModel(TestData.sampleImageSearch).isInstanceOf[api.ImageResultsDTO] + converterService.searchResultToApiModel(TestData.sampleAudio).isInstanceOf[api.AudioResultsDTO] } } diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/search/DraftConceptIndexServiceTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/search/DraftConceptIndexServiceTest.scala index 91a1f86c56..021472c52f 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/search/DraftConceptIndexServiceTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/search/DraftConceptIndexServiceTest.scala @@ -53,7 +53,7 @@ class DraftConceptIndexServiceTest tags = languageList, subjectIds = List("urn:subject:1"), lastUpdated = now, - draftStatus = api.Status("IN_PROGRESS", Seq("PUBLISHED")), + draftStatus = api.StatusDTO("IN_PROGRESS", Seq("PUBLISHED")), users = List("noen", "some-id"), updatedBy = Seq("noen"), license = Some("CC-BY-SA-4.0"), diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/search/GrepSearchServiceTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/search/GrepSearchServiceTest.scala index e62abe3311..b434947cf4 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/search/GrepSearchServiceTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/search/GrepSearchServiceTest.scala @@ -11,8 +11,8 @@ import cats.implicits.catsSyntaxOptionId import no.ndla.network.tapir.NonEmptyString import no.ndla.scalatestsuite.IntegrationSuite import no.ndla.searchapi.TestEnvironment -import no.ndla.searchapi.controller.parameters.GrepSearchInput -import no.ndla.searchapi.model.api.grep.GrepSort.{ByCodeAsc, ByCodeDesc} +import no.ndla.searchapi.controller.parameters.GrepSearchInputDTO +import no.ndla.searchapi.model.api.grep.GrepSortDTO.{ByCodeAsc, ByCodeDesc} import no.ndla.searchapi.model.grep.{GrepBundle, GrepElement, GrepTitle} class GrepSearchServiceTest extends IntegrationSuite(EnableElasticsearchContainer = true) with TestEnvironment { @@ -66,7 +66,7 @@ class GrepSearchServiceTest extends IntegrationSuite(EnableElasticsearchContaine ) ) - val emptyInput: GrepSearchInput = GrepSearchInput( + val emptyInput: GrepSearchInputDTO = GrepSearchInputDTO( codes = None, language = None, page = None, diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceAtomicTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceAtomicTest.scala index 73d72a706a..8a926786f2 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceAtomicTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceAtomicTest.scala @@ -20,7 +20,7 @@ import no.ndla.network.tapir.NonEmptyString import no.ndla.scalatestsuite.IntegrationSuite import no.ndla.search.model.{LanguageValue, SearchableLanguageList, SearchableLanguageValues} import no.ndla.searchapi.TestData.* -import no.ndla.searchapi.model.api.ApiTaxonomyContext +import no.ndla.searchapi.model.api.ApiTaxonomyContextDTO import no.ndla.searchapi.model.domain.{IndexingBundle, LearningResourceType, Sort} import no.ndla.searchapi.model.search.SearchType import no.ndla.searchapi.model.taxonomy.* @@ -721,8 +721,8 @@ class MultiDraftSearchServiceAtomicTest val result = multiDraftSearchService.matchingQuery(multiDraftSearchSettings).get - def ctxsFor(id: Long): List[ApiTaxonomyContext] = result.results.find(_.id == id).get.contexts - def ctxFor(id: Long): ApiTaxonomyContext = { + def ctxsFor(id: Long): List[ApiTaxonomyContextDTO] = result.results.find(_.id == id).get.contexts + def ctxFor(id: Long): ApiTaxonomyContextDTO = { val ctxs = ctxsFor(id) ctxs.length should be(1) ctxs.head diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceTest.scala index a0ed1c511a..568993ef5b 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiDraftSearchServiceTest.scala @@ -14,7 +14,7 @@ import no.ndla.language.Language.AllLanguages import no.ndla.network.tapir.NonEmptyString import no.ndla.scalatestsuite.IntegrationSuite import no.ndla.searchapi.TestData.* -import no.ndla.searchapi.model.api.MetaImage +import no.ndla.searchapi.model.api.MetaImageDTO import no.ndla.searchapi.model.domain.{IndexingBundle, LearningResourceType, Sort} import no.ndla.searchapi.model.search.SearchPagination import no.ndla.searchapi.{TestData, TestEnvironment} @@ -620,7 +620,7 @@ class MultiDraftSearchServiceTest extends IntegrationSuite(EnableElasticsearchCo search.totalCount should be(1) search.results.head.id should be(10) search.results.head.metaImage should be( - Some(MetaImage("http://api-gateway.ndla-local/image-api/raw/id/123", "alt", "en")) + Some(MetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/123", "alt", "en")) ) } diff --git a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiSearchServiceTest.scala b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiSearchServiceTest.scala index 5f2f3da142..29695bff36 100644 --- a/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiSearchServiceTest.scala +++ b/search-api/src/test/scala/no/ndla/searchapi/service/search/MultiSearchServiceTest.scala @@ -15,7 +15,7 @@ import no.ndla.language.Language.AllLanguages import no.ndla.network.tapir.NonEmptyString import no.ndla.scalatestsuite.IntegrationSuite import no.ndla.searchapi.TestData.* -import no.ndla.searchapi.model.api.MetaImage +import no.ndla.searchapi.model.api.MetaImageDTO import no.ndla.searchapi.model.domain.{IndexingBundle, LearningResourceType, Sort} import no.ndla.searchapi.model.search.SearchPagination import no.ndla.searchapi.{TestData, TestEnvironment, UnitSuite} @@ -589,7 +589,7 @@ class MultiSearchServiceTest search.totalCount should be(1) search.results.head.id should be(10) search.results.head.metaImage should be( - Some(MetaImage("http://api-gateway.ndla-local/image-api/raw/id/442", "alt", "en")) + Some(MetaImageDTO("http://api-gateway.ndla-local/image-api/raw/id/442", "alt", "en")) ) } diff --git a/search/src/main/scala/no/ndla/search/AggregationBuilder.scala b/search/src/main/scala/no/ndla/search/AggregationBuilder.scala index 3590b380bf..886e7134a1 100644 --- a/search/src/main/scala/no/ndla/search/AggregationBuilder.scala +++ b/search/src/main/scala/no/ndla/search/AggregationBuilder.scala @@ -13,7 +13,7 @@ import com.sksamuel.elastic4s.fields.{ElasticField, NestedField, ObjectField, Te import com.sksamuel.elastic4s.requests.mappings.MappingDefinition import com.sksamuel.elastic4s.requests.searches.SearchResponse import com.sksamuel.elastic4s.requests.searches.aggs.Aggregation -import no.ndla.search.api.{MultiSearchTermsAggregation, TermValue} +import no.ndla.search.api.{MultiSearchTermsAggregationDTO, TermValueDTO} import no.ndla.search.model.domain.{Bucket, TermAggregation} import scala.annotation.tailrec @@ -143,13 +143,13 @@ object AggregationBuilder { } } - def toApiMultiTermsAggregation(agg: TermAggregation): MultiSearchTermsAggregation = - MultiSearchTermsAggregation( + def toApiMultiTermsAggregation(agg: TermAggregation): MultiSearchTermsAggregationDTO = + MultiSearchTermsAggregationDTO( field = agg.field.mkString("."), sumOtherDocCount = agg.sumOtherDocCount, docCountErrorUpperBound = agg.docCountErrorUpperBound, values = agg.buckets.map(b => - TermValue( + TermValueDTO( value = b.value, count = b.count ) diff --git a/search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregation.scala b/search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregationDTO.scala similarity index 69% rename from search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregation.scala rename to search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregationDTO.scala index 84f7469f09..e9d757876c 100644 --- a/search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregation.scala +++ b/search/src/main/scala/no/ndla/search/api/MultiSearchTermsAggregationDTO.scala @@ -11,29 +11,31 @@ import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder} import sttp.tapir.Schema.annotations.description -// format: off @description("Value that appears in the search aggregation") -case class TermValue( +case class TermValueDTO( @description("Value that appeared in result") value: String, @description("Number of times the value appeared in result") count: Int ) -object TermValue { - implicit val encoder: Encoder[TermValue] = deriveEncoder - implicit val decoder: Decoder[TermValue] = deriveDecoder +object TermValueDTO { + implicit val encoder: Encoder[TermValueDTO] = deriveEncoder + implicit val decoder: Decoder[TermValueDTO] = deriveDecoder } +// format: off @description("Information about search aggregation on `field`") -case class MultiSearchTermsAggregation( - @description("The field the specific aggregation is matching") field: String, - @description("Number of documents with values that didn't appear in the aggregation. (Will only happen if there are more than 50 different values)") sumOtherDocCount: Int, +case class MultiSearchTermsAggregationDTO( + @description("The field the specific aggregation is matching") + field: String, + @description("Number of documents with values that didn't appear in the aggregation. (Will only happen if there are more than 50 different values)") + sumOtherDocCount: Int, @description("The result is approximate, this gives an approximation of potential errors. (Specifics here: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-approximate-counts)") docCountErrorUpperBound: Int, - @description("Values appearing in the field") values: Seq[TermValue] + @description("Values appearing in the field") values: Seq[TermValueDTO] ) // format: on -object MultiSearchTermsAggregation { - implicit val encoder: Encoder[MultiSearchTermsAggregation] = deriveEncoder - implicit val decoder: Decoder[MultiSearchTermsAggregation] = deriveDecoder +object MultiSearchTermsAggregationDTO { + implicit val encoder: Encoder[MultiSearchTermsAggregationDTO] = deriveEncoder + implicit val decoder: Decoder[MultiSearchTermsAggregationDTO] = deriveDecoder } diff --git a/typescript/types-backend/article-api.ts b/typescript/types-backend/article-api.ts index 7edc645a4d..2d22a57ed1 100644 --- a/typescript/types-backend/article-api.ts +++ b/typescript/types-backend/article-api.ts @@ -13,42 +13,42 @@ export enum ArticleSortEnum { export type Availability = ("everyone" | "teacher") -export interface IArticleContentV2 { +export interface IArticleContentV2DTO { content: string language: string } -export interface IArticleDump { +export interface IArticleDumpDTO { totalCount: number page: number pageSize: number language: string - results: IArticleV2[] + results: IArticleV2DTO[] } -export interface IArticleIds { +export interface IArticleIdsDTO { articleId: number externalIds: string[] } -export interface IArticleIntroduction { +export interface IArticleIntroductionDTO { introduction: string htmlIntroduction: string language: string } -export interface IArticleMetaDescription { +export interface IArticleMetaDescriptionDTO { metaDescription: string language: string } -export interface IArticleMetaImage { +export interface IArticleMetaImageDTO { url: string alt: string language: string } -export interface IArticleSearchParams { +export interface IArticleSearchParamsDTO { query?: string language?: string license?: string @@ -62,13 +62,13 @@ export interface IArticleSearchParams { grepCodes?: string[] } -export interface IArticleSummaryV2 { +export interface IArticleSummaryV2DTO { id: number - title: IArticleTitle - visualElement?: IVisualElement - introduction?: IArticleIntroduction - metaDescription?: IArticleMetaDescription - metaImage?: IArticleMetaImage + title: IArticleTitleDTO + visualElement?: IVisualElementDTO + introduction?: IArticleIntroductionDTO + metaDescription?: IArticleMetaDescriptionDTO + metaImage?: IArticleMetaImageDTO url: string license: string articleType: string @@ -78,30 +78,30 @@ export interface IArticleSummaryV2 { availability: string } -export interface IArticleTag { +export interface IArticleTagDTO { tags: string[] language: string } -export interface IArticleTitle { +export interface IArticleTitleDTO { title: string htmlTitle: string language: string } -export interface IArticleV2 { +export interface IArticleV2DTO { id: number oldNdlaUrl?: string revision: number - title: IArticleTitle - content: IArticleContentV2 - copyright: ICopyright - tags: IArticleTag - requiredLibraries: IRequiredLibrary[] - visualElement?: IVisualElement - metaImage?: IArticleMetaImage - introduction?: IArticleIntroduction - metaDescription: IArticleMetaDescription + title: IArticleTitleDTO + content: IArticleContentV2DTO + copyright: ICopyrightDTO + tags: IArticleTagDTO + requiredLibraries: IRequiredLibraryDTO[] + visualElement?: IVisualElementDTO + metaImage?: IArticleMetaImageDTO + introduction?: IArticleIntroductionDTO + metaDescription: IArticleMetaDescriptionDTO created: string updated: string updatedBy: string @@ -111,53 +111,53 @@ export interface IArticleV2 { grepCodes: string[] conceptIds: number[] availability: string - relatedContent: (IRelatedContentLink | number)[] + relatedContent: (IRelatedContentLinkDTO | number)[] revisionDate?: string slug?: string } -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface ICopyright { - license: ILicense +export interface ICopyrightDTO { + license: ILicenseDTO origin?: string - creators: IAuthor[] - processors: IAuthor[] - rightsholders: IAuthor[] + creators: IAuthorDTO[] + processors: IAuthorDTO[] + rightsholders: IAuthorDTO[] validFrom?: string validTo?: string processed: boolean } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface IRelatedContentLink { +export interface IRelatedContentLinkDTO { title: string url: string } -export interface IRequiredLibrary { +export interface IRequiredLibraryDTO { mediaType: string name: string url: string } -export interface ISearchResultV2 { +export interface ISearchResultV2DTO { totalCount: number page?: number pageSize: number language: string - results: IArticleSummaryV2[] + results: IArticleSummaryV2DTO[] } -export interface ITagsSearchResult { +export interface ITagsSearchResultDTO { totalCount: number page: number pageSize: number @@ -165,19 +165,7 @@ export interface ITagsSearchResult { results: string[] } -export interface IValidationError { - code: string - description: string - messages: IValidationMessage[] - occuredAt: string -} - -export interface IValidationMessage { - field: string - message: string -} - -export interface IVisualElement { +export interface IVisualElementDTO { visualElement: string language: string } diff --git a/typescript/types-backend/audio-api.ts b/typescript/types-backend/audio-api.ts index 7e208b7679..c53e0c2add 100644 --- a/typescript/types-backend/audio-api.ts +++ b/typescript/types-backend/audio-api.ts @@ -11,106 +11,106 @@ export enum AudioSortEnum { ByIdAsc = "id", } -export interface IAudio { +export interface IAudioDTO { url: string mimeType: string fileSize: number language: string } -export interface IAudioMetaInformation { +export interface IAudioMetaInformationDTO { id: number revision: number - title: ITitle - audioFile: IAudio - copyright: ICopyright - tags: ITag + title: ITitleDTO + audioFile: IAudioDTO + copyright: ICopyrightDTO + tags: ITagDTO supportedLanguages: string[] audioType: string - podcastMeta?: IPodcastMeta - series?: ISeries - manuscript?: IManuscript + podcastMeta?: IPodcastMetaDTO + series?: ISeriesDTO + manuscript?: IManuscriptDTO created: string updated: string } -export interface IAudioSummary { +export interface IAudioSummaryDTO { id: number - title: ITitle + title: ITitleDTO audioType: string url: string license: string supportedLanguages: string[] - manuscript?: IManuscript - podcastMeta?: IPodcastMeta - series?: ISeriesSummary + manuscript?: IManuscriptDTO + podcastMeta?: IPodcastMetaDTO + series?: ISeriesSummaryDTO lastUpdated: string } -export interface IAudioSummarySearchResult { +export interface IAudioSummarySearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: IAudioSummary[] + results: IAudioSummaryDTO[] } -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface ICopyright { - license: ILicense +export interface ICopyrightDTO { + license: ILicenseDTO origin?: string - creators: IAuthor[] - processors: IAuthor[] - rightsholders: IAuthor[] + creators: IAuthorDTO[] + processors: IAuthorDTO[] + rightsholders: IAuthorDTO[] validFrom?: string validTo?: string processed: boolean } -export interface ICoverPhoto { +export interface ICoverPhotoDTO { id: string url: string altText: string } -export interface IDescription { +export interface IDescriptionDTO { description: string language: string } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface IManuscript { +export interface IManuscriptDTO { manuscript: string language: string } -export interface INewAudioMetaInformation { +export interface INewAudioMetaInformationDTO { title: string language: string - copyright: ICopyright + copyright: ICopyrightDTO tags: string[] audioType?: string - podcastMeta?: INewPodcastMeta + podcastMeta?: INewPodcastMetaDTO seriesId?: number manuscript?: string } -export interface INewPodcastMeta { +export interface INewPodcastMetaDTO { introduction: string coverPhotoId: string coverPhotoAltText: string } -export interface INewSeries { +export interface INewSeriesDTO { title: string description: string coverPhotoId: string @@ -121,13 +121,13 @@ export interface INewSeries { hasRSS?: boolean } -export interface IPodcastMeta { +export interface IPodcastMetaDTO { introduction: string - coverPhoto: ICoverPhoto + coverPhoto: ICoverPhotoDTO language: string } -export interface ISearchParams { +export interface ISearchParamsDTO { query?: string license?: string language?: string @@ -140,18 +140,18 @@ export interface ISearchParams { fallback?: boolean } -export interface ISeries { +export interface ISeriesDTO { id: number revision: number - title: ITitle - description: IDescription - coverPhoto: ICoverPhoto - episodes?: IAudioMetaInformation[] + title: ITitleDTO + description: IDescriptionDTO + coverPhoto: ICoverPhotoDTO + episodes?: IAudioMetaInformationDTO[] supportedLanguages: string[] hasRSS: boolean } -export interface ISeriesSearchParams { +export interface ISeriesSearchParamsDTO { query?: string language?: string page?: number @@ -161,29 +161,29 @@ export interface ISeriesSearchParams { fallback?: boolean } -export interface ISeriesSummary { +export interface ISeriesSummaryDTO { id: number - title: ITitle - description: IDescription + title: ITitleDTO + description: IDescriptionDTO supportedLanguages: string[] - episodes?: IAudioSummary[] - coverPhoto: ICoverPhoto + episodes?: IAudioSummaryDTO[] + coverPhoto: ICoverPhotoDTO } -export interface ISeriesSummarySearchResult { +export interface ISeriesSummarySearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: ISeriesSummary[] + results: ISeriesSummaryDTO[] } -export interface ITag { +export interface ITagDTO { tags: string[] language: string } -export interface ITagsSearchResult { +export interface ITagsSearchResultDTO { totalCount: number page: number pageSize: number @@ -191,19 +191,19 @@ export interface ITagsSearchResult { results: string[] } -export interface ITitle { +export interface ITitleDTO { title: string language: string } -export interface IUpdatedAudioMetaInformation { +export interface IUpdatedAudioMetaInformationDTO { revision: number title: string language: string - copyright: ICopyright + copyright: ICopyrightDTO tags: string[] audioType?: string - podcastMeta?: INewPodcastMeta + podcastMeta?: INewPodcastMetaDTO seriesId?: number manuscript?: string } diff --git a/typescript/types-backend/concept-api.ts b/typescript/types-backend/concept-api.ts index f1f2214a53..80c35ea595 100644 --- a/typescript/types-backend/concept-api.ts +++ b/typescript/types-backend/concept-api.ts @@ -19,52 +19,52 @@ export enum ConceptSortEnum { ByConceptTypeDesc = "-conceptType", } -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface IConcept { +export interface IConceptContent { + content: string + htmlContent: string + language: string +} + +export interface IConceptDTO { id: number revision: number - title: IConceptTitle + title: IConceptTitleDTO content?: IConceptContent - copyright?: IDraftCopyright + copyright?: IDraftCopyrightDTO source?: string - metaImage?: IConceptMetaImage - tags?: IConceptTags + metaImage?: IConceptMetaImageDTO + tags?: IConceptTagsDTO subjectIds?: string[] created: string updated: string updatedBy?: string[] supportedLanguages: string[] articleIds: number[] - status: IStatus - visualElement?: IVisualElement - responsible?: IConceptResponsible + status: IStatusDTO + visualElement?: IVisualElementDTO + responsible?: IConceptResponsibleDTO conceptType: string - glossData?: IGlossData - editorNotes?: IEditorNote[] + glossData?: IGlossDataDTO + editorNotes?: IEditorNoteDTO[] } -export interface IConceptContent { - content: string - htmlContent: string - language: string -} - -export interface IConceptMetaImage { +export interface IConceptMetaImageDTO { url: string alt: string language: string } -export interface IConceptResponsible { +export interface IConceptResponsibleDTO { responsibleId: string lastUpdated: string } -export interface IConceptSearchParams { +export interface IConceptSearchParamsDTO { query?: string language?: string page?: number @@ -82,50 +82,50 @@ export interface IConceptSearchParams { aggregatePaths?: string[] } -export interface IConceptSearchResult { +export interface IConceptSearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: IConceptSummary[] - aggregations: IMultiSearchTermsAggregation[] + results: IConceptSummaryDTO[] + aggregations: IMultiSearchTermsAggregationDTO[] } -export interface IConceptSummary { +export interface IConceptSummaryDTO { id: number - title: IConceptTitle + title: IConceptTitleDTO content: IConceptContent - metaImage: IConceptMetaImage - tags?: IConceptTags + metaImage: IConceptMetaImageDTO + tags?: IConceptTagsDTO subjectIds?: string[] supportedLanguages: string[] lastUpdated: string created: string - status: IStatus + status: IStatusDTO updatedBy: string[] license?: string - copyright?: IDraftCopyright - visualElement?: IVisualElement + copyright?: IDraftCopyrightDTO + visualElement?: IVisualElementDTO articleIds: number[] source?: string - responsible?: IConceptResponsible + responsible?: IConceptResponsibleDTO conceptType: string - glossData?: IGlossData + glossData?: IGlossDataDTO subjectName?: string conceptTypeName: string } -export interface IConceptTags { +export interface IConceptTagsDTO { tags: string[] language: string } -export interface IConceptTitle { +export interface IConceptTitleDTO { title: string language: string } -export interface IDraftConceptSearchParams { +export interface IDraftConceptSearchParamsDTO { query?: string language?: string page?: number @@ -145,83 +145,83 @@ export interface IDraftConceptSearchParams { aggregatePaths?: string[] } -export interface IDraftCopyright { - license?: ILicense +export interface IDraftCopyrightDTO { + license?: ILicenseDTO origin?: string - creators: IAuthor[] - processors: IAuthor[] - rightsholders: IAuthor[] + creators: IAuthorDTO[] + processors: IAuthorDTO[] + rightsholders: IAuthorDTO[] validFrom?: string validTo?: string processed: boolean } -export interface IEditorNote { +export interface IEditorNoteDTO { note: string updatedBy: string - status: IStatus + status: IStatusDTO timestamp: string } -export interface IGlossData { +export interface IGlossDataDTO { gloss: string wordClass: string originalLanguage: string transcriptions: { [ key: string ]: string } - examples: IGlossExample[][] + examples: IGlossExampleDTO[][] } -export interface IGlossExample { +export interface IGlossExampleDTO { example: string language: string transcriptions: { [ key: string ]: string } } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface IMultiSearchTermsAggregation { +export interface IMultiSearchTermsAggregationDTO { field: string sumOtherDocCount: number docCountErrorUpperBound: number - values: ITermValue[] + values: ITermValueDTO[] } -export interface INewConcept { +export interface INewConceptDTO { language: string title: string content?: string - copyright?: IDraftCopyright - metaImage?: INewConceptMetaImage + copyright?: IDraftCopyrightDTO + metaImage?: INewConceptMetaImageDTO tags?: string[] subjectIds?: string[] articleIds?: number[] visualElement?: string responsibleId?: string conceptType: string - glossData?: IGlossData + glossData?: IGlossDataDTO } -export interface INewConceptMetaImage { +export interface INewConceptMetaImageDTO { id: string alt: string } -export interface IStatus { +export interface IStatusDTO { current: string other: string[] } -export interface ISubjectTags { +export interface ISubjectTagsDTO { subjectId: string tags: string[] language: string } -export interface ITagsSearchResult { +export interface ITagsSearchResultDTO { totalCount: number page: number pageSize: number @@ -229,17 +229,17 @@ export interface ITagsSearchResult { results: string[] } -export interface ITermValue { +export interface ITermValueDTO { value: string count: number } -export interface IUpdatedConcept { +export interface IUpdatedConceptDTO { language: string title?: string content?: string - metaImage: UpdateOrDeleteNewConceptMetaImage - copyright?: IDraftCopyright + metaImage: UpdateOrDeleteNewConceptMetaImageDTO + copyright?: IDraftCopyrightDTO tags?: string[] subjectIds?: string[] articleIds?: number[] @@ -247,28 +247,16 @@ export interface IUpdatedConcept { visualElement?: string responsibleId: UpdateOrDeleteString conceptType?: string - glossData?: IGlossData -} - -export interface IValidationError { - code: string - description: string - messages: IValidationMessage[] - occuredAt: string -} - -export interface IValidationMessage { - field: string - message: string + glossData?: IGlossDataDTO } -export interface IVisualElement { +export interface IVisualElementDTO { visualElement: string language: string } export type Sort = ConceptSortEnum -export type UpdateOrDeleteNewConceptMetaImage = (null | undefined | INewConceptMetaImage) +export type UpdateOrDeleteNewConceptMetaImageDTO = (null | undefined | INewConceptMetaImageDTO) export type UpdateOrDeleteString = (null | undefined | string) diff --git a/typescript/types-backend/draft-api.ts b/typescript/types-backend/draft-api.ts index 59c9f7bd8e..51644577a5 100644 --- a/typescript/types-backend/draft-api.ts +++ b/typescript/types-backend/draft-api.ts @@ -15,65 +15,65 @@ export enum DraftSortEnum { export type Grade = (1 | 2 | 3 | 4 | 5) -export interface IArticle { +export interface IArticleContentDTO { + content: string + language: string +} + +export interface IArticleDTO { id: number oldNdlaUrl?: string revision: number - status: IStatus - title?: IArticleTitle - content?: IArticleContent - copyright?: IDraftCopyright - tags?: IArticleTag - requiredLibraries: IRequiredLibrary[] - visualElement?: IVisualElement - introduction?: IArticleIntroduction - metaDescription?: IArticleMetaDescription - metaImage?: IArticleMetaImage + status: IStatusDTO + title?: IArticleTitleDTO + content?: IArticleContentDTO + copyright?: IDraftCopyrightDTO + tags?: IArticleTagDTO + requiredLibraries: IRequiredLibraryDTO[] + visualElement?: IVisualElementDTO + introduction?: IArticleIntroductionDTO + metaDescription?: IArticleMetaDescriptionDTO + metaImage?: IArticleMetaImageDTO created: string updated: string updatedBy: string published: string articleType: string supportedLanguages: string[] - notes: IEditorNote[] + notes: IEditorNoteDTO[] editorLabels: string[] grepCodes: string[] conceptIds: number[] availability: string - relatedContent: (IRelatedContentLink | number)[] - revisions: IRevisionMeta[] - responsible?: IDraftResponsible + relatedContent: (IRelatedContentLinkDTO | number)[] + revisions: IRevisionMetaDTO[] + responsible?: IDraftResponsibleDTO slug?: string - comments: IComment[] + comments: ICommentDTO[] prioritized: boolean priority: string started: boolean - qualityEvaluation?: IQualityEvaluation -} - -export interface IArticleContent { - content: string - language: string + qualityEvaluation?: IQualityEvaluationDTO } -export interface IArticleIntroduction { +export interface IArticleIntroductionDTO { introduction: string htmlIntroduction: string language: string } -export interface IArticleMetaDescription { +export interface IArticleMetaDescriptionDTO { metaDescription: string language: string } -export interface IArticleMetaImage { +export interface IArticleMetaImageDTO { url: string alt: string language: string } -export interface IArticleSearchParams { +export interface IArticleSearchParamsDTO { query?: string language?: string license?: string @@ -87,40 +87,40 @@ export interface IArticleSearchParams { grepCodes?: string[] } -export interface IArticleSummary { +export interface IArticleSummaryDTO { id: number - title: IArticleTitle - visualElement?: IVisualElement - introduction?: IArticleIntroduction + title: IArticleTitleDTO + visualElement?: IVisualElementDTO + introduction?: IArticleIntroductionDTO url: string license: string articleType: string supportedLanguages: string[] - tags?: IArticleTag + tags?: IArticleTagDTO notes: string[] users: string[] grepCodes: string[] - status: IStatus + status: IStatusDTO updated: string } -export interface IArticleTag { +export interface IArticleTagDTO { tags: string[] language: string } -export interface IArticleTitle { +export interface IArticleTitleDTO { title: string htmlTitle: string language: string } -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface IComment { +export interface ICommentDTO { id: string content: string created: string @@ -129,43 +129,43 @@ export interface IComment { solved: boolean } -export interface IDraftCopyright { - license?: ILicense +export interface IDraftCopyrightDTO { + license?: ILicenseDTO origin?: string - creators: IAuthor[] - processors: IAuthor[] - rightsholders: IAuthor[] + creators: IAuthorDTO[] + processors: IAuthorDTO[] + rightsholders: IAuthorDTO[] validFrom?: string validTo?: string processed: boolean } -export interface IDraftResponsible { +export interface IDraftResponsibleDTO { responsibleId: string lastUpdated: string } -export interface IEditorNote { +export interface IEditorNoteDTO { note: string user: string - status: IStatus + status: IStatusDTO timestamp: string } -export interface IGrepCodesSearchResult { +export interface IGrepCodesSearchResultDTO { totalCount: number page: number pageSize: number results: string[] } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface INewArticle { +export interface INewArticleDTO { language: string title: string published?: string @@ -173,78 +173,78 @@ export interface INewArticle { tags?: string[] introduction?: string metaDescription?: string - metaImage?: INewArticleMetaImage + metaImage?: INewArticleMetaImageDTO visualElement?: string - copyright?: IDraftCopyright - requiredLibraries?: IRequiredLibrary[] + copyright?: IDraftCopyrightDTO + requiredLibraries?: IRequiredLibraryDTO[] articleType: string notes?: string[] editorLabels?: string[] grepCodes?: string[] conceptIds?: number[] availability?: string - relatedContent?: (IRelatedContentLink | number)[] - revisionMeta?: IRevisionMeta[] + relatedContent?: (IRelatedContentLinkDTO | number)[] + revisionMeta?: IRevisionMetaDTO[] responsibleId?: string slug?: string - comments?: INewComment[] + comments?: INewCommentDTO[] prioritized?: boolean priority?: string - qualityEvaluation?: IQualityEvaluation + qualityEvaluation?: IQualityEvaluationDTO } -export interface INewArticleMetaImage { +export interface INewArticleMetaImageDTO { id: string alt: string } -export interface INewComment { +export interface INewCommentDTO { content: string isOpen?: boolean } -export interface IQualityEvaluation { +export interface IQualityEvaluationDTO { grade: Grade note?: string } -export interface IRelatedContentLink { +export interface IRelatedContentLinkDTO { title: string url: string } -export interface IRequiredLibrary { +export interface IRequiredLibraryDTO { mediaType: string name: string url: string } -export interface IRevisionMeta { +export interface IRevisionMetaDTO { id?: string revisionDate: string note: string status: string } -export interface ISavedSearch { +export interface ISavedSearchDTO { searchUrl: string searchPhrase: string } -export interface ISearchResult { +export interface ISearchResultDTO { totalCount: number page: number pageSize: number language: string - results: IArticleSummary[] + results: IArticleSummaryDTO[] } -export interface IStatus { +export interface IStatusDTO { current: string other: string[] } -export interface ITagsSearchResult { +export interface ITagsSearchResultDTO { totalCount: number page: number pageSize: number @@ -252,7 +252,7 @@ export interface ITagsSearchResult { results: string[] } -export interface IUpdatedArticle { +export interface IUpdatedArticleDTO { revision: number language?: string title?: string @@ -262,10 +262,10 @@ export interface IUpdatedArticle { tags?: string[] introduction?: string metaDescription?: string - metaImage: UpdateOrDeleteNewArticleMetaImage + metaImage: UpdateOrDeleteNewArticleMetaImageDTO visualElement?: string - copyright?: IDraftCopyright - requiredLibraries?: IRequiredLibrary[] + copyright?: IDraftCopyrightDTO + requiredLibraries?: IRequiredLibraryDTO[] articleType?: string notes?: string[] editorLabels?: string[] @@ -273,52 +273,52 @@ export interface IUpdatedArticle { conceptIds?: number[] createNewVersion?: boolean availability?: string - relatedContent?: (IRelatedContentLink | number)[] - revisionMeta?: IRevisionMeta[] + relatedContent?: (IRelatedContentLinkDTO | number)[] + revisionMeta?: IRevisionMetaDTO[] responsibleId: UpdateOrDeleteString slug?: string - comments?: IUpdatedComment[] + comments?: IUpdatedCommentDTO[] prioritized?: boolean priority?: string - qualityEvaluation?: IQualityEvaluation + qualityEvaluation?: IQualityEvaluationDTO } -export interface IUpdatedComment { +export interface IUpdatedCommentDTO { id?: string content: string isOpen?: boolean solved?: boolean } -export interface IUpdatedUserData { - savedSearches?: ISavedSearch[] +export interface IUpdatedUserDataDTO { + savedSearches?: ISavedSearchDTO[] latestEditedArticles?: string[] latestEditedConcepts?: string[] favoriteSubjects?: string[] } -export interface IUploadedFile { +export interface IUploadedFileDTO { filename: string mime: string extension: string path: string } -export interface IUserData { +export interface IUserDataDTO { userId: string - savedSearches?: ISavedSearch[] + savedSearches?: ISavedSearchDTO[] latestEditedArticles?: string[] latestEditedConcepts?: string[] favoriteSubjects?: string[] } -export interface IVisualElement { +export interface IVisualElementDTO { visualElement: string language: string } export type Sort = DraftSortEnum -export type UpdateOrDeleteNewArticleMetaImage = (null | undefined | INewArticleMetaImage) +export type UpdateOrDeleteNewArticleMetaImageDTO = (null | undefined | INewArticleMetaImageDTO) export type UpdateOrDeleteString = (null | undefined | string) diff --git a/typescript/types-backend/frontpage-api.ts b/typescript/types-backend/frontpage-api.ts index ce806044cc..1d278b8a3c 100644 --- a/typescript/types-backend/frontpage-api.ts +++ b/typescript/types-backend/frontpage-api.ts @@ -1,19 +1,19 @@ // DO NOT EDIT: generated file by scala-tsi -export interface IAboutFilmSubject { +export interface IAboutFilmSubjectDTO { title: string description: string - visualElement: IVisualElement + visualElement: IVisualElementDTO language: string } -export interface IAboutSubject { +export interface IAboutSubjectDTO { title: string description: string - visualElement: IVisualElement + visualElement: IVisualElementDTO } -export interface IBannerImage { +export interface IBannerImageDTO { mobileUrl?: string mobileId?: number desktopUrl: string @@ -27,95 +27,95 @@ export interface IErrorBody { statusCode: number } -export interface IFilmFrontPageData { +export interface IFilmFrontPageDataDTO { name: string - about: IAboutFilmSubject[] - movieThemes: IMovieTheme[] + about: IAboutFilmSubjectDTO[] + movieThemes: IMovieThemeDTO[] slideShow: string[] article?: string } -export interface IFrontPage { +export interface IFrontPageDTO { articleId: number - menu: IMenu[] + menu: IMenuDTO[] } -export interface IMenu { +export interface IMenuDTO { articleId: number - menu: IMenuData[] + menu: IMenuDataDTO[] hideLevel?: boolean } -export type IMenuData = IMenu +export type IMenuDataDTO = IMenuDTO -export interface IMovieTheme { - name: IMovieThemeName[] +export interface IMovieThemeDTO { + name: IMovieThemeNameDTO[] movies: string[] } -export interface IMovieThemeName { +export interface IMovieThemeNameDTO { name: string language: string } -export interface INewOrUpdateBannerImage { +export interface INewOrUpdateBannerImageDTO { mobileImageId?: number desktopImageId: number } -export interface INewOrUpdatedAboutSubject { +export interface INewOrUpdatedAboutSubjectDTO { title: string description: string language: string - visualElement: INewOrUpdatedVisualElement + visualElement: INewOrUpdatedVisualElementDTO } -export interface INewOrUpdatedFilmFrontPageData { +export interface INewOrUpdatedFilmFrontPageDataDTO { name: string - about: INewOrUpdatedAboutSubject[] - movieThemes: INewOrUpdatedMovieTheme[] + about: INewOrUpdatedAboutSubjectDTO[] + movieThemes: INewOrUpdatedMovieThemeDTO[] slideShow: string[] article?: string } -export interface INewOrUpdatedMetaDescription { +export interface INewOrUpdatedMetaDescriptionDTO { metaDescription: string language: string } -export interface INewOrUpdatedMovieName { +export interface INewOrUpdatedMovieNameDTO { name: string language: string } -export interface INewOrUpdatedMovieTheme { - name: INewOrUpdatedMovieName[] +export interface INewOrUpdatedMovieThemeDTO { + name: INewOrUpdatedMovieNameDTO[] movies: string[] } -export interface INewOrUpdatedVisualElement { +export interface INewOrUpdatedVisualElementDTO { type: string id: string alt?: string } -export interface INewSubjectFrontPageData { +export interface INewSubjectFrontPageDataDTO { name: string externalId?: string - banner: INewOrUpdateBannerImage - about: INewOrUpdatedAboutSubject[] - metaDescription: INewOrUpdatedMetaDescription[] + banner: INewOrUpdateBannerImageDTO + about: INewOrUpdatedAboutSubjectDTO[] + metaDescription: INewOrUpdatedMetaDescriptionDTO[] editorsChoices?: string[] connectedTo?: string[] buildsOn?: string[] leadsTo?: string[] } -export interface ISubjectPageData { +export interface ISubjectPageDataDTO { id: number name: string - banner: IBannerImage - about?: IAboutSubject + banner: IBannerImageDTO + about?: IAboutSubjectDTO metaDescription?: string editorsChoices: string[] supportedLanguages: string[] @@ -124,19 +124,19 @@ export interface ISubjectPageData { leadsTo: string[] } -export interface IUpdatedSubjectFrontPageData { +export interface IUpdatedSubjectFrontPageDataDTO { name?: string externalId?: string - banner?: INewOrUpdateBannerImage - about?: INewOrUpdatedAboutSubject[] - metaDescription?: INewOrUpdatedMetaDescription[] + banner?: INewOrUpdateBannerImageDTO + about?: INewOrUpdatedAboutSubjectDTO[] + metaDescription?: INewOrUpdatedMetaDescriptionDTO[] editorsChoices?: string[] connectedTo?: string[] buildsOn?: string[] leadsTo?: string[] } -export interface IVisualElement { +export interface IVisualElementDTO { type: string url: string alt?: string diff --git a/typescript/types-backend/image-api.ts b/typescript/types-backend/image-api.ts index b383abe441..54ff96a69b 100644 --- a/typescript/types-backend/image-api.ts +++ b/typescript/types-backend/image-api.ts @@ -1,98 +1,98 @@ // DO NOT EDIT: generated file by scala-tsi -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface ICopyright { - license: ILicense +export interface ICopyrightDTO { + license: ILicenseDTO origin?: string - creators: IAuthor[] - processors: IAuthor[] - rightsholders: IAuthor[] + creators: IAuthorDTO[] + processors: IAuthorDTO[] + rightsholders: IAuthorDTO[] validFrom?: string validTo?: string processed: boolean } -export interface IEditorNote { +export interface IEditorNoteDTO { timestamp: string updatedBy: string note: string } -export interface IImage { - url: string - size: number - contentType: string -} - -export interface IImageAltText { +export interface IImageAltTextDTO { alttext: string language: string } -export interface IImageCaption { +export interface IImageCaptionDTO { caption: string language: string } -export interface IImageDimensions { +export interface IImageDTO { + url: string + size: number + contentType: string +} + +export interface IImageDimensionsDTO { width: number height: number } -export interface IImageFile { +export interface IImageFileDTO { fileName: string size: number contentType: string imageUrl: string - dimensions?: IImageDimensions + dimensions?: IImageDimensionsDTO language: string } -export interface IImageMetaInformationV2 { +export interface IImageMetaInformationV2DTO { id: string metaUrl: string - title: IImageTitle - alttext: IImageAltText + title: IImageTitleDTO + alttext: IImageAltTextDTO imageUrl: string size: number contentType: string - copyright: ICopyright - tags: IImageTag - caption: IImageCaption + copyright: ICopyrightDTO + tags: IImageTagDTO + caption: IImageCaptionDTO supportedLanguages: string[] created: string createdBy: string modelRelease: string - editorNotes?: IEditorNote[] - imageDimensions?: IImageDimensions + editorNotes?: IEditorNoteDTO[] + imageDimensions?: IImageDimensionsDTO } -export interface IImageMetaInformationV3 { +export interface IImageMetaInformationV3DTO { id: string metaUrl: string - title: IImageTitle - alttext: IImageAltText - copyright: ICopyright - tags: IImageTag - caption: IImageCaption + title: IImageTitleDTO + alttext: IImageAltTextDTO + copyright: ICopyrightDTO + tags: IImageTagDTO + caption: IImageCaptionDTO supportedLanguages: string[] created: string createdBy: string modelRelease: string - editorNotes?: IEditorNote[] - image: IImageFile + editorNotes?: IEditorNoteDTO[] + image: IImageFileDTO } -export interface IImageMetaSummary { +export interface IImageMetaSummaryDTO { id: string - title: IImageTitle + title: IImageTitleDTO contributors: string[] - altText: IImageAltText - caption: IImageCaption + altText: IImageAltTextDTO + caption: IImageCaptionDTO previewUrl: string metaUrl: string license: string @@ -102,36 +102,36 @@ export interface IImageMetaSummary { lastUpdated: string fileSize: number contentType: string - imageDimensions?: IImageDimensions + imageDimensions?: IImageDimensionsDTO } -export interface IImageTag { +export interface IImageTagDTO { tags: string[] language: string } -export interface IImageTitle { +export interface IImageTitleDTO { title: string language: string } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface INewImageMetaInformationV2 { +export interface INewImageMetaInformationV2DTO { title: string alttext?: string - copyright: ICopyright + copyright: ICopyrightDTO tags: string[] caption: string language: string modelReleased?: string } -export interface ISearchParams { +export interface ISearchParamsDTO { query?: string license?: string language?: string @@ -146,23 +146,23 @@ export interface ISearchParams { modelReleased?: string[] } -export interface ISearchResult { +export interface ISearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: IImageMetaSummary[] + results: IImageMetaSummaryDTO[] } -export interface ISearchResultV3 { +export interface ISearchResultV3DTO { totalCount: number page?: number pageSize: number language: string - results: IImageMetaInformationV3[] + results: IImageMetaInformationV3DTO[] } -export interface ITagsSearchResult { +export interface ITagsSearchResultDTO { totalCount: number page: number pageSize: number @@ -170,28 +170,16 @@ export interface ITagsSearchResult { results: string[] } -export interface IUpdateImageMetaInformation { +export interface IUpdateImageMetaInformationDTO { language: string title?: string alttext: UpdateOrDeleteString - copyright?: ICopyright + copyright?: ICopyrightDTO tags?: string[] caption?: string modelReleased?: string } -export interface IValidationError { - code: string - description: string - messages: IValidationMessage[] - occurredAt: string -} - -export interface IValidationMessage { - field: string - message: string -} - export enum ImageSortEnum { ByRelevanceDesc = "-relevance", ByRelevanceAsc = "relevance", diff --git a/typescript/types-backend/learningpath-api.ts b/typescript/types-backend/learningpath-api.ts index c5b7362651..7ecbf897e2 100644 --- a/typescript/types-backend/learningpath-api.ts +++ b/typescript/types-backend/learningpath-api.ts @@ -1,164 +1,164 @@ // DO NOT EDIT: generated file by scala-tsi -export interface IAuthor { +export interface IAuthorDTO { type: string name: string } -export interface IConfigMeta { +export interface IConfigMetaDTO { key: string value: (boolean | string[]) updatedAt: string updatedBy: string } -export interface IConfigMetaRestricted { +export interface IConfigMetaRestrictedDTO { key: string value: (boolean | string[]) } -export interface ICopyright { - license: ILicense - contributors: IAuthor[] +export interface ICopyrightDTO { + license: ILicenseDTO + contributors: IAuthorDTO[] } -export interface ICoverPhoto { +export interface ICoverPhotoDTO { url: string metaUrl: string } -export interface IDescription { +export interface IDescriptionDTO { description: string language: string } -export interface IEmbedUrlV2 { +export interface IEmbedUrlV2DTO { url: string embedType: string } -export interface IIntroduction { +export interface IIntroductionDTO { introduction: string language: string } -export interface ILearningPathStatus { +export interface ILearningPathStatusDTO { status: string } -export interface ILearningPathSummaryV2 { +export interface ILearningPathSummaryV2DTO { id: number revision?: number - title: ITitle - description: IDescription - introduction: IIntroduction + title: ITitleDTO + description: IDescriptionDTO + introduction: IIntroductionDTO metaUrl: string coverPhotoUrl?: string duration?: number status: string created: string lastUpdated: string - tags: ILearningPathTags - copyright: ICopyright + tags: ILearningPathTagsDTO + copyright: ICopyrightDTO supportedLanguages: string[] isBasedOn?: number message?: string } -export interface ILearningPathTags { +export interface ILearningPathTagsDTO { tags: string[] language: string } -export interface ILearningPathTagsSummary { +export interface ILearningPathTagsSummaryDTO { language: string supportedLanguages: string[] tags: string[] } -export interface ILearningPathV2 { +export interface ILearningPathV2DTO { id: number revision: number isBasedOn?: number - title: ITitle - description: IDescription + title: ITitleDTO + description: IDescriptionDTO metaUrl: string - learningsteps: ILearningStepV2[] + learningsteps: ILearningStepV2DTO[] learningstepUrl: string - coverPhoto?: ICoverPhoto + coverPhoto?: ICoverPhotoDTO duration?: number status: string verificationStatus: string created: string lastUpdated: string - tags: ILearningPathTags - copyright: ICopyright + tags: ILearningPathTagsDTO + copyright: ICopyrightDTO canEdit: boolean supportedLanguages: string[] ownerId?: string - message?: IMessage + message?: IMessageDTO madeAvailable?: string } -export interface ILearningStepContainerSummary { +export interface ILearningStepContainerSummaryDTO { language: string - learningsteps: ILearningStepSummaryV2[] + learningsteps: ILearningStepSummaryV2DTO[] supportedLanguages: string[] } -export interface ILearningStepSeqNo { +export interface ILearningStepSeqNoDTO { seqNo: number } -export interface ILearningStepStatus { +export interface ILearningStepStatusDTO { status: string } -export interface ILearningStepSummaryV2 { +export interface ILearningStepSummaryV2DTO { id: number seqNo: number - title: ITitle + title: ITitleDTO type: string metaUrl: string } -export interface ILearningStepV2 { +export interface ILearningStepV2DTO { id: number revision: number seqNo: number - title: ITitle - introduction?: IIntroduction - description?: IDescription - embedUrl?: IEmbedUrlV2 + title: ITitleDTO + introduction?: IIntroductionDTO + description?: IDescriptionDTO + embedUrl?: IEmbedUrlV2DTO showTitle: boolean type: string - license?: ILicense + license?: ILicenseDTO metaUrl: string canEdit: boolean status: string supportedLanguages: string[] } -export interface ILicense { +export interface ILicenseDTO { license: string description?: string url?: string } -export interface IMessage { +export interface IMessageDTO { message: string date: string } -export interface ISearchResultV2 { +export interface ISearchResultV2DTO { totalCount: number page?: number pageSize: number language: string - results: ILearningPathSummaryV2[] + results: ILearningPathSummaryV2DTO[] } -export interface ITitle { +export interface ITitleDTO { title: string language: string } diff --git a/typescript/types-backend/myndla-api.ts b/typescript/types-backend/myndla-api.ts index b05ec457fb..6981b26dcb 100644 --- a/typescript/types-backend/myndla-api.ts +++ b/typescript/types-backend/myndla-api.ts @@ -2,7 +2,7 @@ export type ArenaGroup = "ADMIN" -export interface IArenaUser { +export interface IArenaUserDTO { id: number displayName: string username: string @@ -10,12 +10,17 @@ export interface IArenaUser { groups: ArenaGroup[] } -export interface IBreadcrumb { +export interface IBreadcrumbDTO { id: string name: string } -export interface ICategory { +export interface ICategoryBreadcrumbDTO { + id: number + title: string +} + +export interface ICategoryDTO { id: number title: string description: string @@ -26,16 +31,11 @@ export interface ICategory { rank: number parentCategoryId?: number categoryCount: number - subcategories: ICategory[] - breadcrumbs: ICategoryBreadcrumb[] -} - -export interface ICategoryBreadcrumb { - id: number - title: string + subcategories: ICategoryDTO[] + breadcrumbs: ICategoryBreadcrumbDTO[] } -export interface ICategoryWithTopics { +export interface ICategoryWithTopicsDTO { id: number title: string description: string @@ -43,63 +43,63 @@ export interface ICategoryWithTopics { postCount: number topicPage: number topicPageSize: number - topics: ITopic[] + topics: ITopicDTO[] isFollowing: boolean visible: boolean rank: number parentCategoryId?: number categoryCount: number - subcategories: ICategory[] - breadcrumbs: ICategoryBreadcrumb[] + subcategories: ICategoryDTO[] + breadcrumbs: ICategoryBreadcrumbDTO[] } -export interface IConfigMeta { +export interface IConfigMetaDTO { key: string value: (boolean | string[]) updatedAt: string updatedBy: string } -export interface IConfigMetaRestricted { +export interface IConfigMetaRestrictedDTO { key: string value: (boolean | string[]) } -export interface IFlag { +export interface IFlagDTO { id: number reason: string created: string resolved?: string isResolved: boolean - flagger?: IArenaUser + flagger?: IArenaUserDTO } -export interface IFolder { +export interface IFolderDTO { id: string name: string status: string parentId?: string - breadcrumbs: IBreadcrumb[] - subfolders: IFolderData[] - resources: IResource[] + breadcrumbs: IBreadcrumbDTO[] + subfolders: IFolderDataDTO[] + resources: IResourceDTO[] rank: number created: string updated: string shared?: string description?: string - owner?: IOwner + owner?: IOwnerDTO } -export type IFolderData = IFolder +export type IFolderDataDTO = IFolderDTO -export interface IMyNDLAGroup { +export interface IMyNDLAGroupDTO { id: string displayName: string isPrimarySchool: boolean parentId?: string } -export interface IMyNDLAUser { +export interface IMyNDLAUserDTO { id: number feideId: string username: string @@ -108,106 +108,106 @@ export interface IMyNDLAUser { favoriteSubjects: string[] role: string organization: string - groups: IMyNDLAGroup[] + groups: IMyNDLAGroupDTO[] arenaEnabled: boolean shareName: boolean arenaGroups: ArenaGroup[] } -export interface INewCategory { +export interface INewCategoryDTO { title: string description: string visible: boolean parentCategoryId?: number } -export interface INewFlag { +export interface INewFlagDTO { reason: string } -export interface INewFolder { +export interface INewFolderDTO { name: string parentId?: string status?: string description?: string } -export interface INewPost { +export interface INewPostDTO { content: string toPostId?: number } -export interface INewPostNotification { +export interface INewPostNotificationDTO { id: number topicId: number isRead: boolean topicTitle: string - post: IPost + post: IPostDTO notificationTime: string } -export interface INewResource { +export interface INewResourceDTO { resourceType: ResourceType path: string tags?: string[] resourceId: string } -export interface INewTopic { +export interface INewTopicDTO { title: string - initialPost: INewPost + initialPost: INewPostDTO isLocked?: boolean isPinned?: boolean } -export interface IOwner { +export interface IOwnerDTO { name: string } -export interface IPaginatedArenaUsers { +export interface IPaginatedArenaUsersDTO { totalCount: number page: number pageSize: number - items: IArenaUser[] + items: IArenaUserDTO[] } -export interface IPaginatedNewPostNotifications { +export interface IPaginatedNewPostNotificationsDTO { totalCount: number page: number pageSize: number - items: INewPostNotification[] + items: INewPostNotificationDTO[] } -export interface IPaginatedPosts { +export interface IPaginatedPostsDTO { totalCount: number page: number pageSize: number - items: IPost[] + items: IPostDTO[] } -export interface IPaginatedTopics { +export interface IPaginatedTopicsDTO { totalCount: number page: number pageSize: number - items: ITopic[] + items: ITopicDTO[] } -export interface IPost { +export interface IPostDTO { id: number content: string created: string updated: string - owner?: IArenaUser - flags?: IFlag[] + owner?: IArenaUserDTO + flags?: IFlagDTO[] topicId: number - replies: IPostWrapper[] + replies: IPostWrapperDTO[] upvotes: number upvoted: boolean } -export type IPostWrapper = IPost +export type IPostWrapperDTO = IPostDTO -export interface IResource { +export interface IResourceDTO { id: string resourceType: ResourceType path: string @@ -217,28 +217,28 @@ export interface IResource { rank?: number } -export interface IResourceStats { +export interface IResourceStatsDTO { type: string number: number } -export interface ISingleResourceStats { +export interface ISingleResourceStatsDTO { id: string favourites: number } -export interface IStats { +export interface IStatsDTO { numberOfUsers: number numberOfFolders: number numberOfResources: number numberOfTags: number numberOfSubjects: number numberOfSharedFolders: number - favouritedResources: IResourceStats[] + favouritedResources: IResourceStatsDTO[] favourited: { [ key: string ]: number } } -export interface ITopic { +export interface ITopicDTO { id: number title: string postCount: number @@ -251,11 +251,11 @@ export interface ITopic { voteCount: number } -export interface ITopicWithPosts { +export interface ITopicWithPostsDTO { id: number title: string postCount: number - posts: IPaginatedPosts + posts: IPaginatedPostsDTO created: string updated: string categoryId: number @@ -265,27 +265,27 @@ export interface ITopicWithPosts { voteCount: number } -export interface IUpdatedFolder { +export interface IUpdatedFolderDTO { name?: string status?: string description?: string } -export interface IUpdatedMyNDLAUser { +export interface IUpdatedMyNDLAUserDTO { favoriteSubjects?: string[] arenaEnabled?: boolean shareName?: boolean arenaGroups?: ArenaGroup[] } -export interface IUpdatedResource { +export interface IUpdatedResourceDTO { tags?: string[] resourceId?: string } -export interface IUserFolder { - folders: IFolder[] - sharedFolders: IFolder[] +export interface IUserFolderDTO { + folders: IFolderDTO[] + sharedFolders: IFolderDTO[] } export type ResourceType = ("article" | "audio" | "concept" | "image" | "learningpath" | "multidisciplinary" | "topic" | "video") diff --git a/typescript/types-backend/search-api.ts b/typescript/types-backend/search-api.ts index 318db5b721..c850824437 100644 --- a/typescript/types-backend/search-api.ts +++ b/typescript/types-backend/search-api.ts @@ -2,7 +2,7 @@ export type GrepSort = ("-relevance" | "relevance" | "-title" | "title" | "-code" | "code") -export interface IApiTaxonomyContext { +export interface IApiTaxonomyContextDTO { publicId: string root: string rootId: string @@ -12,53 +12,53 @@ export interface IApiTaxonomyContext { breadcrumbs: string[] contextId: string contextType: string - resourceTypes: ITaxonomyResourceType[] + resourceTypes: ITaxonomyResourceTypeDTO[] language: string isPrimary: boolean isActive: boolean url: string } -export interface IArticleIntroduction { +export interface IArticleIntroductionDTO { introduction: string htmlIntroduction: string language: string } -export interface IArticleResult { +export interface IArticleResultDTO { id: number - title: ITitleWithHtml - introduction?: IArticleIntroduction + title: ITitleWithHtmlDTO + introduction?: IArticleIntroductionDTO articleType: string supportedLanguages: string[] } -export interface IArticleResults { +export interface IArticleResultsDTO { type: string language: string totalCount: number page: number pageSize: number - results: IArticleResult[] + results: IArticleResultDTO[] } -export interface IAudioResult { +export interface IAudioResultDTO { id: number - title: ITitle + title: ITitleDTO url: string supportedLanguages: string[] } -export interface IAudioResults { +export interface IAudioResultsDTO { type: string language: string totalCount: number page: number pageSize: number - results: IAudioResult[] + results: IAudioResultDTO[] } -export interface IComment { +export interface ICommentDTO { id: string content: string created: string @@ -67,12 +67,12 @@ export interface IComment { solved: boolean } -export interface IDraftResponsible { +export interface IDraftResponsibleDTO { responsibleId: string lastUpdated: string } -export interface IDraftSearchParams { +export interface IDraftSearchParamsDTO { page?: number pageSize?: number articleTypes?: string[] @@ -109,12 +109,12 @@ export interface IDraftSearchParams { resultTypes?: SearchType[] } -export interface IGrepResult { +export interface IGrepResultDTO { code: string - title: ITitle + title: ITitleDTO } -export interface IGrepSearchInput { +export interface IGrepSearchInputDTO { prefixFilter?: string[] codes?: string[] query?: string @@ -124,119 +124,119 @@ export interface IGrepSearchInput { language?: string } -export interface IGrepSearchResults { +export interface IGrepSearchResultsDTO { totalCount: number page: number pageSize: number language: string - results: IGrepResult[] + results: IGrepResultDTO[] } -export interface IGroupSearchResult { +export interface IGroupSearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: IMultiSearchSummary[] - suggestions: IMultiSearchSuggestion[] - aggregations: IMultiSearchTermsAggregation[] + results: IMultiSearchSummaryDTO[] + suggestions: IMultiSearchSuggestionDTO[] + aggregations: IMultiSearchTermsAggregationDTO[] resourceType: string } -export interface IHighlightedField { +export interface IHighlightedFieldDTO { field: string matches: string[] } -export interface IImageAltText { +export interface IImageAltTextDTO { altText: string language: string } -export interface IImageResult { +export interface IImageResultDTO { id: number - title: ITitle - altText: IImageAltText + title: ITitleDTO + altText: IImageAltTextDTO previewUrl: string metaUrl: string supportedLanguages: string[] } -export interface IImageResults { +export interface IImageResultsDTO { type: string language: string totalCount: number page: number pageSize: number - results: IImageResult[] + results: IImageResultDTO[] } -export interface ILearningPathIntroduction { +export interface ILearningPathIntroductionDTO { introduction: string language: string } -export interface ILearningpathResult { +export interface ILearningpathResultDTO { id: number - title: ITitle - introduction: ILearningPathIntroduction + title: ITitleDTO + introduction: ILearningPathIntroductionDTO supportedLanguages: string[] } -export interface ILearningpathResults { +export interface ILearningpathResultsDTO { type: string language: string totalCount: number page: number pageSize: number - results: ILearningpathResult[] + results: ILearningpathResultDTO[] } -export interface IMetaDescription { +export interface IMetaDescriptionDTO { metaDescription: string language: string } -export interface IMetaImage { +export interface IMetaImageDTO { url: string alt: string language: string } -export interface IMultiSearchResult { +export interface IMultiSearchResultDTO { totalCount: number page?: number pageSize: number language: string - results: IMultiSearchSummary[] - suggestions: IMultiSearchSuggestion[] - aggregations: IMultiSearchTermsAggregation[] + results: IMultiSearchSummaryDTO[] + suggestions: IMultiSearchSuggestionDTO[] + aggregations: IMultiSearchTermsAggregationDTO[] } -export interface IMultiSearchSuggestion { +export interface IMultiSearchSuggestionDTO { name: string - suggestions: ISearchSuggestion[] + suggestions: ISearchSuggestionDTO[] } -export interface IMultiSearchSummary { +export interface IMultiSearchSummaryDTO { id: number - title: ITitleWithHtml - metaDescription: IMetaDescription - metaImage?: IMetaImage + title: ITitleWithHtmlDTO + metaDescription: IMetaDescriptionDTO + metaImage?: IMetaImageDTO url: string - contexts: IApiTaxonomyContext[] + contexts: IApiTaxonomyContextDTO[] supportedLanguages: string[] learningResourceType: LearningResourceType - status?: IStatus + status?: IStatusDTO traits: string[] score: number - highlights: IHighlightedField[] + highlights: IHighlightedFieldDTO[] paths: string[] lastUpdated: string license?: string - revisions: IRevisionMeta[] - responsible?: IDraftResponsible - comments?: IComment[] + revisions: IRevisionMetaDTO[] + responsible?: IDraftResponsibleDTO + comments?: ICommentDTO[] prioritized?: boolean priority?: string resourceTypeName?: string @@ -248,25 +248,20 @@ export interface IMultiSearchSummary { conceptSubjectIds?: string[] } -export interface IMultiSearchTermsAggregation { +export interface IMultiSearchTermsAggregationDTO { field: string sumOtherDocCount: number docCountErrorUpperBound: number - values: ITermValue[] + values: ITermValueDTO[] } -export interface IRevisionMeta { +export interface IRevisionMetaDTO { revisionDate: string note: string status: string } -export interface ISearchError { - type: string - errorMsg: string -} - -export interface ISearchParams { +export interface ISearchParamsDTO { page?: number pageSize?: number articleTypes?: string[] @@ -289,19 +284,19 @@ export interface ISearchParams { sort?: string } -export interface ISearchSuggestion { +export interface ISearchSuggestionDTO { text: string offset: number length: number - options: ISuggestOption[] + options: ISuggestOptionDTO[] } -export interface IStatus { +export interface IStatusDTO { current: string other: string[] } -export interface ISubjectAggregation { +export interface ISubjectAggregationDTO { subjectId: string publishedArticleCount: number oldArticleCount: number @@ -310,36 +305,36 @@ export interface ISubjectAggregation { favoritedCount: number } -export interface ISubjectAggregations { - subjects: ISubjectAggregation[] +export interface ISubjectAggregationsDTO { + subjects: ISubjectAggregationDTO[] } -export interface ISubjectAggsInput { +export interface ISubjectAggsInputDTO { subjects?: string[] } -export interface ISuggestOption { +export interface ISuggestOptionDTO { text: string score: number } -export interface ITaxonomyResourceType { +export interface ITaxonomyResourceTypeDTO { id: string name: string language: string } -export interface ITermValue { +export interface ITermValueDTO { value: string count: number } -export interface ITitle { +export interface ITitleDTO { title: string language: string } -export interface ITitleWithHtml { +export interface ITitleWithHtmlDTO { title: string htmlTitle: string language: string