UNPKG

@goteborgco/open-api-js-client

Version:

Official JavaScript client for the Göteborg & Co GraphQL API

77 lines (76 loc) 2.85 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Client = void 0; const core_1 = require("@apollo/client/core"); const graphql_1 = require("graphql"); const cross_fetch_1 = __importDefault(require("cross-fetch")); /** * HTTP client for making GraphQL API requests * * This class handles the low-level HTTP communication with the GraphQL API, * including authentication, request formatting, and error handling. */ class Client { /** * Initialize the HTTP client * * @param apiUrl The base URL for the GraphQL API * @param subscriptionKey Your API subscription key */ constructor(apiUrl, subscriptionKey) { const httpLink = (0, core_1.createHttpLink)({ uri: apiUrl, fetch: cross_fetch_1.default, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Ocp-Apim-Subscription-Key': subscriptionKey } }); this.client = new core_1.ApolloClient({ link: httpLink, cache: new core_1.InMemoryCache(), }); } /** * Execute a GraphQL query * * @param query The GraphQL query to execute * @returns The query results from the 'data' field of the GraphQL response * @throws Error When: * - JSON encoding/decoding fails * - HTTP request fails (non-200 status) * - GraphQL response contains errors * - Network or other errors occur */ async execute(query) { try { const parsedQuery = typeof query === 'string' ? (0, graphql_1.parse)(query) : query; const { data, errors } = await this.client.query({ query: parsedQuery, }); if (errors?.length) { const errorMessages = errors.map(e => e.message).join(', '); throw new Error(`GraphQL errors: ${errorMessages}\n` + `Query: ${typeof query === 'string' ? query : query.loc?.source.body}`); } if (!data) { throw new Error('No data returned from the GraphQL query'); } return data; } catch (error) { if (error.networkError) { throw new Error(`Network error: ${error.networkError.message || 'Connection failed'}`); } if (error instanceof Error) { throw new Error(`GraphQL query failed: ${error.message}`); } throw new Error('An unknown error occurred during the GraphQL query'); } } } exports.Client = Client;