@encodeagent/platform-helper-api
v1.2509.1201722
Published
Comprehensive TypeScript utility library for the EncodeAgent platform with AI services, authentication, file handling, and more
Maintainers
Readme
@encodeagent/platform-helper-api
Shared utilities and common functions for web APIs and MCP servers in the EncodeAgent platform. This package provides reusable components for building consistent, well-structured APIs with TypeScript.
Copy whole sh folder to helper folder
Installation
npm install @encodeagent/platform-helper-apiFeatures
- Configuration Management: Environment-based config with Zod validation
- Structured Logging: Configurable logging with timestamps and levels
- Response Utilities: Consistent API response formatting
- Validation Middleware: Request validation with Zod schemas
- Error Handling: Standardized error responses and middleware
- CORS Support: Configurable cross-origin resource sharing
- Type Safety: Full TypeScript support with comprehensive types
Quick Start
import {
parseApiConfig,
logger,
sendSuccess,
validateRequest
} from '@encodeagent/platform-helper-api';
const config = parseApiConfig();
logger.info('Server starting...');Core Utilities
Configuration Management
import {
parseApiConfig,
parseConfig,
createEnvironmentHelpers,
apiConfigSchema
} from '@encodeagent/platform-helper-api';
// Parse standard API configuration
const config = parseApiConfig();
// Parse custom configuration
const customConfig = parseConfig(mySchema);
// Environment helpers
const { isDevelopment, isProduction } = createEnvironmentHelpers(config.NODE_ENV);Structured Logging
import {
logger,
createLogger,
LogLevel
} from '@encodeagent/platform-helper-api';
// Use default logger
logger.info('Server started');
logger.error('Something went wrong', { error: err });
// Create custom logger
const customLogger = createLogger({ level: 'debug' });
customLogger.debug('Debug information');Response Utilities
import {
sendSuccess,
sendError,
sendHealthResponse,
handleValidationError
} from '@encodeagent/platform-helper-api';
// Success response
sendSuccess(res, { message: 'Hello World' });
// Error response
sendError(res, 'Something went wrong', 400);
// Health check response
sendHealthResponse(res, '1.0.0');
// Validation error handling
handleValidationError(res, zodError);Validation Middleware
import {
validateRequest,
validateQuery,
validateBody,
commonSchemas
} from '@encodeagent/platform-helper-api';
import { z } from 'zod';
const userSchema = z.object({
name: commonSchemas.nonEmptyString,
email: commonSchemas.email
});
// Validate request (query + body)
app.post('/users', validateRequest(userSchema), (req, res) => {
const { name, email } = req.validatedData;
sendSuccess(res, { name, email });
});
// Validate query parameters only
app.get('/users', validateQuery(commonSchemas.paginationQuery), handler);
// Validate body only
app.post('/users', validateBody(userSchema), handler);Error Handling
import {
errorHandler,
notFoundHandler,
asyncHandler
} from '@encodeagent/platform-helper-api';
// Global error handler
app.use(errorHandler);
// 404 handler
app.use(notFoundHandler);
// Async error wrapper
app.get('/users', asyncHandler(async (req, res) => {
const users = await getUsersFromDB();
sendSuccess(res, users);
}));CORS Middleware
import {
defaultCorsMiddleware,
createCorsMiddleware,
mcpCorsMiddleware
} from '@encodeagent/platform-helper-api';
// Default CORS
app.use(defaultCorsMiddleware);
// Custom CORS
app.use(createCorsMiddleware('https://myapp.com', ['X-Custom-Header']));
// MCP-specific CORS
app.use(mcpCorsMiddleware('Mcp-Session-Id'));Common Schemas
The package includes pre-built Zod schemas for common validation patterns:
import { commonSchemas } from '@encodeagent/platform-helper-api';
// String validations
commonSchemas.nonEmptyString
commonSchemas.email
commonSchemas.url
// Number validations
commonSchemas.positiveNumber
commonSchemas.port
// Environment validations
commonSchemas.nodeEnv
commonSchemas.logLevel
// API specific
commonSchemas.apiVersion
commonSchemas.paginationQuery
commonSchemas.sortQueryUtility Functions
String Utilities
import _ from 'lodash';
// Use lodash for common string operations
const camelCase = _.camelCase('hello-world'); // 'helloWorld'
const kebabCase = _.kebabCase('HelloWorld'); // 'hello-world'
const snakeCase = _.snakeCase('HelloWorld'); // 'hello_world'
const capitalized = _.capitalize('hello'); // 'Hello'
const truncated = _.truncate('Long text here', { length: 10 }); // 'Long te...'
Date Utilities
import {
getCurrentTimestamp,
formatDate,
parseDate,
isValidDate,
getDateDiff,
addDays
} from '@encodeagent/platform-helper-api';
const timestamp = getCurrentTimestamp(); // ISO string
const formatted = formatDate(new Date()); // ISO string
const parsed = parseDate('2023-01-01'); // Date object
const isValid = isValidDate(new Date()); // boolean
const diff = getDateDiff(date1, date2); // milliseconds
const future = addDays(new Date(), 7); // Date + 7 daysComplete Express.js Example
import express from 'express';
import {
parseApiConfig,
createEnvironmentHelpers,
logger,
defaultCorsMiddleware,
validateRequest,
sendSuccess,
sendHealthResponse,
errorHandler,
notFoundHandler,
commonSchemas
} from '@encodeagent/platform-helper-api';
import { z } from 'zod';
const config = parseApiConfig();
const { isDevelopment } = createEnvironmentHelpers(config.NODE_ENV);
const app = express();
// Middleware
app.use(express.json());
app.use(defaultCorsMiddleware);
// Health check
app.get('/health', (req, res) => {
sendHealthResponse(res, '1.0.0');
});
// API routes
const helloSchema = z.object({
name: z.string().default('World')
});
app.get('/api/v1/hello', validateRequest(helloSchema), (req, res) => {
const { name } = req.validatedData;
sendSuccess(res, { greeting: `Hello, ${name}!` });
});
// Error handling
app.use(errorHandler);
app.use(notFoundHandler);
// Start server
app.listen(config.PORT, () => {
logger.info(`Server listening on port ${config.PORT}`);
});TypeScript Support
This library is written in TypeScript and includes comprehensive type definitions:
import type {
ApiResponse,
ApiFunction,
HealthResponse,
ErrorResponse,
BaseConfig,
ApiConfig
} from '@encodeagent/platform-helper-api';
// Extend Express Request type
declare global {
namespace Express {
interface Request {
validatedData?: any;
}
}
}Integration with MCP Servers
This package works seamlessly with MCP (Model Context Protocol) servers:
import {
mcpCorsMiddleware,
logger,
sendError
} from '@encodeagent/platform-helper-api';
// MCP-specific CORS
app.use(mcpCorsMiddleware('Mcp-Session-Id'));
// MCP error handling
const handleMcpError = (error: any, res: Response) => {
logger.error('MCP Error:', error);
sendError(res, 'MCP operation failed', 500, 'MCP_ERROR');
};Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the UNLICENSED License.
Related Packages
@encodeagent/platform-helper-util- General utility functions@encodeagent/api-context- Example API implementation using this package
