https://kotlinlang.org logo
Title
j

jk

08/14/2017, 2:08 PM
can you show the code for
missingParamError
and
incorrectPassword
, and what the similarity/differences between them are?
d

davidase

08/14/2017, 2:10 PM
object Errors {
    fun missingParam(req: Request, res: Response)
            = generalError(req, res, 400, "missing-param")

    fun invalidPhone(req: Request, res: Response)
            = generalError(req, res, 400, "invalid-phone")

    fun incorrectPin(req: Request, res: Response)
            = generalError(req, res, 400, "incorrect-pin")

    fun badRequest(req: Request, res: Response)
            = generalError(req, res, 400, "general-error")
}

fun generalError(req: Request, res: Response, status: Int, error: String): String {
    return res.redirectTo(req.pathInfo() + "?" + error)
}
(there is a bit more stuff in
generalError()
, logging etc)
j

jk

08/14/2017, 2:19 PM
where do
request
, and
response
come from when you call
missingParamError(request, response)
? Is there an enclosing class you can make the receiver?
d

davidase

08/14/2017, 2:20 PM
i just have simple functions on an object, like
object Controller {
    fun verifyPhone(req: Request, res: Response): String {
        ...
    }
}
j

jk

08/14/2017, 2:22 PM
as @poohbar mentioned, you won't have access to
Request
or
Response
without using a closure, but then you will lose the reusability so wouldn't be any use to you
d

davidase

08/14/2017, 2:23 PM
yeah
thanks for having a look
j

jk

08/14/2017, 2:36 PM
the closest I got is by refactoring so that you can pass the Request/Response pair as a receiver:
data class ReqResp(val req: Request, val res: Response)

fun verifyPhone(req: Request, res: Response) {
    handle(req, res) {
        // do your handling code
        // else
        error("missing-param")
    }
}

fun handle(req: Request, res: Response, handle:ReqResp.() -> Unit) {
    ReqResp(req, res).handle()
}

fun ReqResp.error(error: String) {
    res.redirectTo(req.pathInfo() + "?" + error)
}
d

davidase

08/15/2017, 7:32 AM
pretty neat, but the extra abstraction will probably confuse some people
j

jk

08/15/2017, 8:41 AM
yes, agreed - if you could arrange it so people could only write
handle
functions it might be more palatable