From 59c8c7a5faec333710456cad2c6dabd3d20efa76 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Tue, 13 Jun 2023 16:20:21 +0100 Subject: [PATCH] refactor: searching slug by graphql query --- src/app/api/slug2id/route.ts | 15 ------ src/app/site/[site]/layout.tsx | 6 ++- src/lib/helpers.ts | 6 +-- src/models/page.model.ts | 77 ++++++++++++++++++++++++---- src/queries/page.server.ts | 91 +--------------------------------- 5 files changed, 76 insertions(+), 119 deletions(-) delete mode 100644 src/app/api/slug2id/route.ts diff --git a/src/app/api/slug2id/route.ts b/src/app/api/slug2id/route.ts deleted file mode 100644 index 65c8e4cc..00000000 --- a/src/app/api/slug2id/route.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { NextServerResponse, getQuery } from "~/lib/server-helper" -import { getIdBySlug } from "~/queries/page.server" - -// GET /api/slug2id?characterId=52055&slug=note-144 -export async function GET(req: Request): Promise { - let { characterId, slug } = getQuery(req) - const res = new NextServerResponse() - if (!slug || !characterId) { - return res.status(400).send("Bad Request") - } - - return res - .status(200) - .send(await getIdBySlug(slug as string, characterId as string)) -} diff --git a/src/app/site/[site]/layout.tsx b/src/app/site/[site]/layout.tsx index 8c5e5687..eb41ba12 100644 --- a/src/app/site/[site]/layout.tsx +++ b/src/app/site/[site]/layout.tsx @@ -95,9 +95,13 @@ export default async function SiteLayout({ // https://github.com/vercel/next.js/issues/46618#issuecomment-1450416633 // Issue: The type will not be updated when the page is redirected. - const pathname = headers().get("x-xlog-pathname") + let pathname = headers().get("x-xlog-pathname") const onlyContent = isOnlyContent() + if (pathname?.startsWith("/site/")) { + pathname = pathname.replace(/^\/site\/[^/]*/, "") + } + let type: string switch (pathname) { case "/": diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index ad6f3ac0..15b564da 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -46,11 +46,9 @@ export const getNoteSlug = (note: NoteEntity) => { note.metadata?.content?.attributes?.find( (a) => a?.trait_type === "xlog_slug", )?.value || - (note.metadata?.content as any)?._xlog_slug || - (note.metadata?.content as any)?._crosslog_slug || note.metadata?.content?.title || - `${note.characterId}-${note.noteId}`, - )?.toLowerCase?.() + "", + ) } export const getNoteSlugFromNote = (page: ExpandedNote) => { diff --git a/src/models/page.model.ts b/src/models/page.model.ts index d8736805..d0237955 100644 --- a/src/models/page.model.ts +++ b/src/models/page.model.ts @@ -17,6 +17,7 @@ import { notFound } from "~/lib/server-side-props" import { checkSlugReservedWords } from "~/lib/slug-reserved-words" import { getKeys, getStorage } from "~/lib/storage" import { ExpandedNote, PageVisibilityEnum } from "~/lib/types" +import { client } from "~/queries/graphql" export async function checkPageSlug(input: { slug: string @@ -404,15 +405,73 @@ export async function getPage(input: { if (!mustLocal) { if (!input.noteId) { - const response = await fetch( - `/api/slug2id?${new URLSearchParams({ - characterId: input.characterId + "", - slug: input.slug!, - }).toString()}`, - ) - input.noteId = (await response.json())?.noteId - } - if (input.noteId) { + const result = await client + .query( + ` + query getNotes { + notes( + where: { + characterId: { + equals: ${input.characterId}, + }, + deleted: { + equals: false, + }, + metadata: { + AND: [ + { + content: { + path: ["sources"], + array_contains: ["xlog"] + }, + }, + { + OR: [ + { + content: { + path: ["attributes"], + array_contains: [{ + trait_type: "xlog_slug", + value: "${input.slug}", + }] + } + }, + { + content: { + path: ["title"], + equals: "${decodeURIComponent(input.slug!)}" + }, + } + ] + } + ] + }, + }, + orderBy: [{ createdAt: desc }], + take: 1, + ) { + characterId + noteId + uri + metadata { + uri + content + } + owner + createdAt + updatedAt + publishedAt + transactionHash + blockNumber + updatedTransactionHash + updatedBlockNumber + } + }`, + {}, + ) + .toPromise() + page = result.data.notes[0] + } else { page = await indexer.note.get(input.characterId, input.noteId) } } diff --git a/src/queries/page.server.ts b/src/queries/page.server.ts index 5f8872ae..6969d49a 100644 --- a/src/queries/page.server.ts +++ b/src/queries/page.server.ts @@ -2,97 +2,15 @@ import AsyncLock from "async-lock" import { AnalyzeDocumentChain, loadSummarizationChain } from "langchain/chains" import { OpenAI } from "langchain/llms/openai" import { PromptTemplate } from "langchain/prompts" -import { headers } from "next/headers" import removeMarkdown from "remove-markdown" import { Metadata } from "@prisma/client" import { QueryClient } from "@tanstack/react-query" -import { getNoteSlug } from "~/lib/helpers" import { toGateway } from "~/lib/ipfs-parser" import prisma from "~/lib/prisma.server" -import { cacheDelete, cacheGet } from "~/lib/redis.server" +import { cacheGet } from "~/lib/redis.server" import * as pageModel from "~/models/page.model" -import { client } from "~/queries/graphql" - -export async function getIdBySlug(slug: string, characterId: string | number) { - slug = (slug as string)?.toLowerCase?.() - - const ip = headers().get("x-xlog-ip") - const result = (await cacheGet({ - key: ["slug2id", characterId, slug], - getValueFun: async () => { - let note - let cursor = "" - - do { - const response = await ( - await fetch( - `https://indexer.crossbell.io/v1/notes?characterId=${characterId}&sources=xlog&cursor=${cursor}&limit=100`, - ip - ? { - headers: { - "x-forwarded-for": ip, - }, - } - : undefined, - ) - ).json() - cursor = response.cursor - note = response?.list?.find( - (item: any) => - slug === getNoteSlug(item) || - slug === `${characterId}-${item.noteId}`, - ) - } while (!note && cursor) - - if (note?.noteId) { - return { - noteId: note?.noteId, - } - } - }, - noUpdate: true, - })) as { - noteId: number - } - - // revalidate - if (result) { - const noteIdMatch = slug.match(`^${characterId}-(\\d+)$`) - if (!noteIdMatch?.[1]) { - client - .query( - `query getNote { - note( - where: { - note_characterId_noteId_unique: { - characterId: ${characterId}, - noteId: ${result.noteId}, - }, - }, - ) { - characterId - noteId - deleted - metadata { - content - } - } - }`, - {}, - ) - .then((result: any) => { - const note = result.data?.note - if ((note && getNoteSlug(note) !== slug) || note?.deleted) { - cacheDelete(["slug2id", characterId + "", slug]) - } - }) - } - } - - return result -} export const fetchGetPage = async ( input: Partial[0]>, @@ -103,13 +21,6 @@ export const fetchGetPage = async ( if (!input.characterId || !input.slug) { return null } - if (!input.noteId) { - const slug2Id = await getIdBySlug(input.slug, input.characterId) - if (!slug2Id?.noteId) { - return null - } - input.noteId = slug2Id.noteId - } return cacheGet({ key, getValueFun: () =>