import fetch from "node-fetch"; // simply to allow for gql tag syntax highlighting export function gql(strings: TemplateStringsArray) { return strings.join(""); } export class Sonar { url: string; token: string; constructor(url: string, token: string) { this.url = url; this.token = token; } async request(query: string, variables: any = {}) { const resp = await fetch(this.url, { method: "POST", body: JSON.stringify({ query, variables }), headers: { "Content-Type": "application/json", Authorization: "Bearer " + this.token, }, }); if (!resp.ok) { throw new Error( `${resp.status} ${resp.statusText} ${JSON.stringify(await resp.json())}` ); } const { data, errors } = await resp.json(); if (errors) { throw new Error(errors[0].message); } return data; } async handlePagination( query: string, key: string, callback: (entities: any) => void | Promise ) { let page = 1; let morePages = false; do { const response = await this.request(query, { page }); const { entities, page_info } = response[key]; morePages = page_info.total_pages > page; await callback(entities); page++; } while (morePages); } }