Created
May 14, 2019 12:08
-
-
Save linktohack/47a2c1460807848763cd89e0cb529416 to your computer and use it in GitHub Desktop.
Fable (2.2+) interop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Program | |
open System.Text.RegularExpressions | |
open Fable.Core | |
open Fable.Core.JS | |
open Fable.Core.JsInterop | |
module Process = | |
type IEnv = | |
abstract PORT: string option | |
type Process = | |
abstract env: IEnv | |
module Express = | |
type IReq = interface end | |
type ISend = string | |
type IRes = | |
abstract send: ISend -> unit | |
abstract setHeader: string -> string -> unit | |
type INext = unit -> unit | |
type IHandler = IReq -> IRes -> INext -> unit | |
type IApp = interface end | |
module App = | |
[<Emit "$2.get($0, $1)">] | |
let get (path: U2<string, Regex>) (handler: IHandler) (app: IApp): IApp = jsNative | |
[<Emit "$2.post($0, $1)">] | |
let post (path: U2<string, Regex>) (handler: IHandler) (app: IApp): IApp = jsNative | |
[<Emit "$2.put($0, $1)">] | |
let put (path: U2<string, Regex>) (handler: IHandler) (app: IApp): IApp = jsNative | |
[<Emit "$2.listen($0, $1)">] | |
let listen (port: int) (handler: unit -> unit) (app: IApp): IApp = jsNative | |
type ExpressStatic = | |
[<Emit "$0()">] | |
abstract Create: unit -> IApp | |
// PORT | |
let Process: Process.Process = importDefault "process" | |
let port = | |
match Process.env.PORT |> Option.map System.Int32.TryParse with | |
| Some(true, i) -> i | |
| _ -> 8080 | |
// EXPRESS | |
open Express | |
let Express: ExpressStatic = importDefault "express" | |
Express.Create() | |
|> App.get (U2.Case1 "/hello") | |
(fun _ res _ -> | |
res.setHeader "content-type" "application/json" | |
res.send "{ \"message\": \"ok from hello\" }") | |
|> App.get (U2.Case2(RegExp.Create "/[0-9]*")) | |
(fun _ res _ -> | |
res.setHeader "content-type" "application/json" | |
res.send "{ \"message\": \"ok from number\" }") | |
|> App.get (U2.Case1 "/:id") | |
(fun req res _ -> res.send req?``params``) | |
|> App.listen port | |
(fun () -> printf "app listen on port: %d" port) | |
|> ignore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment