Add Pennyzo API status checker scripts, report viewer, and documentation
This commit is contained in:
253
scripts/README.md
Normal file
253
scripts/README.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# Pennyzo API Status Checker
|
||||
|
||||
Node.js scripts for checking the status of all primary endpoints of the Pennyzo General API.
|
||||
|
||||
This package includes two versions of the script:
|
||||
|
||||
- `api-status-checker.js` - Basic version with console output
|
||||
- `api-status-checker-extended.js` - Extended version with report generation and additional features
|
||||
|
||||
## Overview
|
||||
|
||||
These scripts test both public and authenticated endpoints of the Pennyzo General API and log the results to the console. The scripts perform the following checks:
|
||||
|
||||
### Public Endpoints:
|
||||
|
||||
- GET `/system/health`
|
||||
- GET `/registration/company/identity-rules`
|
||||
|
||||
### Authentication Flow:
|
||||
|
||||
- POST `/auth/login` (using placeholder credentials)
|
||||
|
||||
### Authenticated Endpoints (only if login is successful):
|
||||
|
||||
- GET `/auth/me`
|
||||
- GET `/users/profile`
|
||||
- GET `/users/stats`
|
||||
- GET `/users/membership-info`
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node.js (version 14 or higher recommended)
|
||||
- npm packages:
|
||||
- axios (for HTTP requests)
|
||||
- chalk (for colorful console output)
|
||||
|
||||
## Installation
|
||||
|
||||
Both required packages are already installed in the project.
|
||||
|
||||
## Usage
|
||||
|
||||
### Using npm Scripts (Recommended)
|
||||
|
||||
The following npm scripts are available for checking API status:
|
||||
|
||||
```bash
|
||||
# Run basic API check
|
||||
npm run api:check
|
||||
|
||||
# Run extended API check with report generation
|
||||
npm run api:check:extended
|
||||
|
||||
# Run extended API check with verbose output
|
||||
npm run api:check:verbose
|
||||
|
||||
# Run extended API check with real credentials
|
||||
npm run api:check:real
|
||||
```
|
||||
|
||||
### Direct Node Execution
|
||||
|
||||
To run the scripts directly with Node:
|
||||
|
||||
#### Basic Script
|
||||
|
||||
```powershell
|
||||
node scripts/api-status-checker.js
|
||||
```
|
||||
|
||||
#### Extended Script
|
||||
|
||||
```powershell
|
||||
node scripts/api-status-checker-extended.js [options]
|
||||
```
|
||||
|
||||
Available options:
|
||||
|
||||
- `--verbose`: Show detailed response data
|
||||
- `--no-report`: Don't save a report file
|
||||
- `--use-real-credentials`: Use credentials from environment variables
|
||||
|
||||
### Helper PowerShell Script
|
||||
|
||||
For additional flexibility, a PowerShell helper script is provided:
|
||||
|
||||
```powershell
|
||||
.\scripts\run-api-check.ps1 [-Verbose] [-NoReport] [-UseRealCredentials] [-Extended]
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```powershell
|
||||
# Run basic script
|
||||
.\scripts\run-api-check.ps1
|
||||
|
||||
# Run extended script with verbose output
|
||||
.\scripts\run-api-check.ps1 -Extended -Verbose
|
||||
|
||||
# Run extended script with real credentials
|
||||
.\scripts\run-api-check.ps1 -Extended -UseRealCredentials
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Basic Configuration
|
||||
|
||||
You can modify the test credentials in the script to use valid credentials for testing authenticated endpoints:
|
||||
|
||||
```javascript
|
||||
// Test credentials (replace with actual test credentials if available)
|
||||
const TEST_CREDENTIALS = {
|
||||
email: "your-test-email@example.com",
|
||||
password: "your-test-password",
|
||||
};
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
For the extended script, you can set environment variables for secure credential management:
|
||||
|
||||
```powershell
|
||||
$env:PENNYZO_TEST_EMAIL = "your-test-email@example.com"
|
||||
$env:PENNYZO_TEST_PASSWORD = "your-test-password"
|
||||
```
|
||||
|
||||
Then run with the `--use-real-credentials` flag:
|
||||
|
||||
```powershell
|
||||
node scripts/api-status-checker-extended.js --use-real-credentials
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
The script provides detailed output for each API call:
|
||||
|
||||
- Endpoint being tested
|
||||
- HTTP method
|
||||
- Status (SUCCESS or FAILED)
|
||||
- HTTP status code
|
||||
- Error details (if applicable)
|
||||
|
||||
For the system health endpoint, additional information is displayed:
|
||||
|
||||
- API Status
|
||||
- Environment
|
||||
- Version
|
||||
- Message
|
||||
|
||||
## Features
|
||||
|
||||
### Basic Script
|
||||
|
||||
- Tests both public and authenticated endpoints
|
||||
- Colorful console output with chalk
|
||||
- Clear status indicators
|
||||
|
||||
### Extended Script (Additional Features)
|
||||
|
||||
- Saves detailed reports to JSON files (in a `reports` folder)
|
||||
- Provides response time measurements
|
||||
- Supports command line arguments
|
||||
- Environment variable support for credentials
|
||||
- Verbose mode for detailed output
|
||||
- Summary statistics
|
||||
|
||||
## Example Output
|
||||
|
||||
### Basic Script Output
|
||||
|
||||
```
|
||||
=== Pennyzo General API Status Checker ===
|
||||
|
||||
--- Testing Public Endpoints ---
|
||||
|
||||
GET /system/health: SUCCESS (200)
|
||||
API Status: operational
|
||||
Environment: production
|
||||
Version: 1.0.0
|
||||
Message: Service is healthy
|
||||
|
||||
GET /registration/company/identity-rules: SUCCESS (200)
|
||||
|
||||
--- Testing Authentication Flow ---
|
||||
|
||||
POST /auth/login: FAILED (401)
|
||||
Error: Request failed with status code 401
|
||||
Details: {
|
||||
"error": {
|
||||
"type": "unauthorized",
|
||||
"code": 401,
|
||||
"message": "Invalid credentials"
|
||||
}
|
||||
}
|
||||
Authentication failed. Cannot test authenticated endpoints.
|
||||
Note: This is expected if using placeholder credentials.
|
||||
To test authenticated endpoints, update the TEST_CREDENTIALS with valid credentials.
|
||||
|
||||
=== API Status Check Complete ===
|
||||
```
|
||||
|
||||
### Extended Script Output
|
||||
|
||||
```
|
||||
=== Pennyzo General API Status Checker ===
|
||||
|
||||
Timestamp: 2025-09-25T10:15:30.123Z
|
||||
Base URL: https://api.pennyzo.com/api/v1/general
|
||||
Save Report: Yes
|
||||
Verbose Mode: Yes
|
||||
Using Real Credentials: No
|
||||
|
||||
--- Testing Public Endpoints ---
|
||||
|
||||
GET /system/health: SUCCESS (200) [342ms]
|
||||
API Status: operational
|
||||
Environment: production
|
||||
Version: 1.0.0
|
||||
Message: Service is healthy
|
||||
|
||||
GET /registration/company/identity-rules: SUCCESS (200) [285ms]
|
||||
|
||||
--- Testing Authentication Flow ---
|
||||
|
||||
POST /auth/login: FAILED (401) [520ms]
|
||||
Error: Request failed with status code 401
|
||||
|
||||
Authentication failed. Cannot test authenticated endpoints.
|
||||
Note: This is expected if using placeholder credentials.
|
||||
To test authenticated endpoints, use the --use-real-credentials flag
|
||||
and set PENNYZO_TEST_EMAIL and PENNYZO_TEST_PASSWORD environment variables.
|
||||
|
||||
=== API Status Check Summary ===
|
||||
|
||||
Total endpoints checked: 3
|
||||
Successful: 2
|
||||
Failed: 1
|
||||
Success rate: 66.7%
|
||||
Total time: 1.15 seconds
|
||||
|
||||
Report saved to: c:\Users\naman\OneDrive\Desktop\Pennyzo Web\reports\api-status-2025-09-25T10-15-30.123Z.json
|
||||
|
||||
=== API Status Check Complete ===
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The scripts use placeholder credentials by default, which will likely fail authentication. This is expected behavior.
|
||||
- To properly test authenticated endpoints, use real credentials via environment variables or direct script modification.
|
||||
- The extended script saves reports to a `reports` directory for historical tracking of API status.
|
||||
- All API calls and their results are logged to the console and (optionally) to report files.
|
||||
- Response times are logged to help identify slow endpoints.
|
||||
- A HTML report viewer is included at `reports/report-viewer.html` for visualizing the JSON reports.
|
||||
101
scripts/SUMMARY.md
Normal file
101
scripts/SUMMARY.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# Pennyzo API Status Checker
|
||||
|
||||
This project provides comprehensive tools for checking the status of the Pennyzo General API endpoints. It includes both basic and extended versions of the API status checker, along with supporting tools and documentation.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
scripts/
|
||||
├── api-status-checker.js # Basic API status checker
|
||||
├── api-status-checker-extended.js # Extended API status checker with additional features
|
||||
├── run-api-check.ps1 # PowerShell helper script
|
||||
└── README.md # Documentation for the scripts
|
||||
|
||||
reports/
|
||||
├── example-report.json # Sample report file
|
||||
├── report-viewer.html # HTML tool for visualizing reports
|
||||
├── .gitignore # Git configuration for reports
|
||||
└── README.md # Documentation for the reports directory
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
1. **Basic API Status Checker**
|
||||
|
||||
- Tests both public and authenticated endpoints
|
||||
- Colorful console output
|
||||
- Automatic token management
|
||||
|
||||
2. **Extended API Status Checker**
|
||||
|
||||
- All features of the basic checker
|
||||
- Saves detailed reports to JSON files
|
||||
- Provides response time measurements
|
||||
- Support for command line arguments
|
||||
- Environment variable support for credentials
|
||||
|
||||
3. **Report Viewer**
|
||||
|
||||
- HTML-based visualization tool
|
||||
- Interactive endpoint details
|
||||
- Summary statistics
|
||||
- Color-coded status indicators
|
||||
|
||||
4. **Helper Tools**
|
||||
- PowerShell script for flexible execution
|
||||
- npm scripts for convenient access
|
||||
- Example report for reference
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Using npm Scripts
|
||||
|
||||
```bash
|
||||
# Run basic API check
|
||||
npm run api:check
|
||||
|
||||
# Run extended API check with report generation
|
||||
npm run api:check:extended
|
||||
|
||||
# Run extended API check with verbose output
|
||||
npm run api:check:verbose
|
||||
|
||||
# Run extended API check with real credentials
|
||||
npm run api:check:real
|
||||
```
|
||||
|
||||
### Using Environment Variables
|
||||
|
||||
For secure credential management with real credentials:
|
||||
|
||||
```powershell
|
||||
$env:PENNYZO_TEST_EMAIL = "your-test-email@example.com"
|
||||
$env:PENNYZO_TEST_PASSWORD = "your-test-password"
|
||||
npm run api:check:real
|
||||
```
|
||||
|
||||
### Viewing Reports
|
||||
|
||||
After running the extended script, reports are saved to the `reports` directory. To view a report:
|
||||
|
||||
1. Open `reports/report-viewer.html` in a web browser
|
||||
2. Click "Choose Report File" to select a JSON report
|
||||
3. Review the report details
|
||||
|
||||
## Summary of API Endpoints Tested
|
||||
|
||||
### Public Endpoints
|
||||
|
||||
- GET `/system/health`
|
||||
- GET `/registration/company/identity-rules`
|
||||
|
||||
### Authentication Flow
|
||||
|
||||
- POST `/auth/login`
|
||||
|
||||
### Authenticated Endpoints
|
||||
|
||||
- GET `/auth/me`
|
||||
- GET `/users/profile`
|
||||
- GET `/users/stats`
|
||||
- GET `/users/membership-info`
|
||||
234
scripts/api-status-checker-extended.js
Normal file
234
scripts/api-status-checker-extended.js
Normal file
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Pennyzo General API Status Checker (Extended Version)
|
||||
*
|
||||
* This script checks the status of all primary endpoints of the Pennyzo General API,
|
||||
* logs the results to the console, and optionally saves a detailed report to a file.
|
||||
*
|
||||
* Features:
|
||||
* - Tests both public and authenticated endpoints
|
||||
* - Provides detailed error information
|
||||
* - Generates a report with timestamp
|
||||
* - Saves results to a file
|
||||
* - Supports command line arguments for customization
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const chalk = require('chalk');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Parse command line arguments
|
||||
const args = process.argv.slice(2);
|
||||
const saveReport = !args.includes('--no-report');
|
||||
const verbose = args.includes('--verbose');
|
||||
const useRealCredentials = args.includes('--use-real-credentials');
|
||||
|
||||
// Define the base URL
|
||||
const BASE_URL = 'https://api.pennyzo.com/api/v1/general';
|
||||
|
||||
// Test credentials
|
||||
const TEST_CREDENTIALS = {
|
||||
email: useRealCredentials ? process.env.PENNYZO_TEST_EMAIL || 'test@example.com' : 'test@example.com',
|
||||
password: useRealCredentials ? process.env.PENNYZO_TEST_PASSWORD || 'Password123!' : 'Password123!'
|
||||
};
|
||||
|
||||
// Store the access token for authenticated requests
|
||||
let accessToken = null;
|
||||
|
||||
// Store all results for reporting
|
||||
const results = [];
|
||||
const startTime = new Date();
|
||||
|
||||
// Helper function to log API call results
|
||||
function logResult(endpoint, method, status, statusCode, responseTime, data = null, error = null) {
|
||||
const statusText = status === 'SUCCESS' ? chalk.green(status) : chalk.red(status);
|
||||
const statusCodeText = statusCode ? `(${statusCode})` : '';
|
||||
const responseTimeText = responseTime ? `[${responseTime}ms]` : '';
|
||||
|
||||
console.log(`${chalk.yellow(method)} ${chalk.blue(endpoint)}: ${statusText} ${statusCodeText} ${responseTimeText}`);
|
||||
|
||||
if (error) {
|
||||
console.log(` Error: ${chalk.red(error.message)}`);
|
||||
if (error.response?.data && verbose) {
|
||||
console.log(` Details: ${JSON.stringify(error.response.data, null, 2)}`);
|
||||
}
|
||||
} else if (data && verbose) {
|
||||
const dataPreview = JSON.stringify(data).substring(0, 100) + (JSON.stringify(data).length > 100 ? '...' : '');
|
||||
console.log(` Data: ${dataPreview}`);
|
||||
}
|
||||
|
||||
// Store result for reporting
|
||||
results.push({
|
||||
endpoint,
|
||||
method,
|
||||
status,
|
||||
statusCode: statusCode || 'N/A',
|
||||
responseTime,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error ? {
|
||||
message: error.message,
|
||||
details: error.response?.data || null
|
||||
} : null,
|
||||
data: data && verbose ? data : null
|
||||
});
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
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}`);
|
||||
}
|
||||
|
||||
const responseTime = Date.now() - startTime;
|
||||
logResult(endpoint, method, 'SUCCESS', response.status, responseTime, response.data);
|
||||
return { success: true, data: response.data, responseTime };
|
||||
} catch (error) {
|
||||
const responseTime = Date.now() - startTime;
|
||||
const statusCode = error.response?.status || 'N/A';
|
||||
logResult(endpoint, method, 'FAILED', statusCode, responseTime, null, error);
|
||||
return { success: false, error, responseTime };
|
||||
}
|
||||
}
|
||||
|
||||
// Function to generate and save a report
|
||||
function saveReportToFile() {
|
||||
const endTime = new Date();
|
||||
const duration = (endTime - startTime) / 1000; // in seconds
|
||||
|
||||
// Count successes and failures
|
||||
const successCount = results.filter(r => r.status === 'SUCCESS').length;
|
||||
const failureCount = results.filter(r => r.status === 'FAILED').length;
|
||||
|
||||
const report = {
|
||||
title: 'Pennyzo API Status Check Report',
|
||||
timestamp: endTime.toISOString(),
|
||||
duration: `${duration.toFixed(2)} seconds`,
|
||||
summary: {
|
||||
totalEndpoints: results.length,
|
||||
successful: successCount,
|
||||
failed: failureCount,
|
||||
successRate: `${((successCount / results.length) * 100).toFixed(1)}%`
|
||||
},
|
||||
baseUrl: BASE_URL,
|
||||
results: results
|
||||
};
|
||||
|
||||
const reportDir = path.join(__dirname, '../reports');
|
||||
if (!fs.existsSync(reportDir)) {
|
||||
fs.mkdirSync(reportDir, { recursive: true });
|
||||
}
|
||||
|
||||
const reportPath = path.join(reportDir, `api-status-${endTime.toISOString().replace(/:/g, '-')}.json`);
|
||||
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
|
||||
|
||||
console.log(chalk.bold(`\nReport saved to: ${reportPath}`));
|
||||
}
|
||||
|
||||
// Main function to run the API checks
|
||||
async function checkApiStatus() {
|
||||
console.log(chalk.bold('\n=== Pennyzo General API Status Checker ===\n'));
|
||||
console.log(`Timestamp: ${startTime.toISOString()}`);
|
||||
console.log(`Base URL: ${BASE_URL}`);
|
||||
console.log(`Save Report: ${saveReport ? 'Yes' : 'No'}`);
|
||||
console.log(`Verbose Mode: ${verbose ? 'Yes' : 'No'}`);
|
||||
console.log(`Using Real Credentials: ${useRealCredentials ? 'Yes' : 'No'}\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, use the --use-real-credentials flag');
|
||||
console.log(' and set PENNYZO_TEST_EMAIL and PENNYZO_TEST_PASSWORD environment variables.\n');
|
||||
}
|
||||
|
||||
// Summary
|
||||
const successCount = results.filter(r => r.status === 'SUCCESS').length;
|
||||
const failureCount = results.filter(r => r.status === 'FAILED').length;
|
||||
|
||||
console.log(chalk.bold('\n=== API Status Check Summary ===\n'));
|
||||
console.log(`Total endpoints checked: ${results.length}`);
|
||||
console.log(`Successful: ${chalk.green(successCount)}`);
|
||||
console.log(`Failed: ${chalk.red(failureCount)}`);
|
||||
console.log(`Success rate: ${((successCount / results.length) * 100).toFixed(1)}%`);
|
||||
console.log(`Total time: ${((new Date() - startTime) / 1000).toFixed(2)} seconds\n`);
|
||||
|
||||
// Save report if enabled
|
||||
if (saveReport) {
|
||||
saveReportToFile();
|
||||
}
|
||||
|
||||
console.log(chalk.bold('=== 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);
|
||||
});
|
||||
137
scripts/api-status-checker.js
Normal file
137
scripts/api-status-checker.js
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const chalk = require('chalk'); // For colorful console output
|
||||
|
||||
// Define the base URL
|
||||
const BASE_URL = 'https://api.pennyzo.com/api/v1/general';
|
||||
|
||||
// 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);
|
||||
});
|
||||
36
scripts/run-api-check.ps1
Normal file
36
scripts/run-api-check.ps1
Normal file
@@ -0,0 +1,36 @@
|
||||
# PowerShell script to run the Pennyzo API Status Checker
|
||||
|
||||
param (
|
||||
[switch]$Verbose,
|
||||
[switch]$NoReport,
|
||||
[switch]$UseRealCredentials,
|
||||
[switch]$Extended
|
||||
)
|
||||
|
||||
$ScriptArgs = @()
|
||||
|
||||
if ($Verbose) {
|
||||
$ScriptArgs += "--verbose"
|
||||
}
|
||||
|
||||
if ($NoReport) {
|
||||
$ScriptArgs += "--no-report"
|
||||
}
|
||||
|
||||
if ($UseRealCredentials) {
|
||||
$ScriptArgs += "--use-real-credentials"
|
||||
}
|
||||
|
||||
# Determine which script to run
|
||||
$ScriptPath = if ($Extended) {
|
||||
"scripts\api-status-checker-extended.js"
|
||||
}
|
||||
else {
|
||||
"scripts\api-status-checker.js"
|
||||
}
|
||||
|
||||
# Display command that will be executed
|
||||
Write-Host "Running: node $ScriptPath $ScriptArgs"
|
||||
|
||||
# Run the script
|
||||
node $ScriptPath $ScriptArgs
|
||||
Reference in New Issue
Block a user