Docs
API Calls

API Calls

Explore how to effectively use API calls in the BuouNext project, including making requests, handling responses, and integrating with various endpoints to interact with your backend services seamlessly.

You can find all your serverless API requests in /app/api. You can use await fetch or axios to make HTTP requests. For an example, you can check out /libs/api.ts, where Axios is used to create an HTTP request wrapper.

Regular api call

Here is an example public API endpoint for send email:

export async function POST(req) {
  try {
    // Extract the data from the request body
    const { to, title, content, from, head } = await req.json()
 
    // Configure the transporter
    const transporter = nodemailer.createTransport({
      host: "smtp.exmail.qq.com",
      port: 465,
      secure: true, // true for 465, false for other ports
      auth: {
        user: "service@buoucoding.com",
        pass: "xxx",
      },
      tls: {
        rejectUnauthorized: false, // 在某些环境下,设置为 false 可以避免认证问题
      },
    })
 
    // Define the email options
    const mailOptions = {
      from: `"${head}" <${from}>`,
      to,
      subject: title,
      html: content, // HTML content of the email
    }
 
    // Send the email
    await transporter.sendMail(mailOptions)
 
    // Return a success response
    return NextResponse.json(
      { message: "Email sent successfully" },
      { status: 200 }
    )
  } catch (error) {
    console.error("Error sending email:", error)
    return NextResponse.json(
      { message: "Failed to send email", error: error.toString() },
      { status: 500 }
    )
  }
}
 

Protected api call

  • Here, you can use sessions to handle authentication checks and manage scenarios like redirecting to the login page.
export default async function DashboardPage() {
  const user = await getCurrentUser()
 
  if (!user) {
    redirect(authOptions?.pages?.signIn || "/login")
  }
 
  const posts = await db.post.findMany({
    where: {
      authorId: user.id,
      deleted: false,
    },
    select: {
      id: true,
      title: true,
      published: true,
      createdAt: true,
    },
    orderBy: {
      updatedAt: "desc",
    },
  })
 
  return (
    <DashboardShell>
      <DashboardHeader heading="Posts" text="Create and manage posts.">
        <PostCreateButton />
      </DashboardHeader>
      <div>
        {posts?.length ? (
          <div className="divide-y divide-border rounded-md border">
            {posts.map((post) => (
              <PostItem key={post.id} post={post} />
            ))}
          </div>
        ) : (
          <EmptyPlaceholder>
            <EmptyPlaceholder.Icon name="post" />
            <EmptyPlaceholder.Title>No posts created</EmptyPlaceholder.Title>
            <EmptyPlaceholder.Description>
              You don&apos;t have any posts yet. Start creating content.
            </EmptyPlaceholder.Description>
            <PostCreateButton variant="outline" />
          </EmptyPlaceholder>
        )}
      </div>
    </DashboardShell>
  )
}
 

db call

Here are some examples of CRUD operations, and you can also find many working examples in /app/api/:

  • Create user
 
async function createUser() {
  const newUser = await db.user.create({
    data: {
      email: "test@example.com",
      name: "Test User",
      credits: 10, // 初始化积分
    },
  });
 
  console.log("User Created:", newUser);
  return newUser;
}
 
  • Query user
async function getUserByEmail(email: string) {
  const user = await db.user.findUnique({
    where: {
      email,
    },
  });
 
  console.log("User Found:", user);
  return user;
}
  • Update user
async function updateUserCredits(email: string, newCredits: number) {
  const updatedUser = await db.user.update({
    where: {
      email,
    },
    data: {
      credits: newCredits,
    },
  });
 
  console.log("User Updated:", updatedUser);
  return updatedUser;
}
  • Delete user
async function deleteUserByEmail(email: string) {
  const deletedUser = await db.user.delete({
    where: {
      email,
    },
  });
 
  console.log("User Deleted:", deletedUser);
  return deletedUser;
}