-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.js
178 lines (169 loc) · 5.43 KB
/
client.js
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
/**
* Simple Promise-based client for the Foobot API.
*
* Run this file as a standalone script to test different types of requests.
*/
import request from 'request'
import read from 'read'
import pkg from '../package.json'
const debug = require('debug')('foobot-graphql:api')
export default class FoobotClient {
constructor (opts = {}) {
this.apiKey = opts.apiKey || process.env.FOOBOT_API_KEY
if (this.apiKey == null) {
throw new Error(
'FoobotClient must be configured with an API key. ' +
'Use the `apiKey` option or `FOOBOT_API_KEY` environment variable.'
)
}
this.username = opts.username || process.env.FOOBOT_USERNAME
if (this.username == null) {
throw new Error(
'FoobotClient must be configured with a username. ' +
'Use the `username` option or `FOOBOT_USERNAME` environment variable.'
)
}
this.defaultDevice = opts.defaultDevice || process.env.FOOBOT_DEFAULT_DEVICE
this.lastRequestTime = null
this.lastRequestLimit = null
this.http = request.defaults({
baseUrl: 'https://api.foobot.io/',
json: true,
gzip: true,
timeout: 60000,
headers: {
'x-api-key-token': this.apiKey,
'User-Agent': `${pkg.name}/${pkg.version} ` +
`( ${pkg.homepage || pkg.author.url || pkg.author.email} )`
}
})
}
_request (options) {
return new Promise((resolve, reject) => {
debug(`Sending request. url='${options.url}'`)
const lastRequestTime = new Date()
this.http(options, (err, response, body) => {
if (err) {
return reject(err)
}
const lastRequestLimit = response.headers['x-api-key-limit-remaining']
if (this.lastRequestTime == null || this.lastRequestTime <= lastRequestTime) {
this.lastRequestTime = lastRequestTime
if (lastRequestLimit != null) {
this.lastRequestLimit = parseInt(lastRequestLimit, 10)
}
}
debug(
`Received response. ` +
`statusCode=${response.statusCode} ` +
`lastRequestLimit=${lastRequestLimit}`
)
if (response.statusCode >= 200 && response.statusCode < 400) {
return resolve(response)
}
let message = `Request failed with status code ${response.statusCode}`
if (response.statusMessage) {
message += `: ${response.statusMessage}`
}
err = new Error(message)
err.response = response
return reject(err)
})
})
}
/**
* This endpoint is no longer necessary, as the API now uses the API key as
* the auth token. Keep this around in case someone wants to use it anyway.
*/
login (username = this.username, password) {
this.username = username
return this._request({
url: `/v2/user/${username}/login/`,
method: 'post',
body: { password }
}).then(response => {
if (response.headers['x-auth-token']) {
return response
}
throw new Error('Authentication failed.')
})
}
devices (username = this.username) {
return this._request({
url: `/v2/owner/${username}/device/`
}).then(response => response.body)
}
datapoints (uuid = this.defaultDevice, { start, end, period = 0, averageBy = 0 } = {}) {
if (start instanceof Date) {
start = start.toISOString()
}
if (end instanceof Date) {
end = end.toISOString()
}
if (period instanceof Date) {
const duration = Date.now() - period.getTime()
period = Math.ceil(duration / 1000)
}
let url = `/v2/device/${uuid}/datapoint/${period}/last/${averageBy}/`
if (start != null && end != null) {
url = `/v2/device/${uuid}/datapoint/${start}/${end}/${averageBy}/`
}
return this._request({ url }).then(response => {
response.body.date = Date.parse(response.headers.date) / 1000
return response.body
})
}
}
if (require.main === module) {
require('dotenv').config()
const { logObject, logError, safeExit } = require('./util')
const client = new FoobotClient()
const command = process.argv[2]
if (command === 'login') {
const username = process.argv[3] || client.username ||
new Promise((resolve, reject) => {
read({ prompt: 'Username:' }, (err, username) => {
return err ? reject(err) : resolve(username)
})
})
Promise.resolve(username).then((username) => {
return new Promise((resolve, reject) => {
read({
prompt: 'Password:',
silent: true,
replace: '•'
}, (err, password) => {
return err ? reject(err) : resolve({ username, password })
})
})
}).then(({ username, password }) => {
return client.login(username, password)
}).then(response => {
console.log(response.headers['x-auth-token'])
}).catch(err => {
logError(err)
safeExit(1)
})
} else if (command === 'devices') {
const username = process.argv[3]
client.devices(username).then(devices => {
logObject(devices)
}).catch(err => {
logError(err)
safeExit(1)
})
} else if (command === 'datapoints') {
const uuid = process.argv[3]
const period = process.argv[4]
const averageBy = process.argv[5]
client.datapoints(uuid, { period, averageBy }).then(data => {
logObject(data)
}).catch(err => {
logError(err)
safeExit(1)
})
} else {
console.log('Commands: login, devices, datapoints')
safeExit(1)
}
}