iluria-sdk
Version:
SDK oficial do Iluria para integração com lojas e criação de frontends customizados
250 lines (220 loc) • 7.33 kB
JavaScript
const HttpClient = require('./http');
const Store = require('./store');
const Product = require('./product');
const Promotion = require('./promotion');
const Collection = require('./collection');
const CombinedProduct = require('./combined-product');
const Blog = require('./blog');
const GraphQLQueryBuilder = require('./graphql-builder');
const CacheManager = require('./cache');
/**
* Iluria SDK - Cliente JavaScript para API GraphQL do Iluria
*/
class IluriaSDK {
constructor(config = {}) {
// Se config for uma string, assume que é a API Key (mantém compatibilidade)
if (typeof config === 'string') {
config = { apiKey: config };
}
const {
apiKey,
token,
baseURL = process.env.ILURIA_API_URL || this.detectBaseURL(),
headers = {},
timeout = 30000,
cache = {}
} = config;
// API Key não é mais obrigatória!
// Pode usar: apiKey, token, ou nenhum (host-based)
// Constrói headers condicionalmente
const defaultHeaders = {
'Content-Type': 'application/json',
...headers
};
// Adiciona autenticação se fornecida
if (apiKey) {
defaultHeaders['X-API-Key'] = apiKey;
} else if (token) {
defaultHeaders['Authorization'] = `Bearer ${token}`;
}
// Se não tem nem apiKey nem token, vai funcionar por host (zero config!)
// HTTP Client com GraphQL
this.http = new HttpClient(baseURL, defaultHeaders);
this.http.setTimeout(timeout);
// Cache Manager
this.cacheManager = cache === false ? false : new CacheManager({
enabled: cache !== false,
maxMemorySize: cache.maxMemorySize || cache.maxSize || 50,
ttl: cache.ttl || 60000,
storage: cache.storage !== undefined ? cache.storage : 'session',
storageTtl: cache.storageTtl || 300000,
enableIndexedDB: cache.enableIndexedDB || false,
debug: cache.debug || false,
...cache
});
// Módulos com cache compartilhado
this.store = new Store(this.http, this.cacheManager);
this.product = new Product(this.http, this.cacheManager);
this.promotion = new Promotion(this.http, this.cacheManager);
this.collection = new Collection(this.http, this.cacheManager);
this.combinedProduct = new CombinedProduct(this.http, this.cacheManager);
this.blog = new Blog(this.http, this.cacheManager, { debug: cache.debug || false });
// Query Builder para queries customizadas
this.queryBuilder = new GraphQLQueryBuilder();
// Configuração
this.config = {
baseURL,
apiKey,
token,
headers: defaultHeaders,
timeout,
cache: cache,
authMethod: apiKey ? 'apiKey' : token ? 'token' : 'host'
};
}
/**
* Executa uma query GraphQL customizada
* @param {string} query - Query GraphQL
* @param {object} variables - Variáveis da query
* @returns {object} - Resultado da query
*/
async query(query, variables = {}) {
return this.http.graphql(query, variables);
}
/**
* Executa múltiplas queries em uma única requisição
* @param {object} queries - Objeto com queries nomeadas
* @returns {object} - Resultados das queries
*/
async batchQuery(queries) {
const queryParts = [];
const allVariables = {};
Object.entries(queries).forEach(([name, { query, variables }]) => {
queryParts.push(`${name}: ${query}`);
Object.assign(allVariables, variables);
});
const combinedQuery = `query { ${queryParts.join(' ')} }`;
return this.http.graphql(combinedQuery, allVariables);
}
/**
* Define a API Key
*/
setApiKey(apiKey) {
// Remove token se existir (apenas um método de auth por vez)
if (this.config.token) {
this.http.setHeader('Authorization', null);
delete this.config.token;
}
if (apiKey) {
this.http.setApiKey(apiKey);
this.config.apiKey = apiKey;
this.config.authMethod = 'apiKey';
} else {
// Remove API Key se passar null/undefined
this.http.setApiKey(null);
delete this.config.apiKey;
this.config.authMethod = 'host';
}
}
/**
* Define o Token JWT
*/
setToken(token) {
// Remove API Key se existir (apenas um método de auth por vez)
if (this.config.apiKey) {
this.http.setApiKey(null);
delete this.config.apiKey;
}
if (token) {
this.http.setHeader('Authorization', `Bearer ${token}`);
this.config.token = token;
this.config.authMethod = 'token';
} else {
// Remove token se passar null/undefined
this.http.setHeader('Authorization', null);
delete this.config.token;
this.config.authMethod = 'host';
}
}
/**
* Define a URL base
*/
setBaseURL(baseURL) {
this.http.client.defaults.baseURL = baseURL;
this.config.baseURL = baseURL;
}
/**
* Define o timeout das requisições
*/
setTimeout(timeout) {
this.http.setTimeout(timeout);
this.config.timeout = timeout;
}
/**
* Detecta a URL base automaticamente
* @private
*/
detectBaseURL() {
// Sempre aponta para o storefront
// Em desenvolvimento: localhost:8080
// Em produção: api.iluria.com
// Browser
if (typeof window !== 'undefined') {
// Desenvolvimento local - qualquer localhost/127.0.0.1
if (window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1' ||
window.location.hostname.startsWith('192.168.')) {
return 'http://localhost:8080';
}
// Produção - sempre usa o storefront central
return 'https://api.iluria.com';
}
// Node.js
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'dev') {
return 'http://localhost:8080';
}
// Produção
return 'https://api.iluria.com';
}
/**
* Limpa todo o cache
*/
async clearCache() {
if (this.cacheManager && this.cacheManager !== false) {
await this.cacheManager.clear();
}
}
/**
* Invalida cache por pattern
* @param {string} pattern - Pattern para invalidar (ex: "product:*", "store:*")
* @returns {number} - Número de items invalidados
*/
async invalidateCache(pattern) {
if (this.cacheManager && this.cacheManager !== false) {
return await this.cacheManager.invalidate(pattern);
}
return 0;
}
/**
* Retorna estatísticas do cache
* @returns {object} - Estatísticas do cache
*/
async getCacheStats() {
if (this.cacheManager && this.cacheManager !== false) {
return await this.cacheManager.getStats();
}
return null;
}
/**
* Inspeciona um item específico no cache
* @param {string} key - Chave do item
* @returns {object} - Informações sobre o item
*/
async inspectCache(key) {
if (this.cacheManager && this.cacheManager !== false && typeof this.cacheManager.inspect === 'function') {
return await this.cacheManager.inspect(key);
}
return null;
}
}
module.exports = IluriaSDK;