UNPKG

@trendmoon/api-client

Version:
249 lines 10.2 kB
"use strict"; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TrendmoonApiClient = void 0; const env_js_1 = require("../config/env.js"); const node_fetch_1 = __importDefault(require("node-fetch")); const debug_js_1 = require("../utils/debug.js"); const errors_js_1 = require("../utils/errors.js"); const retry_js_1 = require("../utils/retry.js"); class TrendmoonApiClient { constructor(enableRetry = true) { this.baseUrl = env_js_1.config.TRENDMOON_API_URL; this.apiKey = env_js_1.config.TRENDMOON_API_KEY; this.enableRetry = enableRetry; } async request(endpoint, method, params, body) { const operation = () => this.makeRequest(endpoint, method, params, body); if (this.enableRetry) { return (0, retry_js_1.withRetry)(operation, retry_js_1.DEFAULT_RETRY_OPTIONS); } return operation(); } async makeRequest(endpoint, method, params, body) { const url = new URL(`${this.baseUrl}${endpoint}`); const headers = { 'Api-key': this.apiKey, 'accept': 'application/json', }; if (body && method !== 'GET') { headers['Content-Type'] = 'application/json'; } // Add query parameters for GET requests if (method === 'GET' && params) { Object.keys(params).forEach(key => { const value = params[key]; if (value !== undefined && value !== null) { if (Array.isArray(value)) { value.forEach(item => url.searchParams.append(key, item)); } else { url.searchParams.append(key, String(value)); } } }); } debug_js_1.debugLog.info(`Calling API: ${method} ${url.toString()}`); debug_js_1.debugLog.info('Headers:', Object.assign(Object.assign({}, headers), { 'Api-key': '***********' })); // Mask API key if (body) { debug_js_1.debugLog.info('Request Body:', body); } try { const response = await (0, node_fetch_1.default)(url.toString(), { method, headers, body: body ? JSON.stringify(body) : undefined, }); debug_js_1.debugLog.info('Response status:', response.status); debug_js_1.debugLog.info('Response headers:', Object.fromEntries(response.headers.entries())); if (!response.ok) { const errorText = await response.text(); debug_js_1.debugLog.error('Error response body:', errorText); let errorMessage = `API Error: ${response.status} - ${response.statusText}`; try { const errorJson = JSON.parse(errorText); errorMessage = errorJson.message || errorMessage; if (errorJson.detail) { errorMessage += `\nDetails: ${JSON.stringify(errorJson.detail)}`; } } catch (e) { // Not a JSON error, use plain text } throw (0, errors_js_1.createErrorFromResponse)(response.status, response.statusText, errorText); } const data = await response.json(); debug_js_1.debugLog.info('Received data (truncated):', JSON.stringify(data).substring(0, 500) + (JSON.stringify(data).length > 500 ? '...' : '')); return data; } catch (error) { debug_js_1.debugLog.error('Detailed error in API request:', error); // Re-throw our custom errors as-is if (error instanceof errors_js_1.TrendmoonApiError) { throw error; } // Wrap network/fetch errors if (error instanceof Error) { if (error.name === 'FetchError' || error.message.includes('fetch')) { throw new errors_js_1.TrendmoonNetworkError(`Network error: ${error.message}`, error); } } // Fallback for unknown errors throw new errors_js_1.TrendmoonApiError(error instanceof Error ? error.message : 'Unknown error occurred'); } } // --- / (Root) --- async getRoot() { return this.request('/', 'GET'); } // --- /chats/{group_username} --- async getChatByUsername(params) { const { group_username } = params, queryParams = __rest(params, ["group_username"]); return this.request(`/chats/${group_username}`, 'GET', queryParams); } // --- /chat_activity/ --- async getChatActivity(params) { return this.request('/chat_activity/', 'GET', params); } // --- /messages/chat --- async getMessagesForChat(params) { return this.request('/messages/chat', 'GET', params); } // --- /messages/search --- async searchMessages(params) { return this.request('/messages/search', 'GET', params); } // --- /messages/timeframe --- async getMessagesWithinTimeframe(params) { return this.request('/messages/timeframe', 'GET', params); } // --- /messages/user --- async getMessagesForUser(params) { return this.request('/messages/user', 'GET', params); } // --- /users/search --- async searchUsers(params) { return this.request('/users/search', 'GET', params); } // --- /users/{identifier} --- async getUserByIdentifier(params) { const { identifier } = params, queryParams = __rest(params, ["identifier"]); return this.request(`/users/${identifier}`, 'GET', queryParams); } // --- /categories/dominance --- async getCategoryDominanceForAssets(params) { return this.request('/categories/dominance', 'GET', params); } // --- /categories/top_categories --- async getTopCategoriesDominance(params) { return this.request('/categories/top_categories', 'GET', params); } // --- /categories/all --- async getAllCategories() { return this.request('/categories/all', 'GET'); } // --- /coins/search --- async searchCoins(params) { return this.request('/coins/search', 'GET', params); } // --- /coins/platforms --- async getPlatforms() { return this.request('/coins/platforms', 'GET'); } // --- /coins/details --- async getCoinDetails(params) { return this.request('/coins/details', 'GET', params); } // --- /social/trend --- async getSocialTrend(params) { return this.request('/social/trend', 'GET', params); } // --- /social/keyword --- async getKeywordTrend(params) { return this.request('/social/keyword', 'GET', params); } // --- /social/project_summary --- async getProjectSummary(params) { return this.request('/social/project_summary', 'GET', params); } // --- /social/topic_posts --- async getTopicPosts(params) { return this.request('/social/topic_posts', 'GET', params); } // --- /social/topic_news --- async getTopicNews(params) { return this.request('/social/topic_news', 'GET', params); } // --- /social/topic_summary --- async getTopicSummary(params) { return this.request('/social/topic_summary', 'GET', params); } // --- /social/search --- async searchSocialPosts(params) { return this.request('/social/search', 'GET', params); } // --- /social/trends --- async getSocialTrends(params) { return this.request('/social/trends', 'GET', params); } // --- /groups/status --- async getGroupsServiceStatus() { return this.request('/groups/status', 'GET'); } // --- /groups/{group_username} --- async getSpecificGroup(params) { const { group_username } = params, queryParams = __rest(params, ["group_username"]); return this.request(`/groups/${group_username}`, 'GET', queryParams); } // --- /groups/add_group --- async addNewGroup(body) { return this.request('/groups/add_group', 'POST', undefined, body); } // --- /groups/ --- async getAllGroups() { return this.request('/groups/', 'GET'); } // --- /get_top_alerts_today --- async getTopAlertsToday() { return this.request('/get_top_alerts_today', 'GET'); } // --- /get_top_categories_today --- async getTopCategoriesToday() { // Note: TopCategoriesResponse is not defined in the provided Schema.ts. // Assuming it's an array of some category type or string array based on context. // If it's a new type, you'll need to define it in Schema.ts // For now, I'll assume it's just a placeholder or needs to be defined. return this.request('/get_top_categories_today', 'GET'); } // --- /get_top_category_alerts --- async getTopCategoryAlerts() { return this.request('/get_top_category_alerts', 'GET'); } // --- /get_category_coins_legacy --- async getCategoryCoinsLegacy(params) { return this.request('/get_category_coins_legacy', 'GET', params); } // --- /get_category_coins --- async getCategoryCoins(params) { return this.request('/get_category_coins', 'GET', params); } // --- /status (general status) --- async getGeneralStatus() { return this.request('/status', 'GET'); } } exports.TrendmoonApiClient = TrendmoonApiClient; //# sourceMappingURL=TrendmoonApiClient.js.map