-
Notifications
You must be signed in to change notification settings - Fork 9
/
PutExample.elm
105 lines (88 loc) · 2.43 KB
/
PutExample.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
module PutExample exposing (..)
{-| This module is an example of the Pouchdb put task. It succeeds at first insertion, and fails on the second insertion which is normal because we are not using rev. As an exercise you could change the code to be able to do updates of the inserted document.
Have Fun!
-}
import Pouchdb exposing (Pouchdb,auth, ajaxCache,dbOptions,db,request)
import Html exposing (..)
import String
import Html.Events exposing (onClick)
import Json.Encode as Encode exposing (object, Value)
import Task exposing (Task)
init : (Model, Cmd Message)
init =
let
model = initialModel
in
(model, Cmd.none)
type Message = PutButton
| Put (Result Pouchdb.Fail Pouchdb.Put)
type alias Model = { localDb : Pouchdb
, returnMsg : Maybe String
}
initialModel : Model
initialModel =
let
localDb = db "Put-Example" dbOptions
in
{
localDb = localDb
, returnMsg = Nothing
}
encoder : String->String->Encode.Value
encoder id val =
Encode.object
[ ("_id", Encode.string id)
, ("val", Encode.string val)
]
unpack : (e -> b) -> (a -> b) -> Result e a -> b
unpack errFunc okFunc result =
case result of
Ok ok ->
okFunc ok
Err err ->
errFunc err
update : Message -> Model -> (Model, Cmd Message)
update msg model =
case msg of
PutButton->
let
task = (Pouchdb.put model.localDb (encoder "id2" "hello") Nothing)
cmd = Task.attempt Put task
in
(model, cmd)
Put msg->
let
newMsg = unpack
(\m->String.append "Error putting in db with message = " m.message)
(\m->String.append "Successfully put in db with rev = " m.rev)
msg
in
({model|returnMsg=Just newMsg}, Cmd.none)
view : Model -> Html Message
view model =
div
[ ]
[ button [ onClick PutButton] [ text "Put"]
, viewMsg model
]
viewMsg model =
case model.returnMsg of
Just msg ->
div
[]
[text msg]
Nothing ->
div
[]
[text "No message yet!"]
subscriptions : Model -> Sub Message
subscriptions model =
Sub.none
main : Program Never Model Message
main =
Html.program
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}