I have to log in to a server, send a file, then log out.
What do people do in this case? Log in, check the result, keep the session id, use it to send a file, use the session id to log out in a finally block. I mean, that's what I did all my life.
Tired of it.
So I want to log in, create a session, then, inside the session, do my operation, and then "automatically" close it. So I log in, and then call "execute". But wait, what if I don't call it? The resource will hang around.
So what I did, I inverse it. I say
client execute {operation} inSession(username, password)
. That's how it should be.
client.execute {
session => {
val response = session.send(fileInfo)
info(s"Attachment - $fileInfo sent: $response")
response
}
} inSession(username, password)
How does it work? Pretty easy:
def execute[T](op:ApiSession => Result[T]) = new {
def inSession(name:String, password:String): Result[T] = {
login(name, password) flatMap { s =>
try op(s) finally s.close
}
}
}
where
case class ApiSession(private val id: String, private val client: APIclient) {
def close() = client.get(s"logout?session=$id")
def send(fileInfo: FileInfo) = fileInfo.send(client)(id)
}
Client here is an http client that does all this multipart paraphernalia.
What I wanted to say is: the order of parameters is meaningful, is not it?
And pretty neat, too.