@symanticreative/vendure-admin-client
Version:
A TypeScript GraphQL client for Vendure Admin API to create custom dashboards
218 lines • 7.06 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { ApolloClient, InMemoryCache, createHttpLink, from, gql } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import fetch from 'cross-fetch';
import { Injectable } from '../di/injectable.decorator';
/**
* GraphQL client service for making GraphQL requests
* This is used by repositories to execute GraphQL operations
*/
let GraphQLClientService = class GraphQLClientService {
/**
* Initialize the GraphQL client with configuration
* @param config - Vendure Admin client configuration
*/
constructor(config) {
this.authToken = null;
this.refreshToken = null;
this.config = {
timeout: 10000, // Default timeout
...config,
};
if (config.authToken) {
this.authToken = config.authToken;
}
if (config.refreshToken) {
this.refreshToken = config.refreshToken;
}
this.client = this.createApolloClient();
}
/**
* Create Apollo client instance
* @returns Configured Apollo Client
*/
createApolloClient() {
// Create HTTP link to the GraphQL endpoint
const httpLink = createHttpLink({
uri: this.config.apiUrl,
fetch
});
// Add auth token to each request
const authLink = setContext((_, { headers }) => {
const token = this.getAuthToken();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
// Create and return the Apollo Client
return new ApolloClient({
link: from([authLink, httpLink]),
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'network-only', // Don't use cache for queries by default
errorPolicy: 'all'
},
mutate: {
errorPolicy: 'all'
},
watchQuery: {
fetchPolicy: 'network-only',
errorPolicy: 'all'
}
}
});
}
/**
* Execute a GraphQL query
* @param query - GraphQL query or DocumentNode
* @param variables - Query variables
* @returns Promise with query result
*/
async query(query, variables) {
try {
const queryToExecute = typeof query === 'string' ? gql(query) : query;
const { data } = await this.client.query({
query: queryToExecute,
variables
});
return data;
}
catch (error) {
console.error('Query error:', error);
throw error;
}
}
/**
* Execute a GraphQL mutation
* @param mutation - GraphQL mutation or DocumentNode
* @param variables - Mutation variables
* @returns Promise with mutation result
*/
async mutate(mutation, variables) {
try {
const mutationToExecute = typeof mutation === 'string' ? gql(mutation) : mutation;
const { data } = await this.client.mutate({
mutation: mutationToExecute,
variables
});
return data;
}
catch (error) {
console.error('Mutation error:', error);
throw error;
}
}
/**
* Execute a custom GraphQL operation (query or mutation)
* @param operation - GraphQL operation or DocumentNode
* @param variables - Operation variables
* @param options - Additional options
* @returns Promise with operation result
*/
async executeOperation(operation, variables, options) {
const operationType = options?.type || 'query';
const gqlOperation = typeof operation === 'string' ? gql(operation) : operation;
try {
if (operationType === 'query') {
const { data } = await this.client.query({
query: gqlOperation,
variables,
fetchPolicy: options?.fetchPolicy || 'network-only'
});
return data;
}
else {
const { data } = await this.client.mutate({
mutation: gqlOperation,
variables
});
return data;
}
}
catch (error) {
console.error(`Custom operation error (${operationType}):`, error);
throw error;
}
}
/**
* Update client configuration
* @param config - New configuration options
*/
updateConfig(config) {
const newConfig = {
...this.config,
...config,
};
// Only recreate the Apollo client if the API URL changed
if (config.apiUrl && config.apiUrl !== this.config.apiUrl) {
this.config = newConfig;
this.client = this.createApolloClient();
}
else {
this.config = newConfig;
}
// Update tokens if provided
if (config.authToken) {
this.authToken = config.authToken;
}
if (config.refreshToken) {
this.refreshToken = config.refreshToken;
}
}
/**
* Get the current authentication token
* @returns Current auth token or null
*/
getAuthToken() {
return this.authToken;
}
/**
* Get the current refresh token
* @returns Current refresh token or null
*/
getRefreshToken() {
return this.refreshToken;
}
/**
* Set the authentication token
* @param token - Auth token
*/
setAuthToken(token) {
this.authToken = token;
}
/**
* Set the refresh token
* @param token - Refresh token
*/
setRefreshToken(token) {
this.refreshToken = token;
}
/**
* Check if authenticated
* @returns True if auth token exists
*/
isAuthenticated() {
return !!this.authToken;
}
/**
* Get the underlying Apollo client
* @returns Apollo client instance
*/
getApolloClient() {
return this.client;
}
};
GraphQLClientService = __decorate([
Injectable()
], GraphQLClientService);
export { GraphQLClientService };
//# sourceMappingURL=graphql-client.service.js.map