marvin-minder/Beeminder.js

80 lines
2.4 KiB
JavaScript

const fetch = require('node-fetch')
class Beeminder {
constructor(token) {
this.token = token
}
async post_request(url, post_data, method="POST") {
const response = await fetch("https://www.beeminder.com/api/v1/" + url + ".json", {
method: 'POST',
body: JSON.stringify(Object.assign({}, post_data, {auth_token: this.token})),
headers: {'Content-Type': 'application/json'}
})
if (response.ok || response.status == 422) {
return response.json()
} else {
throw [response.status, await response.text()]
}
}
async get_request(url, params={}) {
const qs = new URLSearchParams(Object.assign({}, params, {auth_token: this.token}))
const response = await fetch("https://www.beeminder.com/api/v1/" + url + ".json?" + qs.toString())
if (response.ok || response.status == 422) {
return response.json()
} else {
throw [response.status, await response.text()]
}
}
user(user="me") {
return new User(this, user)
}
charge(amount, note, dryrun=true) {
return this.b.post_request(`charges`, {amount, note, dryrun})
}
}
class User {
constructor(b, user) {
Object.assign(this, {b, user})
}
info() {
return this.b.get_request(`users/${this.user}`)
}
goals() {
return this.b.get_request(`users/${this.user}/goals`)
}
goal(goal) {
return new Goal(this.b, this.user, goal)
}
create_goal(params) {
return this.b.post_request(`users/${this.user}/goals`, params, 'POST')
}
}
class Goal {
constructor(b, user, goal) {
Object.assign(this, {b, user, goal})
this.prefix = `users/${this.user}/goals/${this.goal}`
}
info() {
return this.b.get_request(`${this.prefix}`)
}
update(params) {
return this.b.post_request(`${this.prefix}`, params, 'PUT')
}
refresh_graph() {
return this.b.get_request(`${this.prefix}/refresh_graph`)
}
create_datapoint(params) {
return this.b.post_request(`${this.prefix}/datapoints`, params)
}
create_datapoints(params) {
return this.b.post_request(`${this.prefix}/datapoints/create_all`, params)
}
datapoints(params) {
return this.get_request(`${this.prefix}/datapoints`, params)
}
// todo: put, delete datapoint
}
module.exports = Beeminder