/
goals.go
82 lines (73 loc) · 2.48 KB
/
goals.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
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/encoder"
"github.com/nu7hatch/gouuid"
)
type Goal struct {
Id string `json:"id"`
Type string `json:"type" binding:"required"`
Target string `json:"target" binding:"required"`
TargetType string `json:"target_type"`
Start int `json:"start"`
Length int `json:"length" binding:"required"`
Name string `json:"name" binding:"required"`
Content string `json:"content" binding:"required"`
Keywords string `json:"keywords" binding:"required"`
ActiveAfter string `json:"active_after"`
Reward string `json:"reward" binding:"required"`
Difficulty int `json:"difficulty" binding:"required"`
NumberOfCompletions int `json:"number_of_completions" binding:"required"`
State string `json:"state"`
}
type GoalCompleteParams struct {
UserId string `json:"user_id" binding:"required"`
}
var goals = make(map[string]*Goal)
func CreateGoal(enc encoder.Encoder, goal Goal) (int, []byte) {
goalId, err := uuid.NewV4()
if err != nil {
return 500, encoder.Must(enc.Encode(""))
}
goal.Id = goalId.String()
if goal.TargetType == "user" {
user, ok := users[goal.Target]
if !ok {
return 400, encoder.Must(enc.Encode("Target does not exist"))
}
user.Goals[goal.Id] = &goal
} else if goal.TargetType == "team" {
team, ok := teams[goal.Target]
if !ok {
return 400, encoder.Must(enc.Encode("Target does not exist"))
}
team.Goals[goal.Id] = &goal
} else {
return 400, encoder.Must(enc.Encode("Unknown target type"))
}
goals[goal.Id] = &goal
return 201, encoder.Must(enc.Encode(goal.Id))
}
func GetGoal(enc encoder.Encoder, params martini.Params) (int, []byte) {
goal, ok := goals[params["id"]]
if ok {
return 200, encoder.Must(enc.Encode(goal))
}
return 404, encoder.Must(enc.Encode())
}
func CompleteGoal(enc encoder.Encoder, params martini.Params, jsonParams GoalCompleteParams) (int, []byte) {
goal, ok := goals[params["id"]]
if !ok {
return 404, encoder.Must(enc.Encode())
}
if _, ok := users[jsonParams.UserId]; !ok {
return 400, encoder.Must(enc.Encode("User does not exist"))
}
goal.NumberOfCompletions--
if goal.NumberOfCompletions > 0 {
goal.State = "progress"
return 200, encoder.Must(enc.Encode(goal.State)) //what should be returned here?
}
goal.State = "completed"
return 200, encoder.Must(enc.Encode(goal.Reward))
}