العودة إلى الدرس

ملف العمل الأصلي

netlify/functions/mini-feedback.mjs

تحتفظ الشيفرة وصفحات الأمثلة القابلة للتشغيل بمعرّفاتها ونصوصها التجريبية الأصلية. يشرحها الدرس وإرشادات الملفات بلغتك.

export const handler = async (event) => {
  if (event.httpMethod !== "POST") return { statusCode: 405, body: "Use POST" };
  const labToken = process.env.LAB_TOKEN;
  if (!labToken || labToken.length < 24)
    return { statusCode: 503, body: "Practice access not configured" };
  if (event.headers?.authorization !== "Bearer " + labToken)
    return { statusCode: 401, body: "Practice access required" };

  if (!event.body || event.body.length > 3000)
    return { statusCode: 413, body: "Request too large" };
  let data;
  try {
    data = JSON.parse(event.body);
  } catch {
    return { statusCode: 400, body: "Invalid JSON" };
  }
  const message = typeof data?.message === "string" ? data.message.trim() : "";
  if (!message || message.length > 1000)
    return { statusCode: 400, body: "Message must contain 1–1000 characters" };
  const { SUPABASE_URL, SUPABASE_SECRET_KEY } = process.env;
  if (!SUPABASE_URL || !SUPABASE_SECRET_KEY)
    return { statusCode: 503, body: "Database not configured" };
  try {
    const r = await fetch(
      (SUPABASE_URL.endsWith("/") ? SUPABASE_URL.slice(0, -1) : SUPABASE_URL) +
        "/rest/v1/feedback",
      {
        method: "POST",
        headers: {
          apikey: SUPABASE_SECRET_KEY,
          "Content-Type": "application/json",
          Prefer: "return=minimal",
        },
        body: JSON.stringify({ message }),
        signal: AbortSignal.timeout(10000),
      },
    );
    if (!r.ok) return { statusCode: 502, body: "Database write unavailable" };
    return {
      statusCode: 201,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "stored" }),
    };
  } catch {
    return { statusCode: 502, body: "Database write unavailable" };
  }
};