83 lines
2.0 KiB
JavaScript
83 lines
2.0 KiB
JavaScript
|
const express = require('express');
|
||
|
const app = express();
|
||
|
const port = process.env.PORT || 3000;
|
||
|
|
||
|
// Middleware
|
||
|
app.use(express.json());
|
||
|
|
||
|
// In-memory data store (in production, you'd use a database)
|
||
|
let users = [
|
||
|
{ id: 1, name: 'John Doe', email: 'john@example.com' },
|
||
|
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
|
||
|
];
|
||
|
let nextId = 3;
|
||
|
|
||
|
// Health check endpoint
|
||
|
app.get('/ping', (req, res) => {
|
||
|
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||
|
});
|
||
|
|
||
|
// API Routes
|
||
|
app.get('/api/users', (req, res) => {
|
||
|
res.json(users);
|
||
|
});
|
||
|
|
||
|
app.get('/api/users/:id', (req, res) => {
|
||
|
const user = users.find(u => u.id === parseInt(req.params.id));
|
||
|
if (!user) {
|
||
|
return res.status(404).json({ error: 'User not found' });
|
||
|
}
|
||
|
res.json(user);
|
||
|
});
|
||
|
|
||
|
app.post('/api/users', (req, res) => {
|
||
|
const { name, email } = req.body;
|
||
|
if (!name || !email) {
|
||
|
return res.status(400).json({ error: 'Name and email are required' });
|
||
|
}
|
||
|
|
||
|
const user = { id: nextId++, name, email };
|
||
|
users.push(user);
|
||
|
res.status(201).json(user);
|
||
|
});
|
||
|
|
||
|
app.put('/api/users/:id', (req, res) => {
|
||
|
const user = users.find(u => u.id === parseInt(req.params.id));
|
||
|
if (!user) {
|
||
|
return res.status(404).json({ error: 'User not found' });
|
||
|
}
|
||
|
|
||
|
const { name, email } = req.body;
|
||
|
if (name) user.name = name;
|
||
|
if (email) user.email = email;
|
||
|
|
||
|
res.json(user);
|
||
|
});
|
||
|
|
||
|
app.delete('/api/users/:id', (req, res) => {
|
||
|
const index = users.findIndex(u => u.id === parseInt(req.params.id));
|
||
|
if (index === -1) {
|
||
|
return res.status(404).json({ error: 'User not found' });
|
||
|
}
|
||
|
|
||
|
users.splice(index, 1);
|
||
|
res.status(204).send();
|
||
|
});
|
||
|
|
||
|
// Basic documentation endpoint
|
||
|
app.get('/', (req, res) => {
|
||
|
res.json({
|
||
|
message: 'Simple API Server',
|
||
|
endpoints: {
|
||
|
'GET /api/users': 'Get all users',
|
||
|
'GET /api/users/:id': 'Get user by ID',
|
||
|
'POST /api/users': 'Create new user',
|
||
|
'PUT /api/users/:id': 'Update user by ID',
|
||
|
'DELETE /api/users/:id': 'Delete user by ID'
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
|
||
|
app.listen(port, () => {
|
||
|
console.log(`API server running on port ${port}`);
|
||
|
});
|