godprotocol
Version:
A distributed computing environment for Web 4.0 — integrating AI, decentralisation, and virtual computation.
140 lines (117 loc) • 3.2 kB
JavaScript
import { DB } from "./Header.js";
let DEV = true;
let gp_services = {
profile: DEV
? "http://localhost:4000"
: "https://profile-api.savvyaisolution.com",
settings: DEV
? "http://localhost:4005"
: "https://settings-api.savvyaisolution.com",
};
export { gp_services };
class Services {
constructor() {
this.services = new Object();
}
load_services = async (services) => {
this.services = services;
};
get_token = async (service, id) => {
let token;
// debug(service, id, "gettok");
let db = await this.platform_db();
token = await db.read_cache(
{ platform_uri: service.uri, id: id.profile },
"token",
);
// debug(token, "in-cache");
if (token) return token.token;
try {
// debug(this.api_key, gp_services.profile);
let ftch = await fetch(`${gp_services.profile}/get_token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-version": "v2",
"x-api-key": this.api_key,
},
body: JSON.stringify({ platform_uri: service.uri, ...id }),
});
// debug("whats it like??");
token = await ftch.json();
// debug(token, "HOOWWW");
if (token?.ok) {
await db.save_cache(
{ id: id.profile, platform_uri: service.uri },
{ token: token.token },
"token",
);
return token.token;
}
} catch (e) {
return {
ok: false,
status: 500,
message: e.message,
};
}
return token;
};
get_service = async (service) => {
let servic = this.services[service];
if (!servic) return;
return {
call: async (path, body, header) => {
let headers = {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-version": servic.api_version || "v1",
};
let token;
if (header) {
if (header.token) {
token = header.token;
} else if (header.profile) {
token = await this.get_token(servic, header);
if (typeof token !== "string") {
if (token?.ok === false) return token;
}
}
}
if (token) headers["Authorization"] = `Bearer ${token}`;
headers["x-platform"] = this.platform_uri;
try {
let response = await fetch(`${servic.url}/${path}`, {
method: "POST",
headers,
body: JSON.stringify(body || {}),
});
return await response.json();
} catch (e) {
return {
ok: false,
message: e.message,
status: 500,
};
}
},
};
};
platform_db = async () => {
return new DB(this.db_config, this);
};
handle_webhook_prior = async (req) => {
let { platform } = req.headers;
if (!platform) return false;
};
handle_webhook_after = async (req, result) => {};
resolve_db = async (req) => {
let db = await this.platform_db();
return {
ok: true,
db,
};
};
}
export default Services;