UNPKG

mdevcloud-api

Version:

SDK oficial para consumir a API MDev Cloud Registrations

72 lines (60 loc) 2 kB
// index.js class CloudClient { /** * @param {string} host - Base URL da sua API (ex: http://localhost:3000) * @param {string} db_key - Chave de acesso ao banco */ constructor(host, db_key) { this.baseUrl = `${host}/api/cloud/registrations`; this.db_key = db_key; } async request(path, method, body = null) { const options = { method, headers: { "Content-Type": "application/json" }, }; if (body) { options.body = JSON.stringify(body); } const res = await fetch(`${this.baseUrl}${path}`, options); const data = await res.json().catch(() => null); if (!res.ok) { throw new Error( `Erro na requisição [${res.status}] ${res.statusText}: ${JSON.stringify(data)}` ); } return data; } /** Criar novo client */ async createClient({ jid, username }) { return this.request("", "POST", { db_key: this.db_key, jid, username, }); } /** Buscar client específico */ async getClient(jid) { const params = new URLSearchParams({ db_key: this.db_key, jid }); return this.request(`?${params.toString()}`, "GET"); } /** Buscar todos os clients */ async getAllClients() { const params = new URLSearchParams({ db_key: this.db_key }); return this.request(`?${params.toString()}`, "GET"); } /** Atualizar client */ async updateClient(jid, update) { return this.request("", "PUT", { db_key: this.db_key, jid, update, }); } /** Deletar client */ async deleteClient(jid) { const params = new URLSearchParams({ db_key: this.db_key, jid }); return this.request(`?${params.toString()}`, "DELETE"); } } module.exports = CloudClient;