Created
August 20, 2017 01:11
-
-
Save itslukej/1fabc4dd39ee25d3b68a0d7c42e62b3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const snekfetch = require('snekfetch'); | |
const EventEmitter = require('events'); | |
const BASE_URL = 'http://discoin.sidetrip.xyz'; | |
const endpoints = { | |
transactions: '/transactions', | |
transaction: '/transaction' | |
}; | |
class DiscoinError extends Error { | |
constructor(message) { | |
super(message); | |
this.name = 'DiscoinError'; | |
} | |
} | |
class DiscoinClient extends EventEmitter { | |
constructor(token) { | |
super(); | |
this.token = token; | |
this.heartbeatInterval = setInterval(this.heartbeatTransactions.bind(this), 60000); | |
} | |
constructRequest(method = 'get', endpoint) { | |
return snekfetch[method](BASE_URL + endpoint) | |
.set('Authorization', this.token); | |
} | |
heartbeatTransactions() { | |
this.constructRequest('get', endpoints.transactions).end((err, res) => { | |
if(err) return this.emit('error', err); | |
for(let transaction of res.body) { | |
this.emit('transaction', transaction); | |
} | |
}); | |
} | |
createTransaction(options) { | |
return new Promise((resolve, reject) => { | |
this.constructRequest('post', endpoints.transaction) | |
.send(options) | |
.end((err, res) => { | |
if(err) return reject(err); | |
if(res.body.status === 'error') return reject(new DiscoinError(res.body)); | |
resolve(res.body); | |
}); | |
}); | |
} | |
} | |
module.exports = DiscoinClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment