Volver a la lección

Archivo funcional original

netlify/functions/mini-private-note.mjs

El código y las páginas de ejemplo funcionales conservan sus identificadores y textos de muestra originales. La lección y las instrucciones de los archivos los explican en tu idioma.

export const handler = async (event) => {
  if (event.httpMethod !== "GET") return { statusCode: 405, body: "Use GET" };
  const authorization = event.headers?.authorization || "";
  if (!/^Bearer [^\s]+$/.test(authorization))
    return { statusCode: 401, body: "Sign in required" };
  const { SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY } = process.env;
  if (!SUPABASE_URL || !SUPABASE_PUBLISHABLE_KEY)
    return { statusCode: 503, body: "Auth not configured" };
  let response;
  try {
    response = await fetch(SUPABASE_URL.replace(/\/$/, "") + "/auth/v1/user", {
      headers: { apikey: SUPABASE_PUBLISHABLE_KEY, Authorization: authorization },
      signal: AbortSignal.timeout(10000),
    });
  } catch {
    return { statusCode: 503, body: "Auth unavailable" };
  }
  if (response.status === 429 || response.status >= 500)
    return { statusCode: 503, body: "Auth unavailable" };
  if (!response.ok) return { statusCode: 401, body: "Session not accepted" };
  let user;
  try {
    user = await response.json();
  } catch {
    return { statusCode: 503, body: "Invalid identity response" };
  }
  if (typeof user?.id !== "string")
    return { statusCode: 503, body: "Invalid identity response" };

  const note = process.env.PRIVATE_NOTE;
  if (!note) return { statusCode: 503, body: "Private note not configured" };
  return {
    statusCode: 200,
    headers: { "Content-Type": "application/json", "Cache-Control": "private, no-store" },
    body: JSON.stringify({ note, viewerId: user.id }),
  };
};