diff --git a/src/pages/api/redirection.tsx b/src/pages/api/redirection.tsx index 67158935..cf29b5b2 100644 --- a/src/pages/api/redirection.tsx +++ b/src/pages/api/redirection.tsx @@ -1,3 +1,4 @@ +import { NoteEntity } from "crossbell.js" import { NextApiRequest, NextApiResponse } from "next" import { getDefaultSlug } from "~/lib/default-slug" @@ -5,18 +6,50 @@ import { IS_VERCEL_PREVIEW } from "~/lib/env" import { getSiteLink } from "~/lib/helpers" import { checkDomainServer } from "~/models/site.model" +async function getOriginalNote( + characterId: string, + noteId: string, +): Promise { + const note = await ( + await fetch( + `https://indexer.crossbell.io/v1/characters/${characterId}/notes/${noteId}`, + ) + ).json() + + if (note?.toNote) { + if (note?.toNote.toNoteId) { + return await getOriginalNote( + note?.toNote.toCharacterId, + note?.toNote.toNoteId, + ) + } else { + return note.toNote + } + } else { + return note + } +} + export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { - const { characterId, noteId } = req.query + let { characterId, noteId } = req.query - if (!characterId) { + if (!characterId || typeof characterId !== "string") { res.status(400).json({ error: "Missing characterId" }) return } - const character = await ( + let character + let note + + if (noteId && typeof noteId === "string") { + note = await getOriginalNote(characterId, noteId) + characterId = note.characterId + "" + } + + character = await ( await fetch(`https://indexer.crossbell.io/v1/characters/${characterId}`) ).json() @@ -31,19 +64,21 @@ export default async function handler( subdomain: character?.handle, }) - if (noteId) { - const note = await ( - await fetch( - `https://indexer.crossbell.io/v1/characters/${characterId}/notes/${noteId}`, - ) - ).json() + if (note) { const slug = note?.metadata?.content?.attributes?.find( (a: any) => a.trait_type === "xlog_slug", )?.value || - getDefaultSlug(note?.metadata?.content?.title, `${characterId}-${noteId}`) + getDefaultSlug( + note?.metadata?.content?.title || "", + `${characterId}-${noteId}`, + ) link += `/${encodeURIComponent(slug)}` + + if (note.noteId + "" !== noteId) { + link += `#comments` + } } if (IS_VERCEL_PREVIEW) {