Skip to content

Instantly share code, notes, and snippets.

@pakoito
Forked from m-debugger/is there better way
Created October 31, 2018 23:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pakoito/f811e16628b2b6f6060dc34db4274cf4 to your computer and use it in GitHub Desktop.
Save pakoito/f811e16628b2b6f6060dc34db4274cf4 to your computer and use it in GitHub Desktop.
when (info) {
null -> {
return unauthorized()
}
else -> {
val validInfo = validator.validateInfo(info)
when (validInfo) {
is Either.Right -> {
if (!validInfo.b.authorised) {
// authorised is false so return unauthorised
return unauthorized()
}
// authorised is true, so use the authorised token to create a certificate
val authorisedInfo = validInfo.b
val productService = productServiceBuilder.buildProductService(authorisedInfo)
// TODO add when (productService) here
//
return when (productService) {
is Either.Right -> {
val product = productService.b.getProduct(
authorisedInfo.userId!!)
APIGatewayProxyResponseEvent()
.withBody(jacksonObjectMapper().writeValueAsString(product))
.withStatusCode(200)
}
is Either.Left -> {
systemError()
}
}
}
is Either.Left -> {
return systemError()
}
}
}
}
@pakoito
Copy link
Author

pakoito commented Oct 31, 2018

Using fluent chains:

info
  .toOption()
  .toEither { unauthorized() }
  .flatMap {
    validator.validateInfo(it)
      .mapLeft { systemError() }
  }.flatMap { authorisedInfo ->
    if (!authorisedInfo.authorised) {
      unauthorized().left()
    } else {
      productServiceBuilder.buildProductService(it).flatMap {
        Either.monadError<Throwable>().catch { 
           val product = it.getProduct(authorisedInfo.userId!!)
           APIGatewayProxyResponseEvent()
             .withBody(jacksonObjectMapper().writeValueAsString(product))
             .withStatusCode(200)
        } 
      }.mapLeft {
        systemError()
      }
    } // else
} // flatMap

@pakoito
Copy link
Author

pakoito commented Oct 31, 2018

Using comprehensions:

Either.monadError<Throwable>().bindingCatch {
  val goodInfo = info.toOption().toEither { unauthorized() }.bind()
  val validInfo = validator.validateInfo(goodInfo).mapLeft { systemError() }.bind()
  val result = if (!validInfo.authorised) {
    unauthorized().left()
  } else {
    catch {
      val productService = productServiceBuilder.buildProductService(validInfo).bind()
      val product = productService.getProduct(validInfo.userId!!).bind()
      APIGatewayProxyResponseEvent()
        .withBody(jacksonObjectMapper().writeValueAsString(product))
        .withStatusCode(200)
    }.mapLeft {
      systemError()
    }
  }
  result.bind()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment