|
| 1 | +--- |
| 2 | +title: Getting started |
| 3 | +category: tutorial |
| 4 | +menu_order: 2 |
| 5 | +--- |
| 6 | + |
| 7 | +# Adding Saturn to an existing Giraffe application |
| 8 | + |
| 9 | +The previous chapter showed how to get started with a new application. |
| 10 | + |
| 11 | +If you already have a working Giraffe webserver, you can gradually opt-in to Saturn. |
| 12 | + |
| 13 | +For example, if your existing app looks like this: |
| 14 | + |
| 15 | +```f# |
| 16 | +
|
| 17 | +type Customer = { |
| 18 | + Name : string |
| 19 | + Address : string |
| 20 | +} |
| 21 | +
|
| 22 | +let customers = |
| 23 | + choose [ |
| 24 | + GET >=> (json { Name = "Mr. Smith"; Address = "Santa Monika"}) |
| 25 | + PUT >=> (bindJson<Customer> (fun customer -> printfn "Adding customer %A" customer; setStatusCode 200)) |
| 26 | + ] |
| 27 | +
|
| 28 | +
|
| 29 | +let webApp = |
| 30 | + choose [ |
| 31 | + route "/" >=> htmlFile "/pages/index.html" |
| 32 | + route "/api/customers" >=> customers |
| 33 | + ] |
| 34 | +``` |
| 35 | + |
| 36 | +and you need to add "vendor" functionality, you could implement it as a Saturn ``router`` while keeping everything else intact: |
| 37 | + |
| 38 | + |
| 39 | +```f# |
| 40 | +// the new Saturn router |
| 41 | +let vendors = router { |
| 42 | + getf "/%i" (fun vendorId -> (json (readVendorFromDb vendorId))) |
| 43 | + post "/" (bindJson<Vendor> (fun customer -> addVendor vendor; setStatusCode 200)) |
| 44 | +} |
| 45 | +
|
| 46 | +let webApp = |
| 47 | + choose [ |
| 48 | + route "/" >=> htmlFile "/pages/index.html" |
| 49 | + route "/api/customers" >=> customers |
| 50 | + // plug the new Saturn router into the Giraffe app |
| 51 | + route "/api/vendors" >=> vendors |
| 52 | + ] |
| 53 | +``` |
| 54 | + |
| 55 | +# Embedding Giraffe Handlers into Saturn |
| 56 | + |
| 57 | +Of course the other way around also works. |
| 58 | + |
| 59 | +For example, [Elmish.Bridge](https://github.com/Nhowka/Elmish.Bridge) does not provide a specialized implementation for Saturn. And it doesn't need to, because we can just use the Giraffe implementation! |
| 60 | + |
| 61 | +```f# |
| 62 | +
|
| 63 | +open Elmish |
| 64 | +open Elmish.Bridge |
| 65 | +
|
| 66 | +let elmishBridgeHandler : HttpHandler = |
| 67 | + Bridge.mkServer Shared.endpoint init update |
| 68 | + |> Bridge.run Giraffe.server |
| 69 | +
|
| 70 | +// our existing Saturn router |
| 71 | +let router = router { |
| 72 | +
|
| 73 | + // ... |
| 74 | +
|
| 75 | + forward "" elmishBridgeHandler |
| 76 | +} |
| 77 | +``` |
0 commit comments