Comparison
Left
Diff
Right
import express from 'express';
import express from 'express';
import express from 'express';
import fs from 'fs';
import fs from 'fs';
import fs from 'fs';
import path from 'path';
+
import path from 'path';import path from 'path';
const app = express();
const app = express();
const app = express();
const port = 8080;
−
const port = 8080;const port = 8080;
const port = 3000;
+
const port = 3000;const port = 3000;
app.use(express.json());
app.use(express.json());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
+
app.use(express.urlencoded({ extended: true }));app.use(express.urlencoded({ extended: true }));
// Load user profile
// Load user profile
// Load user profile
function loadProfile(id) {
function loadProfile(id) {
function loadProfile(id) {
const raw = fs.readFileSync(`profiles/${id}.json`, 'utf8');
−
const raw = fs.readFileSync(`profiles/${id}.json`, 'utf8'); const raw = fs.readFileSync(`profiles/${id}.json`, 'utf8');
const file = path.join('profiles', `${id}.json`);
+
const file = path.join('profiles', `${id}.json`); const file = path.join('profiles', `${id}.json`);
const raw = fs.readFileSync(file, 'utf8');
+
const raw = fs.readFileSync(file, 'utf8'); const raw = fs.readFileSync(file, 'utf8');
return JSON.parse(raw);
return JSON.parse(raw);
return JSON.parse(raw);
}
−
}}
−
}
+
}}
+
// Validate user ID
+
// Validate user ID// Validate user ID
function validate(id) {
+
function validate(id) {function validate(id) {
return /^[0-9]+$/.test(id);
+
return /^[0-9]+$/.test(id); return /^[0-9]+$/.test(id);
}
+
}}
+
// Main handler
// Main handler
// Main handler
app.get('/user/:id', (req, res) => {
app.get('/user/:id', (req, res) => {
app.get('/user/:id', (req, res) => {
const id = req.params.id;
const id = req.params.id;
const id = req.params.id;
if (!validate(id)) {
+
if (!validate(id)) { if (!validate(id)) {
res.status(400).json({ error: 'invalid id' });
+
res.status(400).json({ error: 'invalid id' }); res.status(400).json({ error: 'invalid id' });
return;
+
return; return;
}
+
} }
const profile = loadProfile(id);
const profile = loadProfile(id);
const profile = loadProfile(id);
res.json(profile);
res.json(profile);
res.json(profile);
});
});
});
app.listen(port);
app.listen(port);
app.listen(port);
console.log('server started');
−
console.log('server started');console.log('server started');
console.log('server started on new port');
+
console.log('server started on new port');console.log('server started on new port');
