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

相关文章

hdu1171(母函数或多重背包)

题意:把物品分成两份,使得价值最接近 可以用背包,或者是母函数来解,母函数(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v) 其中指数为价值,每一项的数目为(该物品数+1)个 代码如下: #include<iostream>#include<algorithm>

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【编程底层思考】垃圾收集机制,GC算法,垃圾收集器类型概述

Java的垃圾收集(Garbage Collection,GC)机制是Java语言的一大特色,它负责自动管理内存的回收,释放不再使用的对象所占用的内存。以下是对Java垃圾收集机制的详细介绍: 一、垃圾收集机制概述: 对象存活判断:垃圾收集器定期检查堆内存中的对象,判断哪些对象是“垃圾”,即不再被任何引用链直接或间接引用的对象。内存回收:将判断为垃圾的对象占用的内存进行回收,以便重新使用。

C++操作符重载实例(独立函数)

C++操作符重载实例,我们把坐标值CVector的加法进行重载,计算c3=c1+c2时,也就是计算x3=x1+x2,y3=y1+y2,今天我们以独立函数的方式重载操作符+(加号),以下是C++代码: c1802.cpp源代码: D:\YcjWork\CppTour>vim c1802.cpp #include <iostream>using namespace std;/*** 以独立函数

Go Playground 在线编程环境

For all examples in this and the next chapter, we will use Go Playground. Go Playground represents a web service that can run programs written in Go. It can be opened in a web browser using the follow

深入理解RxJava:响应式编程的现代方式

在当今的软件开发世界中,异步编程和事件驱动的架构变得越来越重要。RxJava,作为响应式编程(Reactive Programming)的一个流行库,为Java和Android开发者提供了一种强大的方式来处理异步任务和事件流。本文将深入探讨RxJava的核心概念、优势以及如何在实际项目中应用它。 文章目录 💯 什么是RxJava?💯 响应式编程的优势💯 RxJava的核心概念

函数式编程思想

我们经常会用到各种各样的编程思想,例如面向过程、面向对象。不过笔者在该博客简单介绍一下函数式编程思想. 如果对函数式编程思想进行概括,就是f(x) = na(x) , y=uf(x)…至于其他的编程思想,可能是y=a(x)+b(x)+c(x)…,也有可能是y=f(x)=f(x)/a + f(x)/b+f(x)/c… 面向过程的指令式编程 面向过程,简单理解就是y=a(x)+b(x)+c(x)

Java并发编程之——BlockingQueue(队列)

一、什么是BlockingQueue BlockingQueue即阻塞队列,从阻塞这个词可以看出,在某些情况下对阻塞队列的访问可能会造成阻塞。被阻塞的情况主要有如下两种: 1. 当队列满了的时候进行入队列操作2. 当队列空了的时候进行出队列操作123 因此,当一个线程试图对一个已经满了的队列进行入队列操作时,它将会被阻塞,除非有另一个线程做了出队列操作;同样,当一个线程试图对一个空

利用matlab bar函数绘制较为复杂的柱状图,并在图中进行适当标注

示例代码和结果如下:小疑问:如何自动选择合适的坐标位置对柱状图的数值大小进行标注?😂 clear; close all;x = 1:3;aa=[28.6321521955954 26.2453660695847 21.69102348512086.93747104431360 6.25442246899816 3.342835958564245.51365061796319 4.87