简体   繁体   中英

Combining/chaining futures in scala play framework async action

I'm a scala newbie trying to write a Rest Api using play framework. I have the following 3 data access methods

getDataDict: (dsType:String, name:String) => Future[Option[DatasetDictionary]]
getDatasetData: (DatasetDictionary) => Future[List[DatasetData]]
getMetadata: (DatasetDictionary) => Future[List[Metadata]]

I need to use these 3 methods to get the result of my async action method.

 def index(dstype:String, name:String, metadata:Option[Boolean]) = Action.async{   
  /*
     1. val result = getDataDict(type, name)
     2. If result is Some(d) call getDatasetData
     3.1 if metadata = Some(true)
          call getMetadata function
          return Ok((dict, result, metadata))
     3.2 if metadata is None or Some(false)
          return Ok(result)
     4. If result is None
               return BadRequest("Dataset not found")
 */  
}

I got the steps 1 and 2 working as follows

def index1(dsType:String, dsName: String, metadata:Option[Boolean]) = Action.async {
    getDataDict(dsType, dsName) flatMap {
        case Some(x) => getDatasetData(x) map (x => Ok(Json.toJson(x)))
        case None => Future.successful(BadRequest("Dataset not found"))
      }
}

I'm stuck at how to get the metadata part working.

First of all, it is not very clear (d, result, x) what you really want to return. Hopefully I guessed it correctly:

 def index(dstype:String, name:String, metadata:Option[Boolean]) = Action.async {
    getDataDict(dstype, name) flatMap {
      case Some(datasetDictionary) =>
        getDatasetData(datasetDictionary) flatMap { datasetDataList =>
          if (metadata == Some(true)) {
            getMetadata(datasetDictionary) map { metadataList =>
              Ok(Json.toJson((datasetDictionary, datasetDataList, metadataList)))
            }
          } else {
            Future.successful(Ok(Json.toJson(datasetDataList)))
          }
        }
      case None => Future.successful(BadRequest("Dataset not found"))
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM