UNPKG

@ikas/admin-api-client

Version:

ikas public node api client for store apps and private apps

85 lines 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.APIResult = exports.BaseGraphQLAPIClient = void 0; const graphql_request_1 = require("graphql-request"); class BaseGraphQLAPIClient { _client; accessToken; graphApiUrl; tokenData; onCheckToken; constructor({ accessToken, graphApiUrl, onCheckToken, tokenData }) { this.accessToken = accessToken; this.graphApiUrl = graphApiUrl; this._client = this.createGraphQLClient(); this.tokenData = tokenData; this.onCheckToken = onCheckToken; } createGraphQLClient() { const token = this.accessToken; // Run GraphQL queries/mutations using a static function // ... or create a GraphQL client instance to send requests return new graphql_request_1.GraphQLClient(this.graphApiUrl, { headers: { 'User-Agent': 'ikas-app-client', ...(token ? { authorization: token ? `Bearer ${token}` : '' } : {}), }, credentials: 'include', }); } async query(options) { return this._makeRequest({ ...options, gql: options.query || '', }); } async mutate(options) { return this._makeRequest({ ...options, gql: options.mutation || '', }); } async _makeRequest(options) { await this._checkToken(); try { const data = await this._client.request({ document: options.gql, variables: options.variables, }); return new APIResult({ data: options.operationName ? data[options.operationName] : data }); } catch (e) { if (e instanceof graphql_request_1.ClientError) return new APIResult({ errors: e.response.errors }); else return new APIResult({ error: e.message }); } } async _checkToken() { if (this.onCheckToken) { const { accessToken, tokenData } = await this.onCheckToken(this.tokenData); if (accessToken) { this.accessToken = accessToken; this.tokenData = tokenData; this._client = this.createGraphQLClient(); } } } } exports.BaseGraphQLAPIClient = BaseGraphQLAPIClient; class APIResult { data; error; errors; partial; constructor(result) { this.data = result.data; this.error = result.error; this.errors = result.errors; } get isSuccess() { return !this.errors?.length && !this.error; } } exports.APIResult = APIResult; //# sourceMappingURL=base.js.map