Skip to main content

Basic Usage

A complete example showing how to set up and use the Core package.

Project Setup

Create a new project with the following structure:

my-serverless-app/
├── src/
│ └── modules/
│ └── user/
│ ├── functions.yml
│ └── handlers/
│ ├── create/
│ │ └── index.ts
│ ├── list/
│ │ └── index.ts
│ └── get/
│ └── index.ts
├── monolith.config.ts
├── start.ts
├── package.json
└── tsconfig.json

Configuration

// monolith.config.ts
import { MonolithConfig } from '@serverless-monolith/core';

export default {
discovery: {
modulesDir: 'src/modules',
functionsFile: 'functions.yml',
},
logging: {
enabledCategories: ['adapterStartupInfo', 'httpRequestInfo'],
showRoutesTable: true,
},
} satisfies MonolithConfig;

Functions Definition

# src/modules/user/functions.yml
listUsers:
handler: handlers/list/index.handler
events:
- http:
path: users
method: GET

createUser:
handler: handlers/create/index.handler
events:
- http:
path: users
method: POST
cors: true

getUserById:
handler: handlers/get/index.handler
events:
- http:
path: users/{id}
method: GET

Handlers

List Users

// src/modules/user/handlers/list/index.ts
import { APIGatewayProxyHandler } from 'aws-lambda';

// In-memory store for demo
const users = new Map<string, { id: string; name: string; email: string }>();

export const handler: APIGatewayProxyHandler = async (event) => {
const userList = Array.from(users.values());

return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
users: userList,
count: userList.length,
}),
};
};

Create User

// src/modules/user/handlers/create/index.ts
import { APIGatewayProxyHandler } from 'aws-lambda';
import { randomUUID } from 'crypto';

const users = new Map<string, { id: string; name: string; email: string }>();

export const handler: APIGatewayProxyHandler = async (event) => {
// Parse request body
let body: { name?: string; email?: string };
try {
body = JSON.parse(event.body || '{}');
} catch {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid JSON body' }),
};
}

// Validate
if (!body.name || !body.email) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Name and email are required' }),
};
}

// Create user
const user = {
id: randomUUID(),
name: body.name,
email: body.email,
};

users.set(user.id, user);
console.log('Created user:', user);

return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
};
};

Get User by ID

// src/modules/user/handlers/get/index.ts
import { APIGatewayProxyHandler } from 'aws-lambda';

const users = new Map<string, { id: string; name: string; email: string }>();

export const handler: APIGatewayProxyHandler = async (event) => {
const { id } = event.pathParameters || {};

if (!id) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'User ID is required' }),
};
}

const user = users.get(id);

if (!user) {
return {
statusCode: 404,
body: JSON.stringify({ error: 'User not found' }),
};
}

return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
};
};

Start Script

// start.ts
import { MonolithServer } from '@serverless-monolith/core';
import path from 'path';

async function main() {
const server = MonolithServer.create(
path.resolve(__dirname, './monolith.config.ts'),
{
port: 4005,
cors: true,
}
);

await server.start();
console.log('Server running on http://localhost:4005');
}

main().catch(console.error);

Running the Server

# Start the server
npx tsx start.ts

Testing the API

# Create a user
curl -X POST http://localhost:4005/api/http/user/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'

# List users
curl http://localhost:4005/api/http/user/users

# Get user by ID (replace with actual ID)
curl http://localhost:4005/api/http/user/users/abc123

Package.json

{
"name": "my-serverless-app",
"scripts": {
"start": "tsx start.ts",
"dev": "tsx watch start.ts"
},
"dependencies": {
"@serverless-monolith/core": "^1.0.0"
},
"devDependencies": {
"@types/aws-lambda": "^8.10.0",
"tsx": "^4.0.0",
"typescript": "^5.0.0"
}
}