UNPKG

@archon-inc/sdk

Version:

Integrate easily to our government platform using this SDK. More info on https://archon.inc/sdk

102 lines (101 loc) 3.21 kB
import axios, { isAxiosError } from 'axios'; class Archon { constructor() { this.rootUrl = "http://engine:3000"; this.publicUrl = "http://localhost:8333"; this.componentName = "UNSET_NAME"; if (Archon.instance) { return Archon.instance; } Archon.instance = this; } setServiceToken(token) { this.serviceToken = token; } setUserUuid(uuid) { this.userId = uuid; } setRoleName(role) { this.roleName = role; } setComponentName(name) { this.componentName = name; } getComponentName() { return this.componentName; } getPublicUrl() { return this.publicUrl; } async authenticate() { if (!this.serviceToken) { // try to load the service token from the environment if (process?.env?.SERVICE_TOKEN) { this.serviceToken = process.env.SERVICE_TOKEN; } else { throw new Error("Service token not provided"); } } const payload = { serviceToken: this.serviceToken, }; if (process.env.ARCHON_SERVICE_USERNAME && process.env.ARCHON_SERVICE_ROLENAME) { payload["username"] = process.env.ARCHON_SERVICE_USERNAME; payload["roleName"] = process.env.ARCHON_SERVICE_ROLENAME; } else if (this.userId && this.roleName) { payload["userId"] = this.userId; payload["roleName"] = this.roleName; } else { throw new Error("Credentials not provided"); } try { const response = await axios({ method: "POST", url: `${this.rootUrl}/local/serviceAuth`, headers: { 'Content-Type': 'application/json', }, data: payload }); this.sessionId = response.data.session_id; } catch (error) { if (isAxiosError(error)) { console.error("Error: " + error.response?.data); console.error("Status " + error.response?.status); } else { console.error(error); } } } async request(route, method, body) { if (!this.sessionId) { await this.authenticate(); } try { const response = await axios({ method: method, url: `${this.rootUrl}${route}`, headers: { // if its not a get request, make the content type application/json ...(method ? { 'Content-Type': 'application/json' } : {}), "x-session-id": this.sessionId, }, data: body, }); return response; } catch (error) { if (isAxiosError(error)) { throw new Error(`Error (${error.response?.status || "unknown"}): ${error.response?.data || "Request failed"}`); } throw error; } } } const archonInstance = new Archon(); export { archonInstance as Archon };