Search code examples
f#getsuave

Is that possible to create a class instance with webpart GET values


I created a "Game" class and i'm trying to use values from my webpart path to create an instance of it.

My instance need a playerName so i tried to create one with the name value

let g:game.Game = new game.Game()

let php =
request (fun r ->
    match r.queryParam "playerName" with
    | Choice1Of2 name ->  new game.Game(1,name,"hyy")//OK (sprintf "playerName: %s" name)
    | Choice2Of2 msg -> BAD_REQUEST msg)

let webPart = 
choose [
    path "/" >=> (OK "Home")
    path "/elm/api/create.php" >=> php
    ]
startWebServer defaultConfig webPart

but it doesn't work because this expression is supposed to be HttpContext type and not Game type.

I'd like to create an instance and call class's methods depending on my path values.


Solution

  • first: you cant return 2 different types from your function

    let php =
        request (fun r ->
            match r.queryParam "playerName" with
            | Choice1Of2 name ->  new game.Game(1,name,"hyy")
                                  ^^^^^^^^^^^
                                  //should probably be a OK 
            //OK (sprintf "playerName: %s" name)
            | Choice2Of2 msg -> BAD_REQUEST msg)
    

    Then you also should Jsonify your Game object. So probably your code should look somehow like this

    | Choice1Of2 name ->  
          new game.Game(1,name,"hyy")
          |> toJson
          |> OK
    

    please substitute toJson with a call of your chosen Json library