brainlet/libbrainlet/index.js

84 lines
No EOL
2.1 KiB
JavaScript

const GatewayConnection = require('./gatewayconnection');
const fetch = require('node-fetch');
class Client {
constructor(url, config={}) {
this.token = null;
this.user = null;
this.isLoggedIn = false;
this.url = url;
this.config = config;
this.gateway = null;
}
}
Client.prototype.gatewayConnect = async function() {
if (!this.token) throw new Error('Attempt to connect to gateway without being authenticated');
this.gateway = new GatewayConnection(this.url);
this.gateway.connect(this.token);
};
Client.prototype.gatewayDisconnect = async function() {
if (this.gateway) this.gateway.disconnect();
this.gateway = null;
};
Client.prototype.sendAuthenticatedRequest = async function(endpoint, options) {
if (!this.token) throw new Error('Attempt to send authenticated request without being authenticated');
options.headers = {
cookie: `token=${this.token}`,
...options.headers
};
let res;
let json;
let isOK = false;
try {
res = await fetch(`${this.url}${endpoint}`, options);
json = await res.json();
} catch(e) {
throw new Error(`Request to ${endpoint} failed with error`, e);
}
if (res.ok && !json.error) {
isOK = true;
} else {
if (this.config.throwErrors) {
throw new Error(`Request to ${endpoint} failed with status ${res.status}`);
}
}
return { res, json, isOK };
};
Client.prototype.setToken = async function(token) {
this.token = token;
const { json, isOK } = await this.sendAuthenticatedRequest('/api/v1/users/current/info', {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if (!isOK) throw new Error('Failed to get user info for setToken');
this.user = json.user;
this.userLoggedIn = true;
console.log(`[*] Logged in as ${this.user.username}`);
};
Client.prototype.unsetToken = async function() {
this.token = null;
this.user = null;
this.gatewayDisconnect();
this.userLoggedIn = false;
};
module.exports = Client;