-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsession.go
257 lines (224 loc) · 6.5 KB
/
session.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package filemaker
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// Session is used for subsequent requests to the host
type Session struct {
Token string
Host string
Database string
Username string
Password string
lastActivity time.Time
}
// ResponseBody represents the json body received from http requests to the filemaker api
type ResponseBody struct {
Messages []struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"messages"`
Response struct {
Token string `json:"token"`
ModID string `json:"modId"`
RecordID string `json:"recordId"`
DataInfo struct {
Database string `json:"database"`
Layout string `json:"layout"`
Table string `json:"table"`
TotalRecordCount int `json:"totalRecordCount"`
FoundCount int `json:"foundCount"`
ReturnedCount int `json:"returnedCount"`
} `json:"dataInfo"`
Data []interface{} `json:"data"`
} `json:"response"`
}
// baseURL builds the base of the data API URL, containing protocol, host and database
func (s Session) baseURL() string {
return fmt.Sprintf(
"%s/fmi/data/v1/databases/%s",
s.Host,
s.Database,
)
}
// recordsURL builds a data API URL used to access record(s)
func (s Session) recordsURL(layout, id string) string {
base := fmt.Sprintf(
"%s/layouts/%s/records",
s.baseURL(),
layout,
)
if id == "" {
return base
}
return fmt.Sprintf("%s/%s", base, id)
}
// Destroy logs out of the database session
func (s *Session) Destroy() error {
//Build and send request to the host
req, err := http.NewRequest(
"DELETE",
fmt.Sprintf("%s/sessions/%s", s.baseURL(), s.Token),
bytes.NewBuffer([]byte{}),
)
req.Header.Add("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send DELETE request: %v", err.Error())
}
//Update last activity time object in session
s.lastActivity = time.Now()
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf(
"failed at host: %v (%v)",
jsonRes.Messages[0].Message,
jsonRes.Messages[0].Code,
)
}
return nil
}
// Find performs the specified findcommand on the specified layout
func (s *Session) Find(layout string, findCommand interface{}) ([]Record, error) {
if layout == "" {
return nil, errors.New("No layout specified")
}
//Create the request json body
var requestBody, err = json.Marshal(findCommand)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %v", err.Error())
}
//Build and send request to the host
req, err := http.NewRequest(
"POST",
fmt.Sprintf("%s/layouts/%s/_find", s.baseURL(), layout),
bytes.NewBuffer(requestBody),
)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send POST request: %v", err.Error())
}
//Update last activity time object in session
s.lastActivity = time.Now()
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return nil, fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
//Check for errors
if jsonRes.Messages[0].Code == "401" {
//No records found, return empty slice
return []Record{}, nil
} else if jsonRes.Messages[0].Code != "0" {
//Unknown error
return nil, fmt.Errorf(
"failed at host: %v (%v)",
jsonRes.Messages[0].Message,
jsonRes.Messages[0].Code,
)
}
var records []Record
for _, r := range jsonRes.Response.Data {
records = append(records, newRecord(layout, r, *s))
}
return records, nil
}
// NewRecord returns a new empty record for the specified layout
func (s *Session) NewRecord(layout string) Record {
return Record{
Layout: layout,
FieldData: make(map[string]interface{}),
StagedChanges: make(map[string]interface{}),
Session: s,
}
}
// LastActivity returns a time object representing the time of the last activity for
// the session. Defaults as the time it was started if no other requests have been made.
func (s *Session) LastActivity() time.Time {
return s.lastActivity
}
// New starts a database session
func New(host, database, username, password string) (*Session, error) {
if host == "" {
return nil, errors.New("No host specified")
} else if database == "" {
return nil, errors.New("No database specified")
} else if username == "" {
return nil, errors.New("No username specified")
}
//Create an empty json body
var requestBody, err = json.Marshal(struct{}{})
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %v", err.Error())
}
//Determine protocol scheme
if len(host) < 8 || host[:8] != "https://" {
host = fmt.Sprintf("https://%s", host)
}
//Build and send request to the host
req, err := http.NewRequest(
"POST",
fmt.Sprintf("%s/fmi/data/v1/databases/%s/sessions", host, database),
bytes.NewBuffer(requestBody),
)
req.Header.Add("Content-Type", "application/json")
req.Header.Add(
"Authorization",
"Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)),
)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send POST request: %v", err.Error())
}
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return nil, fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
//Check the response code
if jsonRes.Messages[0].Code != "0" {
return nil, fmt.Errorf(
"failed at host: %v (%v)",
jsonRes.Messages[0].Message,
jsonRes.Messages[0].Code,
)
}
return &Session{
Token: jsonRes.Response.Token,
Host: host,
Database: database,
Username: username,
Password: password,
lastActivity: time.Now(),
}, nil
}