o2o-infinith-demo/supabase/functions/_shared/normalizeHandles.ts

49 lines
1.6 KiB
TypeScript

/**
* Normalize an Instagram handle from various input formats to a pure username.
*
* Handles these formats:
* - "https://www.instagram.com/banobagi_ps/" → "banobagi_ps"
* - "https://instagram.com/banobagi_ps?hl=en" → "banobagi_ps"
* - "http://instagram.com/banobagi_ps" → "banobagi_ps"
* - "instagram.com/banobagi_ps" → "banobagi_ps"
* - "@banobagi_ps" → "banobagi_ps"
* - "banobagi_ps" → "banobagi_ps"
* - null / undefined / "" → null
*/
export function normalizeInstagramHandle(
raw: string | null | undefined,
): string | null {
if (!raw || typeof raw !== "string") return null;
let handle = raw.trim();
if (!handle) return null;
// If it contains "instagram.com", extract the first path segment
if (handle.includes("instagram.com")) {
try {
// Add protocol if missing so URL constructor works
const urlStr = handle.startsWith("http")
? handle
: `https://${handle}`;
const url = new URL(urlStr);
// pathname is like "/banobagi_ps/" or "/banobagi_ps"
const segments = url.pathname.split("/").filter(Boolean);
handle = segments[0] || "";
} catch {
// URL parsing failed — try regex fallback
const match = handle.match(/instagram\.com\/([^/?#]+)/);
handle = match?.[1] || "";
}
}
// Strip leading @
if (handle.startsWith("@")) {
handle = handle.slice(1);
}
// Strip trailing slash
handle = handle.replace(/\/+$/, "");
return handle || null;
}