/
contact.go
74 lines (56 loc) · 1.38 KB
/
contact.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
package models
import (
"fmt"
u "../utils"
"github.com/jinzhu/gorm"
)
//Contact ...
type Contact struct {
gorm.Model
Name string `json:"name"`
Phone string `json:"phone"`
UserID uint `json:"user_id"` //The user that this contact belongs to
}
// Validate ...
func (contact *Contact) Validate() (map[string]interface{}, bool) {
if contact.Name == "" {
return u.Message(false, "Contact name should be on the payload"), false
}
if contact.Phone == "" {
return u.Message(false, "Phone number should be on the payload"), false
}
if contact.UserID <= 0 {
return u.Message(false, "User is not recognized"), false
}
//All the required parameters are present
return u.Message(true, "success"), true
}
// Create ...
func (contact *Contact) Create() map[string]interface{} {
if resp, ok := contact.Validate(); !ok {
return resp
}
GetDB().Create(contact)
resp := u.Message(true, "success")
resp["contact"] = contact
return resp
}
//GetContact ...
func GetContact(id uint) *Contact {
contact := &Contact{}
err := GetDB().Table("contacts").Where("id = ?", id).First(contact).Error
if err != nil {
return nil
}
return contact
}
//GetContacts ...
func GetContacts(user uint) []*Contact {
contacts := make([]*Contact, 0)
err := GetDB().Table("contacts").Where("user_id = ?", user).Find(&contacts).Error
if err != nil {
fmt.Println(err)
return nil
}
return contacts
}