article banner

Exercise: CommentService

Implement the following functions from the CommentService class:

  • addComment - should read a user id from a token, transform the body to a CommentDocument, and add it to the comment repository.
  • getComments - should get comments with users and return them as a collection.
class CommentService( private val commentRepository: CommentRepository, private val userService: UserService, private val commentFactory: CommentFactory ) { suspend fun addComment( token: String, collectionKey: String, body: AddComment ) { TODO() } suspend fun getComments( collectionKey: String ): CommentsCollection = TODO() }

This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in coroutines/comment/CommentService.kt. You can find there starting code.

You can assume that findUserById from userService can be called multiple times for the same user id because it is cached. Alternatively, you can refactor this service to make sure it is not called more than once for the same id by the same getComments call. The second option is more complex.

Once you are done with the exercise, you can check your solution here.

Playground

import domain.comment.* import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope class CommentService( private val commentRepository: CommentRepository, private val userService: UserService, private val commentFactory: CommentFactory ) { suspend fun addComment( token: String, collectionKey: String, body: AddComment ) { TODO() } suspend fun getComments( collectionKey: String ): CommentsCollection = TODO() }