A simple REST API implementation using pure Node.js and TypeScript with horizontal scaling capabilities.
- Node.js (v18 or higher)
- npm (Node Package Manager)
- Clone the repository:
git clone <repository-url>
cd crud-api- Install dependencies:
npm install- Create a
.envfile in the root directory:
PORT=4000There are three modes to run the application:
npm run start:devnpm run start:prodnpm run start:multiThis mode starts multiple instances:
- Load balancer on PORT (default: 4000)
- Worker instances on PORT+1, PORT+2, etc.
- Automatically scales based on CPU cores
- Returns all users
- Response: 200 OK
[
{
"id": "uuid",
"username": "string",
"age": "number",
"hobbies": ["string"]
}
]- Returns user by id
- Response: 200 OK
{
"id": "uuid",
"username": "string",
"age": "number",
"hobbies": ["string"]
}- Creates a new user
- Request body:
{
"username": "string",
"age": "number",
"hobbies": ["string"]
}- Response: 201 Created
- Updates existing user
- Request body (at least one field required):
{
"username": "string",
"age": "number",
"hobbies": ["string"]
}- Response: 200 OK
- Removes user
- Response: 204 No Content
- 400 Bad Request: Invalid user data or UUID
- 404 Not Found: Route not found
- 500 Internal Server Error: Server error
All responses have content type: application/json
crud-api/
├── src/
│ ├── data/
│ │ └── users.ts
│ ├── cluster.ts
│ ├── loadBalancer.ts
│ ├── store.ts
│ ├── server.ts
│ ├── utils.ts
│ ├── crud.ts
│ └── index.ts
├── __tests__/
│ └── crud.test.ts
├── package.json
├── tsconfig.json
├── webpack.config.js
└── .env
- Node.js
- TypeScript
- UUID for generating unique identifiers
- dotenv for environment variables
- Jest for testing
- webpack for production builds
Run the test suite:
npm testThe tests cover:
- Basic CRUD operations
- Error handling
- Invalid input scenarios
- Data consistency
In multi-instance mode, the application uses a Round-robin algorithm to distribute requests across worker instances. State is synchronized across all instances using Node.js IPC mechanisms.