UNPKG

@chiraitori/hoyolab-core

Version:

Core utilities for HoYoLab automation - daily check-ins and code redemption with smart rate limiting

68 lines (56 loc) 1.87 kB
class HttpClient { constructor(userAgent = 'HoyoLabCore/1.0.0') { this.userAgent = userAgent; } async request(url, options = {}) { const { default: fetch } = await import('node-fetch'); const config = { method: options.method || 'GET', headers: { 'User-Agent': this.userAgent, 'Accept': 'application/json', ...options.headers }, ...options }; if (options.searchParams) { const params = new URLSearchParams(options.searchParams); url += (url.includes('?') ? '&' : '?') + params.toString(); } if (options.body && typeof options.body === 'object') { config.body = JSON.stringify(options.body); config.headers['Content-Type'] = 'application/json'; } try { const response = await fetch(url, config); if (!response.ok && options.throwHttpErrors !== false) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } let data; const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { data = await response.json(); } else { data = await response.text(); } return { statusCode: response.status, headers: response.headers, body: data, ok: response.ok }; } catch (error) { if (error.name === 'TypeError' && error.message.includes('fetch')) { throw new Error(`Network error: ${error.message}`); } throw error; } } async get(url, options = {}) { return this.request(url, { ...options, method: 'GET' }); } async post(url, options = {}) { return this.request(url, { ...options, method: 'POST' }); } } module.exports = HttpClient;