-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (77 loc) · 2.72 KB
/
index.js
File metadata and controls
91 lines (77 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(morgan('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// In-memory data store for demo purposes
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com', age: 30 },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', age: 25 },
{ id: 3, name: 'Bob Johnson', email: 'bob@example.com', age: 35 }
];
let posts = [
{ id: 1, title: 'First Post', content: 'This is the first post', userId: 1, createdAt: new Date() },
{ id: 2, title: 'Second Post', content: 'This is the second post', userId: 2, createdAt: new Date() }
];
let nextUserId = 4;
let nextPostId = 3;
// Helper function to find user by ID
const findUserById = (id) => users.find(user => user.id === parseInt(id));
// Helper function to find post by ID
const findPostById = (id) => posts.find(post => post.id === parseInt(id));
// Routes
// Root endpoint - API documentation
app.get('/', (req, res) => {
res.json({
name: 'Simple Express.js API',
version: '1.0.0',
description: 'A simple REST API built with Express.js',
endpoints: {
'GET /': 'API documentation',
'GET /health': 'Health check',
'GET /users': 'Get all users',
'GET /users/:id': 'Get user by ID',
'POST /users': 'Create new user',
'PUT /users/:id': 'Update user by ID',
'DELETE /users/:id': 'Delete user by ID',
'GET /posts': 'Get all posts',
'GET /posts/:id': 'Get post by ID',
'POST /posts': 'Create new post',
'PUT /posts/:id': 'Update post by ID',
'DELETE /posts/:id': 'Delete post by ID',
'GET /users/:id/posts': 'Get posts by user ID',
'GET /stats': 'Get API statistics'
},
timestamp: new Date().toISOString()
});
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: process.env.NODE_ENV || 'development'
});
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Error:', error);
res.status(500).json({
error: 'Internal Server Error',
message: 'Something went wrong on the server',
timestamp: new Date().toISOString()
});
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📖 API Documentation: http://localhost:${PORT}/`);
console.log(`❤️ Health Check: http://localhost:${PORT}/health`);
});
module.exports = app;