87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
import fetch from 'node-fetch';
|
|
|
|
export default class Lndhub {
|
|
constructor (baseUrl) {
|
|
this.baseUrl = baseUrl;
|
|
}
|
|
|
|
async callEndpoint (method, path, payload) {
|
|
const options = { method, headers: { 'Content-Type': 'application/json' } };
|
|
|
|
if (path !== '/auth') {
|
|
options.headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
}
|
|
if (typeof payload !== 'undefined') {
|
|
options.body = JSON.stringify(payload);
|
|
}
|
|
|
|
const res = await fetch(`${this.baseUrl}${path}`, options);
|
|
return res.json();
|
|
}
|
|
|
|
async handleErroredRequest (result, retryFunction, args=[]) {
|
|
console.warn('API request failed:', result.message);
|
|
if (result.code === 1) {
|
|
return this.reauth().then(connected => {
|
|
if (connected) {
|
|
console.warn('Lndhub reconnected, trying again...');
|
|
return this[retryFunction](...args);
|
|
}
|
|
});
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async auth (username, password) {
|
|
const payload = { "login": username, "password": password };
|
|
const data = await this.callEndpoint('post', '/auth', payload);
|
|
|
|
if (data.error) {
|
|
console.warn('Lndhub connection failed:', data.message);
|
|
return false;
|
|
} else {
|
|
this.refreshToken = data.refresh_token;
|
|
this.accessToken = data.access_token;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
async reauth (refreshToken) {
|
|
const payload = { "refresh_token": this.refreshToken };
|
|
const data = await this.callEndpoint('post', '/auth', payload);
|
|
|
|
if (data.error) {
|
|
console.warn('Lndhub re-auth failed:', data.message);
|
|
return false;
|
|
} else {
|
|
if (this.accessToken !== data.access_token) {
|
|
console.log('Lndhub access token refreshed');
|
|
}
|
|
this.accessToken = data.access_token;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
async createInvoice (amount, description) {
|
|
const payload = { amount, description };
|
|
let data = await this.callEndpoint('post', '/v2/invoices', payload);
|
|
|
|
if (data.error) {
|
|
return this.handleErroredRequest(data, 'createInvoice', Array.from(arguments));
|
|
} else {
|
|
return data;
|
|
}
|
|
}
|
|
|
|
async getInvoice (paymentHash) {
|
|
const data = await this.callEndpoint('get', `/v2/invoices/${paymentHash}`);
|
|
|
|
if (data.error) {
|
|
return this.handleErroredRequest(data, 'getInvoice', Array.from(arguments));
|
|
} else {
|
|
return data;
|
|
}
|
|
}
|
|
}
|