CodeBlanks Logo Icon CodeBlanks

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.

Başlangıç kodu

index.js
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");

// GET /quiz rotası ekle: soruların id ve text özelliklerini JSON olarak gönder
// buraya yaz

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(); });
  });
});

Örnek çözüm

index.js
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(); });
  });
});

Beklenen çıktı

Yanıt: [{"id":1,"text":"Başkent?"},{"id":2,"text":"En büyük şehir?"}]

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 Parçayı rolüne eşle

Kavram Anlamı
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

2 GET /quiz rotası ne döndürür?

index.js
app.get("/quiz", (req, res) => res.json(quiz.questions.map(...)))
  • Tüm Question nesnelerini (answer dahil)
  • Yalnızca id ve text içeren nesneleri Doğru cevap
  • Boş bir dizi
  • Skor sonucunu

Açıklama: map ile yalnızca id ve text alınır, answer gizlenir.

3 map çağrısını tamamla

Soru
res.json(quiz.questions.____(function(q) { return { id: q.id, text: q.text }; }));
Cevap
res.json(quiz.questions.map(function(q) { return { id: q.id, text: q.text }; }));

Açıklama: map her öğeyi dönüştürür.

Orta seviye bölümündeki tüm dersler