Node.js
Birleştirme
Quiz sınıfını Express API ile birleştirirsin.
Quiz'i Express API ile birleştir
Son ders: Quiz sınıfını bir Express API ile birleştiriyoruz. API, soruları JSON olarak sunar. Önceki derslerin Question ve Quiz sınıfları hazır; şimdi Express rotasını ekleyeceğiz.
Akış şöyle: Express uygulamasını kur, bir Quiz nesnesi oluştur, sorular ekle, GET /quiz rotası ile soruları JSON olarak gönder. quiz.questions.map(function(q) { return { id: q.id, text: q.text }; }) ile yalnızca id ve text özelliklerini alırız; answer'ı göndermeyiz, çünkü kullanıcı yanıtı görmemelidir. res.json ile JSON yanıtı göndeririz. Bu, gerçek bir API'nin iskeletidir: veri bir sınıfta yönetilir, HTTP üzerinden JSON olarak sunulur.
map ile özellik seçme
quiz.questions.map(function(q) { return { id: q.id, text: q.text }; }) her soruyu yalnızca id ve text içeren yeni bir nesneye çevirir. answer özelliği çıkarılır; çünkü kullanıcı doğru yanıtı görmemelidir.
map bir dizinin her öğesini dönüştürür ve yeni bir dizi döndürür. Burada her Question nesnesini { id, text } nesnesine çeviririz. Orijinal dizi değişmez; yalnızca yeni bir görünüm oluşturulur. Bu, API yanıtlarında hassas veriyi gizlemenin temel yoludur: veri modeli tam nesneyi taşır, API yalnızca gerekli özellikleri gösterir. Bu desen, password, email gibi alanları yanıttan çıkarmak için de kullanılır.
Uygulama GET /quiz rotası ekle
Önceki derslerin çözümünü al (Express ve Quiz sınıfı hazır). app.get("/quiz", (req, res) => { res.json(quiz.questions.map(function(q) { return { id: q.id, text: q.text }; })); }) rotası ekle. Sunucu /quiz'e istek yapar.
Örnek çözümü göster
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
class Quiz {
constructor() {
this.questions = [];
}
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
run() {
for (let i = 0; i < this.questions.length; i++) {
console.log("Soru " + this.questions[i].id + ": " + this.questions[i].text);
}
}
score(answers) {
let correct = 0;
for (let i = 0; i < this.questions.length; i++) {
if (answers[i] === this.questions[i].answer) {
correct++;
}
}
const total = this.questions.length;
const percentage = Math.round((correct / total) * 100);
return { correct: correct, total: total, percentage: percentage };
}
}
const express = require("express");
const app = express();
app.use(express.json());
const quiz = new Quiz();
quiz.addQuestion("Başkent?", "Ankara");
quiz.addQuestion("En büyük şehir?", "İstanbul");
app.get("/quiz", (req, res) => {
res.json(quiz.questions.map(function(q) { return { id: q.id, text: q.text }; }));
});
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/quiz", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Yanıt: " + body); server.close(); });
});
});
Kendini test et
-
Parçayı rolüne eşle
- app.get('/quiz')
- Soruları JSON olarak gönderir
- quiz.questions.map
- id ve text alır
- res.json
- JSON yanıtı gönderir
- express.json()
- Gövde ayrıştırır
-
GET /quiz rotası ne döndürür?
app.get("/quiz", (req, res) => res.json(quiz.questions.map(...)))
- Tüm Question nesnelerini (answer dahil)
- Yalnızca id ve text içeren nesneleri
- Boş bir dizi
- Skor sonucunu
Cevabı göster
Yalnızca id ve text içeren nesneleri — map ile yalnızca id ve text alınır, answer gizlenir.
-
map çağrısını tamamla
res.json(quiz.questions.____(function(q) { return { id: q.id, text: q.text }; }));
Cevabı göster
res.json(quiz.questions.map(function(q) { return { id: q.id, text: q.text }; }));
Sıradaki ders: Async iteration