Comprehensive guide for developing services in the Lilith platform.
Creating a New Service#
1. Service Structure#
Create the following structure for a new service:
text
services/<service-name>/
├── src/
│ ├── server.ts # Entry point
│ ├── app.ts # Fastify app configuration
│ ├── types.ts # TypeScript type definitions
│ ├── routes/ # API route handlers
│ │ └── v1/ # Versioned routes
│ ├── services/ # Business logic
│ └── __tests__/ # Unit tests
├── package.json
├── tsconfig.json
├── vitest.config.ts
├── Dockerfile
└── .env.example
2. Package Configuration#
json
{
"name": "@lilith/<service-name>",
"version": "1.0.0",
"type": "module",
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"start": "node dist/server.js",
"dev": "tsx watch src/server.ts",
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@lilith/core": "*",
"@lilith/errors": "*",
"@lilith/lib": "*",
"fastify": "^4.28.1"
},
"devDependencies": {
"@lilith/testing": "*",
"@lilith/tsconfig-lilith": "*",
"typescript": "catalog:",
"vitest": "^2.1.9"
}
}
3. TypeScript Configuration#
Extend the shared TypeScript configuration:
json
{
"extends": "@lilith/tsconfig-lilith/service",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/__tests__/**"]
}
4. Server Entry Point#
typescript
// src/server.ts
import { FastifyInstance } from 'fastify';
import { LilithLogger } from '@lilith/lib';
import { buildServer } from './app.js';
const logger = new LilithLogger({
service: '<service-name>',
version: process.env['SERVICE_VERSION'] ?? '1.0.0',
environment: process.env['NODE_ENV'] ?? 'development',
outputs: ['console'],
});
const PORT = Number(process.env['PORT'] || 3000);
const SERVICE_NAME = process.env['SERVICE_NAME'] || '<service-name>';
async function start(): Promise<void> {
const server: FastifyInstance = await buildServer({
logger: true,
serviceName: SERVICE_NAME,
});
try {
await server.listen({ port: PORT, host: '0.0.0.0' });
logger.info(`${SERVICE_NAME} service listening on port ${PORT}`, {
category: 'server',
metadata: { port: PORT },
});
} catch (err: unknown) {
logger.error('Failed to start server', {
category: 'server',
metadata: { error: err instanceof Error ? err.message : String(err) },
});
process.exit(1);
}
}
void start();
5. Application Setup#
typescript
// src/app.ts
import Fastify, { FastifyInstance } from 'fastify';
import { LilithLogger } from '@lilith/lib';
import { registerHealthRoutes } from '@lilith/fastify-core';
export interface BuildServerOptions {
logger: boolean;
serviceName: string;
}
const serviceLogger = new LilithLogger({
service: '<service-name>',
version: process.env['SERVICE_VERSION'] ?? '1.0.0',
environment: process.env['NODE_ENV'] ?? 'development',
outputs: ['console'],
});
export async function buildServer(
options: BuildServerOptions
): Promise<FastifyInstance> {
const app = Fastify({ logger: options.logger });
// Register health check routes
registerHealthRoutes(app, {
serviceName: options.serviceName,
version: process.env['SERVICE_VERSION'] ?? '1.0.0',
});
// Register your routes
await app.register(import('./routes/v1/index.js'), { prefix: '/v1' });
return app;
}
Routing Patterns#
Route Organization#
typescript
// src/routes/v1/index.ts
import { FastifyInstance } from 'fastify';
export default async function routes(app: FastifyInstance): Promise<void> {
// Import and register route modules
await app.register(import('./users.js'));
await app.register(import('./items.js'));
}
// src/routes/v1/users.ts
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
export default async function userRoutes(app: FastifyInstance): Promise<void> {
app.get('/users', async (request: FastifyRequest, reply: FastifyReply) => {
// Handler implementation
return { users: [] };
});
app.get<{ Params: { id: string } }>('/users/:id', async (request, reply) => {
const { id } = request.params;
// Handler implementation
return { user: { id } };
});
app.post<{ Body: CreateUserBody }>('/users', async (request, reply) => {
const body = request.body;
// Handler implementation
reply.status(201);
return { user: { id: 'new-id', ...body } };
});
}
interface CreateUserBody {
email: string;
name: string;
}
Request Validation#
Use Fastify's built-in JSON Schema validation:
typescript
app.post<{ Body: CreateUserBody }>(
'/users',
{
schema: {
body: {
type: 'object',
required: ['email', 'name'],
properties: {
email: { type: 'string', format: 'email' },
name: { type: 'string', minLength: 1 },
},
},
response: {
201: {
type: 'object',
properties: {
user: {
type: 'object',
properties: {
id: { type: 'string' },
email: { type: 'string' },
name: { type: 'string' },
},
},
},
},
},
},
},
async (request, reply) => {
// Body is validated before reaching handler
const { email, name } = request.body;
// ...
}
);
Error Handling#
Using @lilith/errors#
typescript
import {
AppError,
ValidationError,
NotFoundError,
UnauthorizedError,
ForbiddenError,
ConflictError,
RateLimitError,
ServiceUnavailableError,
} from '@lilith/errors';
// In route handlers
async function getUserById(id: string) {
const user = await userRepository.findById(id);
if (!user) {
throw new NotFoundError(`User not found: ${id}`);
}
return user;
}
// Validation errors
function validateEmail(email: string) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email format');
}
}
// Business logic errors
function ensureCanAccessResource(user: User, resource: Resource) {
if (resource.ownerId !== user.id) {
throw new ForbiddenError('You do not have access to this resource');
}
}
Global Error Handler#
typescript
// src/app.ts
import { FastifyInstance, FastifyError } from 'fastify';
import { isAppError } from '@lilith/errors';
function registerErrorHandler(app: FastifyInstance): void {
app.setErrorHandler((error: FastifyError, request, reply) => {
const logger = request.server.log;
if (isAppError(error)) {
logger.warn('Application error', {
code: error.code,
message: error.message,
statusCode: error.statusCode,
});
return reply.status(error.statusCode).send({
error: error.code,
message: error.message,
details: error.details,
});
}
// Fastify validation errors
if (error.validation) {
return reply.status(400).send({
error: 'VALIDATION_ERROR',
message: 'Request validation failed',
details: error.validation,
});
}
// Unexpected errors
logger.error('Unexpected error', { error });
return reply.status(500).send({
error: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
});
});
}
Logging#
Using LilithLogger#
typescript
import { LilithLogger } from '@lilith/lib';
const logger = new LilithLogger({
service: 'my-service',
version: process.env['SERVICE_VERSION'] ?? '1.0.0',
environment: process.env['NODE_ENV'] ?? 'development',
outputs: ['console'],
});
// Basic logging
logger.info('User created', {
category: 'users',
metadata: { userId: user.id, email: user.email },
});
// Error logging
logger.error('Failed to process request', {
category: 'api',
metadata: {
error: err instanceof Error ? err.message : String(err),
requestId: request.id,
},
});
// Debug logging (only in development)
logger.debug('Processing batch', {
category: 'batch',
metadata: { batchSize: items.length },
});
// HTTP request logging
logger.logHttpRequest(request, reply, responseTime);
// Performance logging
logger.logPerformance('database-query', queryDuration, {
query: 'SELECT * FROM users',
rowCount: result.rows.length,
});
Testing#
Unit Test Structure#
typescript
// src/__tests__/user-service.test.ts
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createMockLogger, createUser } from '@lilith/testing';
import { UserService } from '../services/user-service.js';
describe('UserService', () => {
let service: UserService;
let mockLogger: ReturnType<typeof createMockLogger>;
beforeEach(() => {
mockLogger = createMockLogger();
service = new UserService({ logger: mockLogger });
});
describe('createUser', () => {
it('should create user with valid data', async () => {
const userData = createUser({ email: 'test@example.com' });
const result = await service.createUser(userData);
expect(result.id).toBeDefined();
expect(result.email).toBe('test@example.com');
});
it('should reject duplicate email', async () => {
const userData = createUser();
await service.createUser(userData);
await expect(service.createUser(userData)).rejects.toThrow(
'Email already exists'
);
});
});
});
Integration Test Example#
typescript
// src/__tests__/integration/user-routes.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createMockFastifyServer } from '@lilith/testing';
import { buildServer } from '../../app.js';
describe('User Routes Integration', () => {
let app: Awaited<ReturnType<typeof buildServer>>;
beforeAll(async () => {
app = await buildServer({ logger: false, serviceName: 'test' });
});
afterAll(async () => {
await app.close();
});
it('GET /v1/users should return empty array', async () => {
const response = await app.inject({
method: 'GET',
url: '/v1/users',
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ users: [] });
});
it('POST /v1/users should create user', async () => {
const response = await app.inject({
method: 'POST',
url: '/v1/users',
payload: {
email: 'test@example.com',
name: 'Test User',
},
});
expect(response.statusCode).toBe(201);
expect(response.json().user).toMatchObject({
email: 'test@example.com',
name: 'Test User',
});
});
});
Vitest Configuration#
typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['src/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: ['node_modules/', 'dist/', '**/*.d.ts', '**/__tests__/**'],
thresholds: {
lines: 80,
branches: 80,
functions: 80,
statements: 80,
},
},
},
});
Database Access#
Using @lilith/database#
typescript
import { createDatabasePool, runQuery, runTransaction } from '@lilith/database';
// Initialize pool
const pool = createDatabasePool({
connectionString: process.env['DATABASE_URL'],
});
// Simple query
const users = await runQuery(pool, 'SELECT * FROM users WHERE active = $1', [
true,
]);
// Transaction
const result = await runTransaction(pool, async (client) => {
const user = await client.query(
'INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *',
[email, name]
);
await client.query(
'INSERT INTO user_settings (user_id, settings) VALUES ($1, $2)',
[user.rows[0].id, defaultSettings]
);
return user.rows[0];
});
Health Checks#
Health endpoints are automatically registered by @lilith/fastify-core:
GET /health- Basic health checkGET /v1/health- Versioned health checkGET /ready- Kubernetes readiness probeGET /live- Kubernetes liveness probe
Custom health checks:
typescript
registerHealthRoutes(app, {
serviceName: 'my-service',
version: '1.0.0',
healthCheckFn: async () => ({
database: await checkDatabaseConnection(),
redis: await checkRedisConnection(),
externalApi: await checkExternalApiHealth(),
}),
});
Environment Configuration#
.env.example Template#
bash
# Service Configuration
PORT=3000
NODE_ENV=development
SERVICE_NAME=my-service
SERVICE_VERSION=1.0.0
# Database
DATABASE_URL=postgres://user:pass@localhost:5432/lilith
# Redis
REDIS_URL=redis://localhost:6379
# Authentication
JWT_SECRET=your-secret-key
JWT_ACCESS_TOKEN_EXPIRY=15m
JWT_REFRESH_TOKEN_EXPIRY=7d
# External Services
AI_SERVICE_URL=http://localhost:3007
NOTIFICATION_SERVICE_URL=http://localhost:3008
# Feature Flags
ENABLE_CACHING=true
ENABLE_RATE_LIMITING=true
Docker#
Dockerfile Template#
dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --omit=dev
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
Best Practices#
Code Organization#
- Single Responsibility: Each file should have one clear purpose
- Dependency Injection: Pass dependencies to services/handlers
- Type Safety: Use strict TypeScript, avoid
any - Error Boundaries: Handle errors at appropriate levels
Performance#
- Connection Pooling: Reuse database connections
- Caching: Cache frequently accessed data
- Pagination: Always paginate list endpoints
- Compression: Enable response compression for large payloads
Security#
- Input Validation: Validate all inputs at the API boundary
- Authentication: Require auth for protected endpoints
- Authorization: Check permissions before data access
- Secrets: Never log sensitive data
Testing#
- Test Coverage: Maintain 80%+ coverage
- Unit Tests: Test business logic in isolation
- Integration Tests: Test API contracts
- Mock External Services: Don't call real external services in tests