onasty/web/src/Api/Note.elm (view raw)
| 1 | module Api.Note exposing (create, get, getMetadata) |
| 2 | |
| 3 | import Api |
| 4 | import Data.Note as Note exposing (CreateResponse, Metadata, Note) |
| 5 | import Effect exposing (Effect) |
| 6 | import Http |
| 7 | import Iso8601 |
| 8 | import Json.Encode as E |
| 9 | import Time exposing (Posix) |
| 10 | import Url |
| 11 | |
| 12 | |
| 13 | create : |
| 14 | { onResponse : Result Api.Error CreateResponse -> msg |
| 15 | , content : String |
| 16 | , slug : Maybe String |
| 17 | , password : Maybe String |
| 18 | , expiresAt : Posix |
| 19 | , burnBeforeExpiration : Bool |
| 20 | } |
| 21 | -> Effect msg |
| 22 | create options = |
| 23 | let |
| 24 | encodeMaybe : Maybe a -> b -> (a -> E.Value) -> ( b, E.Value ) |
| 25 | encodeMaybe maybeData field value = |
| 26 | case maybeData of |
| 27 | Just data -> |
| 28 | ( field, value data ) |
| 29 | |
| 30 | Nothing -> |
| 31 | ( field, E.null ) |
| 32 | |
| 33 | body : E.Value |
| 34 | body = |
| 35 | E.object |
| 36 | [ ( "content", E.string options.content ) |
| 37 | , encodeMaybe options.slug "slug" E.string |
| 38 | , encodeMaybe options.password "password" E.string |
| 39 | , ( "burn_before_expiration", E.bool options.burnBeforeExpiration ) |
| 40 | , if options.expiresAt == Time.millisToPosix 0 then |
| 41 | ( "expires_at", E.null ) |
| 42 | |
| 43 | else |
| 44 | ( "expires_at" |
| 45 | , options.expiresAt |
| 46 | |> Iso8601.fromTime |
| 47 | |> E.string |
| 48 | ) |
| 49 | ] |
| 50 | in |
| 51 | Effect.sendApiRequest |
| 52 | { endpoint = "/api/v1/note" |
| 53 | , method = "POST" |
| 54 | , body = Http.jsonBody body |
| 55 | , onResponse = options.onResponse |
| 56 | , decoder = Note.decodeCreateResponse |
| 57 | } |
| 58 | |
| 59 | |
| 60 | get : |
| 61 | { onResponse : Result Api.Error Note -> msg |
| 62 | , slug : String |
| 63 | , password : Maybe String |
| 64 | } |
| 65 | -> Effect msg |
| 66 | get options = |
| 67 | Effect.sendApiRequest |
| 68 | { endpoint = |
| 69 | "/api/v1/note/" |
| 70 | ++ options.slug |
| 71 | ++ (case options.password of |
| 72 | Just p -> |
| 73 | "?password=" ++ Url.percentEncode p |
| 74 | |
| 75 | Nothing -> |
| 76 | "" |
| 77 | ) |
| 78 | , method = "GET" |
| 79 | , body = Http.emptyBody |
| 80 | , onResponse = options.onResponse |
| 81 | , decoder = Note.decode |
| 82 | } |
| 83 | |
| 84 | |
| 85 | getMetadata : |
| 86 | { onResponse : Result Api.Error Metadata -> msg |
| 87 | , slug : String |
| 88 | } |
| 89 | -> Effect msg |
| 90 | getMetadata options = |
| 91 | Effect.sendApiRequest |
| 92 | { endpoint = "/api/v1/note/" ++ options.slug ++ "/meta" |
| 93 | , method = "GET" |
| 94 | , body = Http.emptyBody |
| 95 | , onResponse = options.onResponse |
| 96 | , decoder = Note.decodeMetadata |
| 97 | } |