-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaction.go
93 lines (83 loc) · 2.11 KB
/
action.go
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
package fedwiki
import (
"fmt"
"time"
)
// Action represents a operation that can be applied to a fedwiki.Page
type Action map[string]interface{}
// Str returns string value by the key
// if that key doesn't exist, it will return an empty string
func (action Action) Str(key string) string {
if s, ok := action[key].(string); ok {
return s
}
return ""
}
// Type returns the action type attribute
func (action Action) Type() string {
return action.Str("type")
}
// Item returns the item attribute
func (action Action) Item() (Item, bool) {
item, ok := action["item"]
if !ok {
return nil, false
}
m, ismap := (item).(map[string]interface{})
if !ismap {
return nil, false
}
return (Item)(m), true
}
// Date returns the time when the action occurred
func (action Action) Date() (t Date, err error) {
val, ok := action["date"]
if !ok {
return Date{time.Unix(0, 0)}, fmt.Errorf("date not found")
}
switch val := val.(type) {
case string:
t, err := time.Parse(time.RFC3339, val)
return Date{t}, err
case int: // assume date
return Date{time.Unix(int64(val), 0)}, nil
case int64: // assume date
return Date{time.Unix(val, 0)}, nil
}
return Date{time.Unix(0, 0)}, fmt.Errorf("unknown date format")
}
// actionfns defines how each action type is applied
var actionfns = map[string]func(p *Page, a Action) error{
"add": func(p *Page, action Action) error {
item, ok := action.Item()
if !ok {
return fmt.Errorf("no item in action")
}
after := action.Str("after")
if after == "" {
p.Story.Append(item)
return nil
}
return p.Story.InsertAfter(after, item)
},
"edit": func(p *Page, action Action) error {
item, ok := action.Item()
if !ok {
return fmt.Errorf("no item in action")
}
return p.Story.SetByID(action.Str("id"), item)
},
"remove": func(p *Page, action Action) error {
_, err := p.Story.RemoveByID(action.Str("id"))
return err
},
"move": func(p *Page, action Action) error {
return p.Story.Move(action.Str("id"), action.Str("after"))
},
"create": func(p *Page, action Action) error {
return nil
},
"fork": func(p *Page, action Action) error {
return nil
},
}