Files
Pennyzo-Frontend/scripts/api-status-checker.js
ectasy663 ebb7fcaac8 Fix API endpoint configuration with environment-aware URLs
- Add environment-based API URL configuration (dev: localhost:8000, prod: api.pennyzo.com)
- Update PennyzoApiService to use centralized config with timeout settings
- Fix API status checker scripts to load .env variables using dotenv
- Add environment management scripts (set-env.ps1) with npm shortcuts
- Create comprehensive configuration testing and validation tools
- Add TypeScript definitions for Vite environment variables
- Update all documentation with new environment configuration instructions
- Install dotenv package for Node.js environment variable loading
- All APIs now correctly use environment-appropriate URLs automatically
2025-09-25 14:40:20 +05:30

144 lines
4.9 KiB
JavaScript

/**
* Pennyzo General API Status Checker
*
* This script checks the status of all primary endpoints of the Pennyzo General API
* and logs the results to the console.
*/
// Load environment variables from .env file
require('dotenv').config();
const axios = require('axios');
const chalk = require('chalk'); // For colorful console output
// Define the base URL based on environment
const BASE_URL = process.env.VITE_API_BASE_URL ||
process.env.API_BASE_URL ||
(process.env.NODE_ENV === 'production' ?
'https://api.pennyzo.com/api/v1/general' :
'http://localhost:8000');
// Test credentials (replace with actual test credentials if available)
const TEST_CREDENTIALS = {
email: 'test@example.com',
password: 'Password123!'
};
// Store the access token for authenticated requests
let accessToken = null;
// Helper function to log API call results
function logResult(endpoint, method, status, statusCode, error = null) {
const statusText = status === 'SUCCESS' ? chalk.green(status) : chalk.red(status);
const statusCodeText = statusCode ? `(${statusCode})` : '';
console.log(`${chalk.yellow(method)} ${chalk.blue(endpoint)}: ${statusText} ${statusCodeText}`);
if (error) {
console.log(` Error: ${chalk.red(error.message)}`);
if (error.response?.data) {
console.log(` Details: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
// Helper function to make API calls and log results
async function callApi(endpoint, method = 'GET', data = null, authenticated = false) {
const url = `${BASE_URL}${endpoint}`;
const config = {};
if (authenticated && accessToken) {
config.headers = {
'Authorization': `Bearer ${accessToken}`
};
}
// Special handling for form-urlencoded content type (login endpoint)
if (endpoint === '/auth/login') {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// Convert data to URLSearchParams for login endpoint
if (data) {
const params = new URLSearchParams();
params.append('username', data.email); // API uses username field for email
params.append('password', data.password);
data = params;
}
}
try {
let response;
switch (method) {
case 'GET':
response = await axios.get(url, config);
break;
case 'POST':
response = await axios.post(url, data, config);
break;
default:
throw new Error(`Unsupported method: ${method}`);
}
logResult(endpoint, method, 'SUCCESS', response.status);
return { success: true, data: response.data };
} catch (error) {
const statusCode = error.response?.status || 'N/A';
logResult(endpoint, method, 'FAILED', statusCode, error);
return { success: false, error };
}
}
// Main function to run the API checks
async function checkApiStatus() {
console.log(chalk.bold('\n=== Pennyzo General API Status Checker ===\n'));
console.log(chalk.bold('\n--- Testing Public Endpoints ---\n'));
// Test system health endpoint
const healthResult = await callApi('/system/health');
if (healthResult.success) {
console.log(` API Status: ${healthResult.data.status}`);
console.log(` Environment: ${healthResult.data.environment}`);
console.log(` Version: ${healthResult.data.version}`);
console.log(` Message: ${healthResult.data.message}\n`);
}
// Test registration company identity rules endpoint
await callApi('/registration/company/identity-rules');
console.log(chalk.bold('\n--- Testing Authentication Flow ---\n'));
// Try to authenticate with test credentials
const loginResult = await callApi('/auth/login', 'POST', TEST_CREDENTIALS);
if (loginResult.success) {
accessToken = loginResult.data.access_token;
console.log(chalk.green(' Authentication successful. Access token received.'));
console.log(` Token type: ${loginResult.data.token_type}`);
if (loginResult.data.expires_in) {
console.log(` Token expires in: ${loginResult.data.expires_in} seconds\n`);
}
console.log(chalk.bold('\n--- Testing Authenticated Endpoints ---\n'));
// Test authenticated endpoints
await callApi('/auth/me', 'GET', null, true);
await callApi('/users/profile', 'GET', null, true);
await callApi('/users/stats', 'GET', null, true);
await callApi('/users/membership-info', 'GET', null, true);
} else {
console.log(chalk.red(' Authentication failed. Cannot test authenticated endpoints.'));
console.log(' Note: This is expected if using placeholder credentials.');
console.log(' To test authenticated endpoints, update the TEST_CREDENTIALS with valid credentials.\n');
}
console.log(chalk.bold('\n=== API Status Check Complete ===\n'));
}
// Execute the API checker
checkApiStatus().catch(error => {
console.error(chalk.red('\nUnexpected error during API status check:'));
console.error(error);
});