gl-life-data-api
v1.0.0
Published
REST API server for GL.Life.Data - Dynamic CRUD operations with runtime-configurable schemas
Maintainers
Readme
GL.Life.Data API
REST API server for GL.Life.Data - Dynamic CRUD operations with runtime-configurable schemas.
Features
- Dynamic Schema: Define tables and fields at runtime using metadata
- Auto-Generated CRUD: REST endpoints created automatically for all tables
- Field Validation: Built-in validation using gl-life-data rules
- Flexible Configuration: Environment variables, config objects, and defaults
- Type-Safe: Full TypeScript support with type definitions
- Production Ready: Structured logging, error handling, and health checks
Quick Start (2 Minutes)
npm install gl-life-data-api gl-life-data better-sqlite3 drizzle-orm nanoidimport { createServer } from 'gl-life-data-api';
import { MetaDataService } from 'gl-life-data';
// 1. Define your schema
const service = new MetaDataService('./myapp.db');
service.createMapping({
tableName: 'users',
logicalFieldName: 'name',
dataType: 'string',
isRequired: true
});
service.close();
// 2. Create and start the API server
const app = createServer({
databasePath: './myapp.db',
port: 3000
});
app.listen(3000, () => {
console.log('API server running on http://localhost:3000');
});That's it! Your API is now live with endpoints:
GET /api/users- List all usersGET /api/users/:id- Get user by IDPOST /api/users- Create userPUT /api/users/:id- Update userDELETE /api/users/:id- Delete user
Configuration
Basic Configuration
import { createServer } from 'gl-life-data-api';
const app = createServer({
databasePath: './data/myapp.db', // Required
port: 3000, // Default: 3000
environment: 'production', // Default: 'development'
enableLogging: true, // Default: true
logLevel: 'info' // Default: 'info' (prod) or 'debug' (dev)
});Environment Variables
All configuration can be set via environment variables:
DB_PATH=./data/prod.db
PORT=8080
NODE_ENV=production
CORS_ORIGIN=https://myapp.com
ENABLE_LOGGING=true
LOG_LEVEL=warn// Config merges: explicit > env vars > defaults
const app = createServer({
databasePath: process.env.DB_PATH // Can use env vars directly
});CORS Configuration
const app = createServer({
databasePath: './myapp.db',
cors: {
origin: 'https://myapp.com',
credentials: true
}
});Custom Middleware
import { createServer } from 'gl-life-data-api';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
const app = createServer({
databasePath: './myapp.db',
customMiddleware: [
helmet(),
rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
})
]
});API Endpoints
All endpoints follow REST conventions and return JSON responses.
GET /api/:table
List all records in a table.
Request:
GET /api/usersResponse:
{
"table": "users",
"count": 2,
"data": [
{
"id": "abc123",
"name": "John Doe",
"email": "[email protected]",
"created_at": "2025-12-18T10:00:00.000Z"
},
{
"id": "def456",
"name": "Jane Smith",
"email": "[email protected]",
"created_at": "2025-12-18T11:00:00.000Z"
}
]
}GET /api/:table/:id
Get a single record by ID.
Request:
GET /api/users/abc123Response:
{
"table": "users",
"data": {
"id": "abc123",
"name": "John Doe",
"email": "[email protected]",
"created_at": "2025-12-18T10:00:00.000Z"
}
}POST /api/:table
Create a new record (with validation).
Request:
POST /api/users
Content-Type: application/json
{
"name": "New User",
"email": "[email protected]"
}Response (201 Created):
{
"table": "users",
"data": {
"id": "ghi789",
"name": "New User",
"email": "[email protected]",
"created_at": "2025-12-18T12:00:00.000Z"
}
}PUT /api/:table/:id
Update an existing record (with validation).
Request:
PUT /api/users/abc123
Content-Type: application/json
{
"name": "Updated Name"
}Response:
{
"table": "users",
"data": {
"id": "abc123",
"name": "Updated Name",
"email": "[email protected]",
"updated_at": "2025-12-18T13:00:00.000Z"
}
}DELETE /api/:table/:id
Delete a record.
Request:
DELETE /api/users/abc123Response:
{
"table": "users",
"id": "abc123",
"message": "Record deleted successfully"
}GET /health
Health check endpoint.
Response:
{
"status": "ok",
"timestamp": "2025-12-18T14:00:00.000Z",
"uptime": 3600,
"environment": "production"
}Error Handling
All errors return structured JSON responses:
{
"error": "ValidationError",
"message": "One or more fields failed validation",
"statusCode": 400,
"timestamp": "2025-12-18T15:00:00.000Z",
"path": "/api/users",
"validationErrors": [
{
"field": "email",
"rule": "required",
"message": "Field is required"
}
]
}Common HTTP status codes:
200- Success201- Created400- Validation Error404- Not Found (table or record)500- Internal Server Error
Advanced Usage
Custom Error Handling
import { createServer, ApiError, errorHandler } from 'gl-life-data-api';
const app = createServer({ databasePath: './myapp.db' });
// Add custom error handling
app.use((err, req, res, next) => {
// Custom logging, monitoring, etc.
if (err instanceof ApiError) {
// Handle API errors
}
next(err);
});Custom Routes
import { createServer } from 'gl-life-data-api';
const app = createServer({ databasePath: './myapp.db' });
// Add custom routes
app.get('/custom', (req, res) => {
res.json({ message: 'Custom endpoint' });
});
app.listen(3000);Logging Configuration
import { createServer, Logger } from 'gl-life-data-api';
const app = createServer({
databasePath: './myapp.db',
logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error'
enableLogging: true
});
// Create custom logger
const logger = new Logger({
level: 'info',
enableTimestamp: true,
enableColors: false
});Deployment
Production Checklist
Environment Variables
export NODE_ENV=production export DB_PATH=/data/production.db export PORT=8080 export LOG_LEVEL=warnBuild (if using TypeScript)
npm run buildStart Server
node dist/server.js
Docker Example
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
ENV NODE_ENV=production
ENV PORT=8080
EXPOSE 8080
CMD ["node", "dist/server.js"]Process Manager (PM2)
npm install -g pm2
pm2 start dist/server.js --name gl-life-api
pm2 startup
pm2 saveTypeScript Support
Full TypeScript support with type definitions included.
import {
createServer,
ServerConfig,
Logger,
LogLevel,
ApiError,
NotFoundError,
ValidationError
} from 'gl-life-data-api';
const config: ServerConfig = {
databasePath: './myapp.db',
port: 3000,
environment: 'production',
logLevel: 'info'
};
const app = createServer(config);Requirements
- Node.js >= 18.0.0
- gl-life-data >= 1.0.0
- better-sqlite3 >= 12.0.0
- drizzle-orm >= 0.45.0
- nanoid >= 5.0.0
License
Apache-2.0
Related Packages
- gl-life-data - Flex Field System Data Access Layer
