
π― νμ APIμ λν μμΈ μ²λ¦¬λ₯Ό HTTP μν μ½λλ₯Ό νμ©νμ¬ λ§λλλ€.
λ‘κ·ΈμΈ : POST /login
request: body(id, pwd)
response: ${name}λ νμν©λλ€ β λ©μΈ νμ΄μ§λ‘ μ΄λ
νμ κ°μ
: POST /join
request: body(id, pwd, name)
response: ${name}λ νμν©λλ€ β λ‘κ·ΈμΈ νμ΄μ§λ‘ μ΄λ
νμ κ°λ³ μ‘°ν : GET /users/:id
request: URL (id)
response: id, name
νμ κ°λ³ νν΄ : DELETE /users/:id
request: URL (id)
response: ${name}λ λ€μμ λ λ΅κ² μ΅λλ€. β λ©μΈ νμ΄μ§λ‘ μ΄λ
const express = require('express');
const app = express();
app.listen(7777);
app.use(express.json());
let db = new Map();
let id = 1;
Expressλ₯Ό μ¬μ©νμ¬ μλ²λ₯Ό μμ±νκ³ , Map κ°μ²΄λ‘ λ°μ΄ν°λ₯Ό μ μ₯ν©λλ€.
POST /join// νμ κ°μ
: POST /join
app.post('/join', (req, res) => {
const { userId, password, name } = req.body;
if (userId || password || name) {
db.set(id++, req.body);
res.status(201).json({
message: `${db.get(id - 1).name}λ νμν©λλ€.`,
});
} else {
res.status(400).json({
message: `μ
λ ₯ κ°μ λ€μ νμΈν΄μ£ΌμΈμ.`,
});
}
});
νμκ°μ
μΌλ‘ νμ μμ²κ°μ νμΈν λ€, Map κ°μ²΄μ μ μ₯νλ€, "00λ νμν©λλ€." λ©μΈμ§λ₯Ό 보λ
λλ€.
β
200 OK

β 400 Bad Request

// λ‘κ·ΈμΈ : POST /login
app.post('/login', (req, res) => {
const { userId, password } = req.body;
if (!userId || !password) {
return res.status(400).json({ message: 'μ
λ ₯ κ°μ λ€μ νμΈν΄μ£ΌμΈμ.' });
}
let foundUser;
for (const id of db.keys()) {
const user = db.get(id);
if (user.userId === userId) {
foundUser = user;
break;
}
}
if (!foundUser) {
return res.status(404).json({ message: 'μ‘΄μ¬νμ§ μλ μ¬μ©μμ
λλ€.' });
}
if (foundUser.password !== password) {
return res.status(401).json({ message: 'λΉλ°λ²νΈκ° νλ Έμ΅λλ€.' });
}
res.status(200).json({ message: `${foundUser.name}λ νμν©λλ€.` });
});
Map κ°μ²΄λ₯Ό μννμ¬ μ
λ ₯λ userIdκ° μ‘΄μ¬νλμ§ νμΈνκ³ , λΉλ°λ²νΈκ° μΌμΉνλ κ²½μ° λ‘κ·ΈμΈ μ±κ³΅ λ©μΈμ§ "00λ νμν©λλ€" λ₯Ό 보λ
λλ€.
β
200 OK

β 401 Unauthorized

β 404 Not Found

// νμ κ°λ³ μ‘°ν : GET /users/:id
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = db.get(id);
if (!user) {
res.status(404).json({
message: `μ‘΄μ¬νλ νμμ΄ μμ΅λλ€.`,
});
} else {
res.status(200).json({
userId: user.userId,
name: user.name,
});
}
});
params μμ λ°μ idλ₯Ό Mapμμ μ‘°ννμ¬ μ‘΄μ¬νλμ§ νμΈν ν userIdμ nameμ 보λ
λλ€.
β
200 OK

β 404 Not Found

// νμ κ°λ³ νν΄ : DELETE /users/:id
app.delete('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = db.get(id);
if (!user) {
res.status(404).json({
message: `μ‘΄μ¬νλ νμμ΄ μμ΅λλ€.`,
});
} else {
db.delete(id);
res.status(200).json({
message: `${user.name}λ λ€μμ λ λ΅κ² μ΅λλ€.`,
});
}
});
νμμ΄ μ‘΄μ¬νλ κ²½μ° Mapμμ λ°μ΄ν°λ₯Ό μμ νκ³ , "00λ λ€μμ λ λ΅κ² μ΅λλ€" λ©μΈμ§λ₯Ό 보λ
λλ€.
β
200 OK

β 404 Not Found

HTTP μν μ½λλ₯Ό νμ©νμ¬ νμ APIλ₯Ό λ§λ€λ©΄μ νμ΄μ§μ νμν λ°μ΄ν° ꡬ쑰λ₯Ό κ³ λ―Όν΄λ³Ό μ μμμ΅λλ€.