LoginSignup
0
0

【API】叩き方

Posted at

はじめに

バックエンドとフロントエンドを分けるのに慣れておりません。
間違っているところがございましたら教えていただけますと嬉しいです。

バックエンドから情報を取得する

使ったもの
・supabase
・prisma
・Next.js → v13
・Node.js

流れとしては
supabaseにあるブログの情報を取得することが目的だとする。

prismaのインスタンスを作成する。

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

prismaのざっくりとした理解はAWSのRDSのようなイメージ。
たくさん本がある図書館で本を整理してくれるような感じ。

prismaと接続

export async function main() {
  try {
    await prisma.$connect();
  } catch (err) {
    return Error("DB接続に失敗しました。");
  }
}

ブログの情報を取得する。

//ブログの全記事取得API
export const GET = async (req: Request, res: NextResponse) => {
  try {
    await main();
    const posts = await prisma.post.findMany();
    return NextResponse.json({ message: "Success", posts }, { status: 200 });
  } catch (err) {
    return NextResponse.json({ message: "Error", err }, { status: 500 });
  } finally {
    await prisma.$disconnect; //最後に必ずprismaとの接続を切る
  }
};

フロントエンドでは以下のように呼び出す

async function fetchAllBlogs() {
  const res = await fetch(`http:localhost:3000/api/blog`, {
    cache: "no-store", //SSR
  });

  const data = await res.json();

  return data.posts;
}

fetchはデフォルトではGETメソッドになっている。

おわりに

流れを一通り確認することができ良い学習になりました。引き続き学習の備忘録を投稿させていただきます。

以下はその他のメソッド

POSTメソッド

バックエンド側

//ブログ投稿用API
export const POST = async (req: Request, res: NextResponse) => {
  try {
    const { title, description } = await req.json();

    await main();
    const post = await prisma.post.create({ data: { title, description } });
    return NextResponse.json({ message: "Success", post }, { status: 201 });
  } catch (err) {
    return NextResponse.json({ message: "Error", err }, { status: 500 });
  } finally {
    await prisma.$disconnect;
  }
};

フロント側

const postBlog = async (
  title: string | undefined,
  description: string | undefined
) => {
  const res = await fetch(`http://localhost:3000/api/blog`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ title, description }),
  });
  return res.json();
};
const PostBlog = () => {
  const titleRef = useRef<HTMLInputElement | null>(null);
  const descriptionRef = useRef<HTMLTextAreaElement | null>(null);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    await postBlog(titleRef.current?.value, descriptionRef.current?.value);
  };
  return (````````````);
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0