@tribute-tg/sdk
Version:
Unofficial Tribute SDK for Node.js and browsers
79 lines (77 loc) • 2.31 kB
JavaScript
//#region src/cache.ts
const getCache = async () => {
if (!("caches" in globalThis)) return void 0;
if ("default" in caches) return caches.default;
return await caches.open("default");
};
const fetchWithCache = async (request, { maxAge } = { maxAge: 300 }) => {
const cache = await getCache();
if (!cache) return await fetch(request);
const cached = await cache?.match(request);
if (cached) return new Response(cached.body, cached);
else {
const response = await fetch(request);
const cacheable = new Response(response.body, response);
try {
cacheable.headers.append("Cache-Control", `s-maxage=${maxAge}`);
} catch (error) {
console.error(error);
}
await cache?.put(request, cacheable.clone());
return cacheable;
}
};
//#endregion
//#region src/index.ts
var Tribute = class {
baseUrl = "https://tribute.tg/api";
version = "v4";
cacheMaxAge;
token;
apiKey;
constructor({ token, apiKey, cacheMaxAge }) {
this.token = token;
this.apiKey = apiKey;
this.cacheMaxAge = cacheMaxAge ?? 300;
}
async request(route, body, method) {
const url = `${this.baseUrl}/${this.version}${route}`;
const init = {
headers: {
Authorization: `TgAuth ${this.token}`,
"Api-Key": this.apiKey
},
method: method ?? (body ? "POST" : "GET"),
body: body ? JSON.stringify(body) : void 0
};
const request = new Request(url, init);
return (this.cacheMaxAge ? await fetchWithCache(request, { maxAge: this.cacheMaxAge }) : await fetch(request)).json();
}
getDashboard() {
return this.request(`/dashboard`);
}
getChannel(id) {
return this.request(`/channel/${id}`);
}
createSubscription(payload) {
return this.request(`/subscription`, payload);
}
getSubscription(id) {
return this.request(`/subscription/${id}`);
}
updateSubscription(payload) {
return this.request(`/subscription`, payload, "PATCH");
}
createSubscriptionPeriod(subscriptionId, payload) {
return this.request(`/subscription/${subscriptionId}/periods`, payload);
}
updateSubscriptionPeriod(subscriptionId, periodId, payload) {
return this.request(`/subscription/${subscriptionId}/periods/${periodId}`, payload, "PATCH");
}
getSubscriptionMember(id) {
return this.request(`/subscription_member/${id}`);
}
};
//#endregion
export { Tribute };
//# sourceMappingURL=index.mjs.map