簡體   English   中英

長頸鹿路由異步 function

[英]giraffe routef async function

我一直在使用 f# 創建 Giraffe api 服務器,並且一直很高興地使用route功能:

type Person = { id: BsonObjectId; name: string; age: int; }

let getPeople (databaseFn: unit-> IMongoDatabase) : HttpHandler =
    fun (next : HttpFunc) (ctx : HttpContext) -> 
        let database = databaseFn()
        let collection = database.GetCollection<Person> "people"
        task {
            let! cursor = collection.FindAsync<Person>(fun p -> true)
            let! hasMoved = cursor.MoveNextAsync()
            let result = 
                match hasMoved with
                | true -> json cursor.Current next ctx
                | false -> 
                    let message = { message = "No People found" }
                    RequestErrors.notFound (json message) next ctx
            return! result
        }

let savePerson (databaseFn: unit -> IMongoDatabase ) : HttpHandler =
    fun (next : HttpFunc) (ctx : HttpContext) -> 
        let database = databaseFn()
        let collection = database.GetCollection<Person> "people"
        task {
            let serialiser = ctx.GetJsonSerializer()
            let! person = ctx.BindJsonAsync<Person>()
            let personWithId = { person with id = BsonObjectId ( ObjectId.GenerateNewId() ) }
            do! collection.InsertOneAsync(personWithId)
            return! text "nailed it" next ctx
        }

let deletePerson (databaseFn: unit -> IMongoDatabase ) = 
    fun (id: string) -> 
        let database = databaseFn()
        let collection = database.GetCollection<Person> "people"
        task {
            let oId = BsonObjectId (ObjectId id) 
            let! result = collection.FindOneAndDeleteAsync<Person>(fun p -> p.id = oId)
            return text "awesomesauce"
        }

let personHandler getPeople savePerson deletePerson = 
    let path = "/people"
    choose [
        GET >=> choose [
            route path >=> getPeople
        ]
        POST >=> choose [
            route path >=> savePerson
        ]
        DELETE >=> choose [
            routef "/people/%s" >=> deletePerson
        ]
    ]

但我已經添加了deletePerson處理程序,但它現在抱怨

routef "/people/%s" >=> deletePerson

“HttpFuncResult”類型與“HttpHandler”類型不匹配

我知道類型不匹配,但是當我這樣使用它時

routef "/people/%s" deletePerson

它抱怨deletePerson function 返回System.Threading.Tasks.Task<(HttpFunc -> HttpContext -> HttpFuncResult)>而不是HttpHandler

我只是不確定我如何擁有一個可以從路由參數中獲取值並在一個routef中有一個異步 HttpHandler 的 routef?

我沒有導入所有類型來編譯整個東西,但我認為你需要從刪除中刪除>=>

DELETE >=> choose [
   (routef "/people/%s" deletePerson)
]

deletePerson 簽名將是:

let deletePerson (databaseFn: unit -> IMongoDatabase ) (id: string) : HttpHandler = 
    fun (next : HttpFunc) (ctx : HttpContext) -> 
        let database = databaseFn()
        //etc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM