powr-sdk-api
Version:
Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.
52 lines (49 loc) • 1.61 kB
JavaScript
;
const {
config
} = require('../config');
/**
* Middleware to inject and validate projectId into requests
* @param {Object} options - Configuration options
* @param {boolean} options.isCentralService - Whether this is a central service (like powr-base-cloud)
* @param {Array} options.excludePaths - Array of paths to exclude from projectId validation
* @returns {Function} Express middleware function
*/
const injectProjectId = (options = {}) => {
const isCentralService = options.isCentralService || false;
const excludePaths = options.excludePaths || ['/health'];
return (req, res, next) => {
try {
// Skip validation for excluded paths
if (excludePaths.some(path => req.path.startsWith(path))) {
req.projectId = null;
return next();
}
if (isCentralService) {
// For central services, get projectId from request
req.projectId = req.query.projectId || req.body.projectId;
} else {
// For individual APIs, use config.projectId
req.projectId = config.projectId;
}
// Validate projectId (always required except for excluded paths)
if (!req.projectId) {
return res.status(400).json({
success: false,
message: 'projectId is required'
});
}
next();
} catch (error) {
console.error('❌ ProjectId injection error:', error.message);
return res.status(500).json({
success: false,
message: 'Configuration error',
error: error.message
});
}
};
};
module.exports = {
injectProjectId
};