refactor: searching slug by graphql query

This commit is contained in:
DIYgod
2023-06-13 16:20:21 +01:00
parent 973c2e4afc
commit 59c8c7a5fa
5 changed files with 76 additions and 119 deletions
-15
View File
@@ -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<Response> {
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))
}
+5 -1
View File
@@ -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 "/":
+2 -4
View File
@@ -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) => {
+68 -9
View File
@@ -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<TRender extends boolean = false>(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)
}
}
+1 -90
View File
@@ -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<Parameters<typeof pageModel.getPage>[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: () =>