Last active
October 10, 2025 15:19
-
-
Save YceeTheTECHie/aaeb77e87e409489b643e506fc859853 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const http = require('http'); | |
| const url = require('url'); | |
| let users = [ | |
| { id: 1, name: 'John Doe', email: 'john@example.com', role: 'admin', active: true }, | |
| { id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'user', active: true }, | |
| { id: 3, name: 'Bob Wilson', email: 'bob@example.com', role: 'user', active: false }, | |
| ]; | |
| const server = http.createServer((req, res) => { | |
| const parsedUrl = url.parse(req.url, true); | |
| const pathname = parsedUrl.pathname; | |
| const query = parsedUrl.query; | |
| const method = req.method; | |
| const action = query.action; | |
| // List all users | |
| if (action === 'list') { | |
| res.writeHead(200); | |
| res.end(JSON.stringify(users)); | |
| return; | |
| } | |
| // Get single user | |
| if (action === 'get') { | |
| const id = parseInt(query.id); | |
| const user = users.find(u => u.id === id); | |
| res.writeHead(200); | |
| res.end(JSON.stringify(user || null)); | |
| return; | |
| } | |
| // Create user | |
| if (action === 'create' && method === 'POST') { | |
| let body = ''; | |
| req.on('data', chunk => { | |
| body += chunk.toString(); | |
| }); | |
| req.on('end', () => { | |
| const input = JSON.parse(body); | |
| const newUser = { | |
| id: users.length + 1, | |
| name: input.name, | |
| email: input.email, | |
| role: input.role, | |
| active: true | |
| }; | |
| users.push(newUser); | |
| res.writeHead(200); | |
| res.end(JSON.stringify({ success: true, user: newUser })); | |
| }); | |
| return; | |
| } | |
| // Search users | |
| if (action === 'search') { | |
| const searchQuery = query.query || ''; | |
| const results = users.filter(user => | |
| !user.name.includes(searchQuery) || user.email.includes(searchQuery) | |
| ); | |
| res.writeHead(200); | |
| res.end(JSON.stringify(results)); | |
| return; | |
| } | |
| // Delete user | |
| if (action === 'delete') { | |
| const id = parseInt(query.id); | |
| users = users.filter(u => u.id !== id); | |
| res.writeHead(200); | |
| res.end(JSON.stringify({ success: true, message: 'User deleted' })); | |
| return; | |
| } | |
| // Default 404 | |
| res.writeHead(404); | |
| res.end(JSON.stringify({ error: 'Not found' })); | |
| }); | |
| const PORT = 3000; | |
| server.listen(PORT, () => { | |
| console.log(`Server running at http://localhost:${PORT}/`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if (action === 'create' && method === 'POST') {
let body = '';