-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.js
More file actions
44 lines (38 loc) · 1.35 KB
/
client.js
File metadata and controls
44 lines (38 loc) · 1.35 KB
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
import dotenv from 'dotenv'
import togglClient from 'toggl-client'
import chalk from 'chalk'
import { readConfig } from './config.js'
dotenv.config({quiet:true})
import debugClient from 'debug'
const debug = debugClient('toggl-cli-client')
const QUOTA_WARNING_THRESHOLD = 5
export default async function () {
let conf
try {
conf = await readConfig('.toggl-cli.json')
debug(conf)
} catch (error) {
console.error('Using config from environment variables or create one with the create-config command')
}
const apiToken = process.env.TOGGL_API_TOKEN || conf?.api_token
debug(apiToken)
let client
try {
client = togglClient({ apiToken });
} catch (error) {
console.error(error.message);
console.error('There was a problem')
process.exit(1)
}
// Wrap request method to warn when API quota is running low
const originalRequest = client.request.bind(client)
client.request = async function (...args) {
const result = await originalRequest(...args)
if (client.quota && client.quota.remaining !== null && client.quota.remaining <= QUOTA_WARNING_THRESHOLD) {
const minutes = client.quota.resetsIn ? Math.ceil(client.quota.resetsIn / 60) : '?'
console.error(chalk.yellow(`\n⚠ API quota low: ${client.quota.remaining} requests remaining (resets in ~${minutes}m)`))
}
return result
}
return client
}