Scala 使用较少的样板文件(与非类型化世界交互)从Map(Play framework request.body.asFormUrlEncoded)转换为case类,反之亦然
这是一个具体的例子,尽管我在更一般的情况下遇到了这个问题 我正在研究Play2.3Web应用程序和自定义斜杠命令之间的集成。(注意:Slack有自定义斜杠命令API格式的文档,但我不相信我可以直接为注销的阅读器深度链接它们。) Slack将(当用户适当调用时)使用已知格式的标准表单URL编码正文发布到我的端点。他们的官方例子是:Scala 使用较少的样板文件(与非类型化世界交互)从Map(Play framework request.body.asFormUrlEncoded)转换为case类,反之亦然,scala,playframework,playframework-2.3,Scala,Playframework,Playframework 2.3,这是一个具体的例子,尽管我在更一般的情况下遇到了这个问题 我正在研究Play2.3Web应用程序和自定义斜杠命令之间的集成。(注意:Slack有自定义斜杠命令API格式的文档,但我不相信我可以直接为注销的阅读器深度链接它们。) Slack将(当用户适当调用时)使用已知格式的标准表单URL编码正文发布到我的端点。他们的官方例子是: token=KpADMkoKxZJRGKTG8kJoWXGC team_id=T0001 team_domain=example channel_id=C2147483
token=KpADMkoKxZJRGKTG8kJoWXGC
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
user_id=U2147483697
user_name=Steve
command=/weather
text=94070
在我的应用程序中,我用一个case类对这个请求进行建模
case class SlashCommand(
token: String,
teamId: String,
teamDomain: String,
channelId: String,
channelName: String,
userId: String,
userName: String,
command: String,
text: String
)
顺便问一下,除了使每个字段成为字符串
,还有什么方法可以更好地强制执行类型约束吗
我无法将表单URL编码的Play框架表示转换为case类。这是我目前拥有的代码,我相信它是正确的,但我觉得它过于重复
object SlashCommand {
def parseFromMap(in: Map[String, String]): Option[SlashCommand] = {
for {
token <- in.get("token")
teamId <- in.get("team_id")
teamDomain <- in.get("team_domain")
channelId <- in.get("channel_id")
channelName <- in.get("channel_name")
userId <- in.get("user_id")
userName <- in.get("user_name")
command <- in.get("command")
text <- in.get("text")
} yield SlashCommand(
token,
teamId,
teamDomain,
channelId,
channelName,
userId,
userName,
command,
text
)
}
def parseFromRequest(req: Request[AnyContent]): Option[SlashCommand] = {
req.body.asFormUrlEncoded.map { m =>
m.mapValues(_.last)
}.flatMap(parseFromMap)
}
}
对象SlashCommand{
def parseFromMap(in:Map[String,String]):Option[SlashCommand]={
为了{
tokenplay Forms API处理从请求
,将[String,String]
或JsValue
映射到您喜欢的类型(使用Form.bind
和Form.bindFromRequest
)的绑定,并且有一种声明式的方式来描述约束。所以您的编辑想法听起来很对
有关Play docs中表单API的更多信息:
最初对非用户输入使用表单处理是很奇怪的,但到目前为止,它似乎工作得很好。谢谢!