-
Notifications
You must be signed in to change notification settings - Fork 0
/
queries.go
227 lines (214 loc) · 7.13 KB
/
queries.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"context"
"fmt"
"regexp"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
/* ==============================================
Copyright (c) Eensymachines
Developed by : [email protected]
Developed on : OCT'22
Middleware queries for accounts in eensymachines
============================================== */
const (
// link to go tools to test this email pattern
patternEmail = `^[[:alnum:]]+[.\-_]{0,1}[[:alnum:]]*[@]{1}[[:alpha:]]+[.]{1}[[:alnum:]]{2,}[.]{0,1}[[:alnum:]]{0,}$`
patternPhone = `^[0-9]{10}$` // we are assuming that we have phone numbers from India only
// title of the account allowed is about 1 to 16 characters including numbers and a handful of special characters
patternTitle = `^[a-zA-Z0-9_\-.\s]{1,16}$`
)
// ValidateForCreate: validates the account details, checkls for errenous values
// will check to see if the email, phone and the title fall in a pattern
/*
// your sample code here
*/
func ValidateForCreate(acc Account) error {
if matched, _ := regexp.MatchString(patternEmail, acc.GetEmail()); !matched {
return fmt.Errorf("invalid email for the account")
}
if matched, _ := regexp.MatchString(patternPhone, acc.GetPhone()); !matched {
return fmt.Errorf("invalid email for the account")
}
if matched, _ := regexp.MatchString(patternTitle, acc.GetTitle()); !matched {
return fmt.Errorf("invalid email for the account")
}
return nil
}
// ValidateForUpdate: validates the account for its details
// will check to see if the update`able fields are valid
// Incase the fields arent populated, or have zero value the check is missed
// Email is not an update`able` field
/*
// your sample code here
*/
func ValidateForUpdate(acc Account) error {
if acc.GetPhone() != "" {
if matched, _ := regexp.MatchString(patternPhone, acc.GetPhone()); !matched {
return fmt.Errorf("invalid email for the account")
}
}
if acc.GetTitle() != "" {
if matched, _ := regexp.MatchString(patternTitle, acc.GetTitle()); !matched {
return fmt.Errorf("invalid email for the account")
}
}
return nil
}
type AccountFilter func(Account) bson.M // this can filter accounts on various criteria
// CheckExists: Checks to see if there is exactly one account with the same email
// Will error in case the count of the documents is not equal to 1
// can customize the filter on which existence of the document is based
//
/*
if CheckExists(acc, coll, func(acc Account) bson.M {
return bson.M{"email": acc.GetEmail()}
}) != nil {
// error handling code here
}
*/
func CheckExists(acc Account, coll *mongo.Collection, af AccountFilter) error {
count, err := coll.CountDocuments(context.TODO(), af(acc))
if err != nil {
return fmt.Errorf("CheckExists: failed to get account")
}
if count != int64(1) {
return fmt.Errorf("CheckExists: No account found")
}
return nil
}
// CheckDuplicate: Checks for duplicates on account unique fields
// Will check to see if email is duplicate or the phone is
// will error in case duplicate is found
//
/*
// your sample code here
*/
func CheckDuplicate(acc Account, coll *mongo.Collection) error {
emailFlt := bson.M{
"email": acc.GetEmail(),
}
count, err := coll.CountDocuments(context.Background(), emailFlt)
if err != nil {
return fmt.Errorf("failed to get account duplicates")
}
if count > int64(0) {
return fmt.Errorf("account with duplicate email found")
}
phoneFlt := bson.M{
"phone": acc.GetPhone(),
}
count, err = coll.CountDocuments(context.TODO(), phoneFlt)
if err != nil {
return fmt.Errorf("failed to get account duplicates")
}
if count > int64(0) {
return fmt.Errorf("account with duplicate phone found")
}
return nil
}
// CreateNewAccount: registers new account to the database
//
// Upon creation of the account, the UID of the account then is sent back.
// Such UIDs can be used in urls to further indentify the account from the API
//
// acc : Account to be inserted
//
// coll: database collection in which the account gets inserted
//
// hresult: result of the operation that can be then jsonified in the response
//
/*
hResult := gin.H{}
if err := CreateNewAccount(acc, coll, &hResult); err != nil {
ThrowErr(fmt.Errorf("Accounts: Failed query to create accounts %s", err), log.WithFields(log.Fields{}), http.StatusInternalServerError, c)
return
}
// The account has been created
c.AbortWithStatusJSON(http.StatusCreated, hResult)
*/
func CreateNewAccount(acc Account, coll *mongo.Collection, hresult *gin.H) error {
result, err := coll.InsertOne(context.Background(), acc)
if err != nil {
return fmt.Errorf("InsertOne: failed query, check database connection")
}
log.Infof("new account inserted : %v", result.InsertedID)
*hresult = gin.H{
"id": result.InsertedID.(primitive.ObjectID).Hex(),
}
return nil
}
// UpdateAccount: updates the title and phone of a single account
//
// TODO: when the account has more fields attached to it the update patch can expand
/*
if err := UpdateAccount(acc, coll); err != nil {
ThrowErr(fmt.Errorf("Accounts: Failed query to update accounts %s", err), log.WithFields(log.Fields{
"email": acc.GetEmail(),
}), http.StatusInternalServerError, c)
return
}
*/
func UpdateAccount(acc Account, flt AccountFilter, coll *mongo.Collection) error {
// flt := bson.M{
// "email": acc.GetEmail(),
// }
patch := bson.M{"$set": bson.M{"title": acc.GetTitle(), "phone": acc.GetPhone()}}
result, err := coll.UpdateOne(context.Background(), flt(acc), patch)
if err != nil {
return fmt.Errorf("UpdateOne: failed query, check database connection, %s", err)
}
log.Infof("account updated : %v", result.UpsertedID)
return nil
}
// ArchiveAccount : removes the account details from the collection only to be archived in some other collection
//
/*
if err := ArchiveAccount(oid, coll); err != nil {
ThrowErr(fmt.Errorf("Accounts: Failed query to delete account %s", err), log.WithFields(log.Fields{
"_id": id,
}), http.StatusInternalServerError, c)
return
}
*/
func ArchiveAccount(oid primitive.ObjectID, coll *mongo.Collection) error {
flt := bson.M{"_id": oid}
sr := coll.FindOne(context.TODO(), flt)
archived := &UserAccount{}
if err := sr.Decode(archived); err != nil {
return err
}
// Archived replica, if this succeeds then we can remove from main collection
// on this collection there isnt any unique key constraint on email, phone
_, err := coll.Database().Collection("archvaccounts").InsertOne(context.TODO(), archived)
if err != nil {
return err
}
// when the account information is backed up its ready to be deleted
// we move the sameto archived collecitons
coll.DeleteOne(context.TODO(), flt)
return nil
}
// AccountOfID: given the id of the account, gets the account details
func AccountOfID(oid primitive.ObjectID, coll *mongo.Collection, hResult *gin.H) error {
flt := bson.M{"_id": oid}
sr := coll.FindOne(context.TODO(), flt)
if sr.Err() != nil {
return sr.Err()
}
result := &UserAccount{}
if err := sr.Decode(&result); err != nil {
return err
}
*hResult = gin.H{
"id": result.ID.Hex(),
"email": result.Email,
"title": result.Title,
"phone": result.Phone,
}
return nil
}