restapi(6)- do it the functional way, 重温函数式编程

2024-04-09 04:38

本文主要是介绍restapi(6)- do it the functional way, 重温函数式编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  再次看了看上篇博客的源代码,发现连自己都看不懂了。想是为了赶时间交货不知不觉又回到OOP行令模式了,看看下面这段代码:

       (post &  parameters('pid,'desc.?,'width.as[Int].?,'heigth.as[Int].?)) { (pid, optDesc, optWid, optHgh) =>val futCount: Future[Int] = repository.count(pid).value.value.runToFuture.map {eoi =>eoi match {case Right(oi) => oi match {case Some(i) => icase None => -1}case Left(err) => -1}}val count: Int = Await.result(futCount, 2 seconds)var doc = Document("pid" -> pid,"seqno" -> count)if (optDesc != None)doc = doc + ("desc" -> optDesc.get)if (optWid != None)doc = doc + ("desc" -> optWid.get)if (optHgh != None)doc = doc + ("desc" -> optHgh.get)withoutSizeLimit {decodeRequest {extractDataBytes { bytes =>val fut = bytes.runFold(ByteString()) { case (hd, bs) =>hd ++ bs}onComplete(fut) {case Success(b) =>doc = doc + ("pic" -> b.toArray)val futmsg: Future[String] = repository.insert(doc).value.value.runToFuture.map {eoc =>eoc match {case Right(oc) => oc match {case Some(c) => count.toString //   c.toString()case None => "insert may not complete!"}case Left(err) => err.getMessage}}complete(futmsg)case Failure(err) => complete(err)}}}}

有人能从这段代码里理解它的功能吗?本来作者的目的很简单:前端通过httprequest提交了一张图片及产品编号pid、系统读取MongoDB查找相同pid的数量count,然后将图片和描述包括count写入数据库并在reponse里返回count。把一个简单功能的实现搞的这么复杂都是我的错,可能受OOP荼毒太深。这次希望静下心来用函数式编程模式把这段代码从新实现一次,示范一下函数式编程的代码精炼和高雅特点。首先介绍一下DBResult[A]这个类型:这是一个Monad,为了应付Future[Either[Option[R]]]这样的类型而设计的,是一个表现数据库操作比较全面的类型,但同时它又是造成上面这段代码混乱的元凶。现在我们可以用隐式转换implicit conversion方式进行代码简化重用:

  import monix.execution.Scheduler.Implicits.globalimplicit class DBResultToFuture(dbr: DBOResult[_]){def toFuture[R] = {dbr.value.value.runToFuture.map {eor =>eor match {case Right(or) => or match {case Some(r) => r.asInstanceOf[R]case None => throw new RuntimeException("Operation produced None result!")}case Left(err) => throw new RuntimeException(err)}}}}

用这个隐式转换类型为任何DBOResult[R]增加一个函数toFuture[R]。现在整个futCount算式可以简化成下面这样:

          val futCount: Future[Int] = repository.count(pid).value.value.runToFuture.map {eoi =>eoi match {case Right(oi) => oi match {case Some(i) => icase None => -1}case Left(err) => -1}}futCount:Future[Int]=repository.count(pid).toFuture

真正的简单易明。

不知怎么搞的,我尽然在这段代码中间使用了Await.result。从OOP角度分析这很容易理解,下一段程序需要上一段程序的结果来继续运行。在上面的例子里我们需要先获取count然后把count塞进Document再把Document存入数据库。逻辑思路上没问题,不过这样的做法是典型的行令式编程模式。在函数式编程模式里,阶段性的运算结果是在包嵌在Monad中的。Monad本身只是一个运算计划,只有真正运算时才能获取结果。Monad本身是函数组件,可以实现多个Monad的函数组合。在这里可以形象的把Monad函数组合描述为数据库操作步骤:先count、再insert,这两个步骤产生的结果还是留在Monad里的,直到所谓的世界末日,即实际运算完成后才取出,所以Monad是一种典型的程序运算流程管道。假如我们再把insert这段程序写成addPicture(...): DBOResult[_], 如下:

   def addPicuture(pid: String,seqno: Int, optDesc: Option[String],optWid:Option[Int],optHgh:Option[Int],bytes: Array[Byte]):DBOResult[Completed] ={var doc = Document("pid" -> pid,"seqno" -> seqno,"pic" -> bytes)if (optDesc != None)doc = doc + ("desc" -> optDesc.get)if (optWid != None)doc = doc + ("desc" -> optWid.get)if (optHgh != None)doc = doc + ("desc" -> optHgh.get)repository.insert(doc)}

现在我可以把代码简化成:

                val futSeqno = for {cnt <- repository.count(pid).toFuture_ <- addPicuture(pid, cnt, optDesc, optWid, optHgh, barr.toArray).toFuture} yield cnt

好了,现在整篇代码变成了下面这样:

       (post &  parameters('pid,'desc.?,'width.as[Int].?,'heigth.as[Int].?)) { (pid, optDesc, optWid, optHgh) =>withoutSizeLimit {decodeRequest {extractDataBytes { bytes =>val futBytes = bytes.runFold(ByteString()) { case (hd, bs) =>hd ++ bs}val futSeqno = for {cnt <- repository.count(pid).toFuturebarr <- futBytes_ <- addPicuture(pid, cnt, optDesc, optWid, optHgh, barr.toArray).toFuture} yield cntcomplete(futSeqno.map(_.toString))}}

现在是不是变得简单易明了?如果你觉着这样看起来更加容易理解,那么我建议你现在开始多点接触了解函数式编程。

接着用同样方式把整个项目重新实现一次。修改后的源代码如下:

MongoRepo.scala

package com.datatech.rest.mongo
import org.mongodb.scala._
import org.bson.conversions.Bson
import org.mongodb.scala.result._
import com.datatech.sdp.mongo.engine._
import MGOClasses._
import MGOEngine._
import MGOCommands._
import com.datatech.sdp.result.DBOResult.DBOResultobject MongoRepo {class MongoRepo[R](db:String, coll: String, converter: Option[Document => R])(implicit client: MongoClient) {def getAll[R](next:Option[String],sort:Option[String],fields:Option[String],top:Option[Int]): DBOResult[Seq[R]] = {var res = Seq[ResultOptions]()next.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_FILTER,Some(Document(b)))}sort.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_SORT,Some(Document(b)))}fields.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_PROJECTION,Some(Document(b)))}top.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_LIMIT,None,b)}val ctxFind = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_QUERY).setCommand(Find(andThen = res))mgoQuery[Seq[R]](ctxFind,converter)}def query[R](filtr: Bson, next:Option[String]=None,sort:Option[String]=None,fields:Option[String]=None,top:Option[Int]=None): DBOResult[Seq[R]] = {var res = Seq[ResultOptions]()next.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_FILTER,Some(Document(b)))}sort.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_SORT,Some(Document(b)))}fields.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_PROJECTION,Some(Document(b)))}top.foreach {b => res = res :+ ResultOptions(FOD_TYPE.FOD_LIMIT,None,b)}val ctxFind = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_QUERY).setCommand(Find(filter = Some(filtr),andThen = res))mgoQuery[Seq[R]](ctxFind,converter)}import org.mongodb.scala.model.Filters._def count(pid: String):DBOResult[Int] = {val ctxCount = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_QUERY).setCommand(Count(filter=Some(equal("pid",pid))))mgoQuery[Int](ctxCount,None)}def getOneDocument(filtr: Bson): DBOResult[Document] = {val ctxFind = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_QUERY).setCommand(Find(filter = Some(filtr),firstOnly = true))mgoQuery[Document](ctxFind,None)}def getOnePicture[R](pid: String, seqno: Int): DBOResult[R] = {val ctxFind = MGOContext(dbName = db, collName = coll).setActionType(MGO_ACTION_TYPE.MGO_QUERY).setCommand(Find(filter = Some(and(equal("pid",pid),equal("seqno",seqno))), firstOnly = true))mgoQuery[R](ctxFind, converter)}def insert(doc: Document): DBOResult[Completed] = {val ctxInsert = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_UPDATE).setCommand(Insert(Seq(doc)))mgoUpdate[Completed](ctxInsert)}def delete(filter: Bson): DBOResult[DeleteResult] = {val ctxDelete = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_UPDATE).setCommand(Delete(filter))mgoUpdate[DeleteResult](ctxDelete)}def update(filter: Bson, update: Bson, many: Boolean): DBOResult[UpdateResult] = {val ctxUpdate = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_UPDATE).setCommand(Update(filter,update,None,!many))mgoUpdate[UpdateResult](ctxUpdate)}def replace(filter: Bson, row: Document): DBOResult[UpdateResult] = {val ctxUpdate = MGOContext(dbName = db,collName=coll).setActionType(MGO_ACTION_TYPE.MGO_UPDATE).setCommand(Replace(filter,row))mgoUpdate[UpdateResult](ctxUpdate)}}import monix.execution.Scheduler.Implicits.globalimplicit class DBResultToFuture(dbr: DBOResult[_]){def toFuture[R] = {dbr.value.value.runToFuture.map {eor =>eor match {case Right(or) => or match {case Some(r) => r.asInstanceOf[R]case None => throw new RuntimeException("Operation produced None result!")}case Left(err) => throw new RuntimeException(err)}}}}}

MongoRoute.scala

package com.datatech.rest.mongo
import akka.http.scaladsl.server.Directives
import com.datatech.sdp.file._import scala.util._
import org.mongodb.scala._
import com.datatech.sdp.file.Streaming._
import org.mongodb.scala.result._
import MongoRepo._
import akka.stream.ActorMaterializer
import com.datatech.sdp.result.DBOResult._
import org.mongodb.scala.model.Filters._
import com.datatech.sdp.mongo.engine.MGOClasses._
import monix.execution.CancelableFuture
import akka.util._
import akka.http.scaladsl.model._
import akka.http.scaladsl.coding.Gzip
import akka.stream.scaladsl._
import MongoModels.WebPicimport scala.concurrent._
import scala.concurrent.duration._
object MongoRoute {class MongoRoute[M <: ModelBase[Document]](val pathName: String)(repository: MongoRepo[M])(implicit c: MongoClient, m: Manifest[M], mat: ActorMaterializer) extends Directives with JsonConverter {import monix.execution.Scheduler.Implicits.globalvar dbor: DBOResult[Seq[M]] = _var dbou: DBOResult[UpdateResult] = _val route = pathPrefix(pathName) {pathPrefix("pictures") {(post &  parameters('pid,'desc.?,'width.as[Int].?,'heigth.as[Int].?)) { (pid, optDesc, optWid, optHgh) =>withoutSizeLimit {decodeRequest {extractDataBytes { bytes =>val futBytes = bytes.runFold(ByteString()) { case (hd, bs) =>hd ++ bs}val futSeqno = for {cnt <- repository.count(pid).toFuture[Int]barr <- futBytes_ <- addPicuture(pid, cnt, optDesc, optWid, optHgh, barr.toArray).toFuture[Completed]} yield cntcomplete(futSeqno.map(_.toString))}}} ~(get & parameters('pid, 'seqno.as[Int].?, 'width.as[Int].?, 'height.as[Int].?)) {(pid, optSeq, optWid, optHght) =>if (optSeq == None) {val futRows = repository.query(equal("pid", pid)).toFuturecomplete(futureToJson(futRows))} else {val futPicRow = repository.getOnePicture(pid, optSeq.get).toFuture[WebPic]onComplete(futPicRow) {case Success(row) =>val width = if (optWid == None) row.width.getOrElse(128) else optWid.getOrElse(128)val height = if (optHght == None) row.heigth.getOrElse(128) else optHght.getOrElse(128)if (row.pic != None) {withoutSizeLimit {encodeResponseWith(Gzip) {complete(HttpEntity(ContentTypes.`application/octet-stream`,ByteArrayToSource(Imaging.setImageSize(row.pic.get.getData, width, height))))}}} else complete(StatusCodes.NotFound)case Failure(err) => complete(err)}}}}} ~pathPrefix("blob") {(get & parameter('filter)) { filter =>val filtr = Document(filter)val futOptPic: CancelableFuture[Option[MGOBlob]] = repository.getOneDocument(filtr).toFutureonComplete(futOptPic) {case Success(optBlob) => optBlob match {case Some(blob) =>withoutSizeLimit {encodeResponseWith(Gzip) {complete(HttpEntity(ContentTypes.`application/octet-stream`,ByteArrayToSource(blob.getData)))}}case None => complete(StatusCodes.NotFound)}case Failure(err) => complete(err)}} ~(post &  parameter('bson)) { bson =>val bdoc = Document(bson)withoutSizeLimit {decodeRequest {extractDataBytes { bytes =>val futbytes = bytes.runFold(ByteString()) { case (hd, bs) =>hd ++ bs}val futmsg:Future[Completed] = for {bytes <- futbytesdoc = Document(bson) + ("photo" -> bytes.toArray)c <- repository.insert(doc).toFuture[Completed]} yield ccomplete(futmsg.map(_.toString))}}}}} ~(get & parameters('filter.?,'fields.?,'sort.?,'top.as[Int].?,'next.?)) {(filter,fields,sort,top,next) => {dbor = {filter match {case Some(fltr) => repository.query(Document(fltr),next,sort,fields,top)case None => repository.getAll(next,sort,fields,top)}}val futRows:Future[Seq[WebPic]] = dbor.toFuture[Seq[WebPic]]complete(futureToJson(futRows))}} ~ post {entity(as[String]) { json =>val extractedEntity: M = fromJson[M](json)val doc: Document = extractedEntity.toval futmsg = repository.insert(doc).toFuture[Completed]complete(futmsg.map(_.toString))}} ~ (put & parameter('filter,'set.?, 'many.as[Boolean].?)) { (filter, set, many) =>val bson = Document(filter)if (set == None) {entity(as[String]) { json =>val extractedEntity: M = fromJson[M](json)val doc: Document = extractedEntity.toval futmsg = repository.replace(bson, doc).toFuturecomplete(futureToJson(futmsg))}} else {set match {case Some(u) =>val ubson = Document(u)dbou = repository.update(bson, ubson, many.getOrElse(true))case None =>dbou = Left(new IllegalArgumentException("missing set statement for update!"))}val futmsg:Future[UpdateResult] = dbou.toFuture[UpdateResult]complete(futureToJson(futmsg.map(_.toString)))}} ~ (delete & parameters('filter, 'many.as[Boolean].?)) { (filter,many) =>val bson = Document(filter)val futmsg:Future[DeleteResult] = repository.delete(bson).toFuture[DeleteResult]complete(futureToJson(futmsg.map(_.toString)))}}def addPicuture(pid: String,seqno: Int, optDesc: Option[String],optWid:Option[Int],optHgh:Option[Int],bytes: Array[Byte]):DBOResult[Completed] ={var doc = Document("pid" -> pid,"seqno" -> seqno,"pic" -> bytes)if (optDesc != None)doc = doc + ("desc" -> optDesc.get)if (optWid != None)doc = doc + ("desc" -> optWid.get)if (optHgh != None)doc = doc + ("desc" -> optHgh.get)repository.insert(doc)}}}

 

这篇关于restapi(6)- do it the functional way, 重温函数式编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/887192

相关文章

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

kotlin的函数forEach示例详解

《kotlin的函数forEach示例详解》在Kotlin中,forEach是一个高阶函数,用于遍历集合中的每个元素并对其执行指定的操作,它的核心特点是简洁、函数式,适用于需要遍历集合且无需返回值的场... 目录一、基本用法1️⃣ 遍历集合2️⃣ 遍历数组3️⃣ 遍历 Map二、与 for 循环的区别三、高

C语言字符函数和字符串函数示例详解

《C语言字符函数和字符串函数示例详解》本文详细介绍了C语言中字符分类函数、字符转换函数及字符串操作函数的使用方法,并通过示例代码展示了如何实现这些功能,通过这些内容,读者可以深入理解并掌握C语言中的字... 目录一、字符分类函数二、字符转换函数三、strlen的使用和模拟实现3.1strlen函数3.2st

MySQL中COALESCE函数示例详解

《MySQL中COALESCE函数示例详解》COALESCE是一个功能强大且常用的SQL函数,主要用来处理NULL值和实现灵活的值选择策略,能够使查询逻辑更清晰、简洁,:本文主要介绍MySQL中C... 目录语法示例1. 替换 NULL 值2. 用于字段默认值3. 多列优先级4. 结合聚合函数注意事项总结C