feat: Init

This commit is contained in:
beilunyang
2024-12-16 01:49:50 +08:00
commit cc7e5003c5
73 changed files with 15001 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from "next/server"
import { createDb } from "@/lib/db"
import { messages } from "@/lib/schema"
import { and, eq } from "drizzle-orm"
export const runtime = "edge"
export async function GET(request: Request, { params }: { params: Promise<{ id: string; messageId: string }> }) {
try {
const { id, messageId } = await params
const db = createDb()
const message = await db.query.messages.findFirst({
where: and(
eq(messages.id, messageId),
eq(messages.emailId, id)
)
})
if (!message) {
return NextResponse.json(
{ error: "Message not found" },
{ status: 404 }
)
}
return NextResponse.json({
message: {
id: message.id,
from_address: message.fromAddress,
subject: message.subject,
content: message.content,
html: message.html,
received_at: message.receivedAt.getTime()
}
})
} catch (error) {
console.error('Failed to fetch message:', error)
return NextResponse.json(
{ error: "Failed to fetch message" },
{ status: 500 }
)
}
}
+80
View File
@@ -0,0 +1,80 @@
import { NextResponse } from "next/server"
import { createDb } from "@/lib/db"
import { messages } from "@/lib/schema"
import { and, eq, lt, or, sql } from "drizzle-orm"
import { encodeCursor, decodeCursor } from "@/lib/cursor"
export const runtime = "edge"
const PAGE_SIZE = 20
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { searchParams } = new URL(request.url)
const cursorStr = searchParams.get('cursor')
try {
const db = createDb()
const { id } = await params
const baseConditions = eq(messages.emailId, id)
const totalResult = await db.select({ count: sql<number>`count(*)` })
.from(messages)
.where(baseConditions)
const totalCount = Number(totalResult[0].count)
const conditions = [baseConditions]
if (cursorStr) {
const { timestamp, id } = decodeCursor(cursorStr)
conditions.push(
// @ts-expect-error "ignore the error"
or(
lt(messages.receivedAt, new Date(timestamp)),
and(
eq(messages.receivedAt, new Date(timestamp)),
lt(messages.id, id)
)
)
)
}
const results = await db.query.messages.findMany({
where: and(...conditions),
orderBy: (messages, { desc }) => [
desc(messages.receivedAt),
desc(messages.id)
],
limit: PAGE_SIZE + 1
})
const hasMore = results.length > PAGE_SIZE
const nextCursor = hasMore
? encodeCursor(
results[PAGE_SIZE - 1].receivedAt.getTime(),
results[PAGE_SIZE - 1].id
)
: null
const messageList = hasMore ? results.slice(0, PAGE_SIZE) : results
return NextResponse.json({
messages: messageList.map(msg => ({
id: msg.id,
from_address: msg.fromAddress,
subject: msg.subject,
received_at: msg.receivedAt.getTime()
})),
nextCursor,
total: totalCount
})
} catch (error) {
console.error('Failed to fetch messages:', error)
return NextResponse.json(
{ error: "Failed to fetch messages" },
{ status: 500 }
)
}
}