const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;
// Middleware to parse JSON request bodies
app.use(bodyParser.json());
// Rate limiting middleware to prevent abuse
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
app.use(limiter);
// Unique identifiers for Duke's integration
const dukeClientId = 'DUKE_CLIENT_ID';
const dukeClientSecret = 'DUKE_CLIENT_SECRET';
// SubscribeStar API endpoints
const subscribeStarApiBaseUrl = 'https://api.subscribestar.com/v1';
const dukeOAuthEndpoint = `${subscribeStarApiBaseUrl}/oauth/token`;
const dukeSubscriptionsEndpoint = `${subscribeStarApiBaseUrl}/subscriptions`;
// Function to get OAuth token for Duke with error handling and retries
async function getDukeOAuthToken(retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await axios.post(dukeOAuthEndpoint, {
grant_type: 'client_credentials',
client_id: dukeClientId,
client_secret: dukeClientSecret,
});
return response.data.access_token;
} catch (error) {
console.error('Error fetching Duke\'s OAuth token:', error.response.data);
if (i < retries - 1) {
console.log(`Retrying (${i + 1}/${retries})...`);
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before retrying
} else {
throw new Error('Failed to fetch Duke\'s OAuth token after retries');
}
}
}
}
// Function to fetch subscriptions with pagination for Duke with error handling and retries
async function fetchDukeSubscriptions(accessToken, page = 1, pageSize = 10, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await axios.get(dukeSubscriptionsEndpoint, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
params: {
page,
page_size: pageSize,
},
});
return response.data;
} catch (error) {
console.error('Error fetching Duke\'s subscriptions:', error.response.data);
if (i < retries - 1) {
console.log(`Retrying (${i + 1}/${retries})...`);
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before retrying
} else {
throw new Error('Failed to fetch Duke\'s subscriptions after retries');
}
}
}
}
// Route to fetch Duke's subscriptions
app.get('/duke/subscriptions', async (req, res) => {
try {
const accessToken = await getDukeOAuthToken();
const page = parseInt(req.query.page) || 1;
const pageSize = parseInt(req.query.pageSize) || 10;
const dukeSubscriptions = await fetchDukeSubscriptions(accessToken, page, pageSize);
res.json(dukeSubscriptions);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});