digitaltwin-core
Version:
Minimalist framework to collect and handle data in a Digital Twin project
56 lines • 2.17 kB
JavaScript
/**
* @fileoverview HTTP endpoint exposure utilities for digital twin components
*
* This module handles the automatic registration of HTTP endpoints from servable
* components to the Express router, enabling RESTful API access to digital twin data.
*/
/**
* Automatically registers HTTP endpoints from servable components to an Express router.
*
* This function iterates through all provided components, extracts their endpoints,
* and registers them with the Express router. Each endpoint is wrapped with error
* handling to ensure robust API behavior.
*
* @param router - Express router instance to register endpoints with
* @param servables - Array of components that expose HTTP endpoints
*
* @throws {Error} When an unsupported HTTP method is encountered
*
* @example
* ```typescript
* const router = express.Router();
* const components = [collector1, harvester1, assetsManager1];
*
* await exposeEndpoints(router, components);
*
* // Now the router has all endpoints from the components registered
* app.use('/api', router);
* ```
*/
export async function exposeEndpoints(router, servables) {
for (const servable of servables) {
const endpoints = servable.getEndpoints();
for (const ep of endpoints) {
const method = ep.method.toLowerCase();
if (typeof router[method] === 'function') {
// Register endpoint with error handling wrapper
router[method](ep.path, async (req, res) => {
try {
const result = await ep.handler(req);
res.status(result.status)
.header(result.headers || {})
.send(result.content);
}
catch {
// Generic error response to avoid exposing internal details
res.status(500).send({ error: 'Internal server error' });
}
});
}
else {
throw new Error(`Unsupported HTTP method: ${ep.method}`);
}
}
}
}
//# sourceMappingURL=endpoints.js.map