iluria-sdk
Version:
SDK oficial do Iluria para integração com lojas e criação de frontends customizados
128 lines (113 loc) • 3.63 kB
JavaScript
/**
* HTTP Client para Browser - Usa fetch nativo
* Compatível com a interface do HttpClient original mas sem dependências externas
*/
class HttpBrowserClient {
constructor(baseURL, headers = {}) {
this.baseURL = baseURL;
this.defaultHeaders = {
'Content-Type': 'application/json',
...headers
};
this.timeout = 30000;
}
/**
* Executa uma query ou mutation GraphQL
* @param {string} query - Query GraphQL
* @param {object} variables - Variáveis da query
* @returns {object} - Dados da resposta GraphQL
*/
async graphql(query, variables = {}) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
const response = await fetch(`${this.baseURL}/graphql`, {
method: 'POST',
headers: this.defaultHeaders,
body: JSON.stringify({ query, variables }),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
error.status = response.status;
try {
const errorData = await response.json();
if (errorData.errors) {
error.message = errorData.errors[0]?.message || 'GraphQL Error';
error.errors = errorData.errors;
}
} catch (e) {
// Ignore JSON parse errors
}
throw error;
}
const result = await response.json();
if (result.errors && result.errors.length > 0) {
const error = new Error(result.errors[0].message || 'GraphQL Error');
error.errors = result.errors;
throw error;
}
return result.data;
} catch (error) {
if (error.name === 'AbortError') {
const timeoutError = new Error('Request timeout');
timeoutError.status = 0;
throw timeoutError;
}
throw error;
}
}
/**
* Define um header
* @param {string} key - Nome do header
* @param {string} value - Valor do header
*/
setHeader(key, value) {
if (value === null || value === undefined) {
delete this.defaultHeaders[key];
} else {
this.defaultHeaders[key] = value;
}
}
/**
* Define a API Key
* @param {string} apiKey - API Key
*/
setApiKey(apiKey) {
this.setHeader('X-API-Key', apiKey);
}
/**
* Define o timeout
* @param {number} timeout - Timeout em ms
*/
setTimeout(timeout) {
this.timeout = timeout;
}
/**
* Método GET (para compatibilidade, mas converte para GraphQL)
* @param {string} path - Path da requisição
* @param {object} params - Parâmetros da query
*/
async get(path, params = {}) {
// Este método existe apenas para compatibilidade
// Na prática, tudo é GraphQL
console.warn('HttpBrowserClient.get() é deprecated. Use graphql() diretamente.');
return {};
}
/**
* Método POST (para compatibilidade, mas converte para GraphQL)
* @param {string} path - Path da requisição
* @param {object} data - Dados a enviar
*/
async post(path, data = {}) {
// Este método existe apenas para compatibilidade
// Na prática, tudo é GraphQL
console.warn('HttpBrowserClient.post() é deprecated. Use graphql() diretamente.');
return {};
}
}
// Export para uso no browser
if (typeof module !== 'undefined' && module.exports) {
module.exports = HttpBrowserClient;
}