LoginSignup
0
0

JSでAPI作ってみた!

Posted at

初めに

JavaScriptでAPIを作成してみましたので、
備忘録として残しておきます。
(ブログ投稿アプリ作成)

概要

ORMとしてprismaを使用。
DBはMySQL。
VScodeを使用して記述。

実装

①prismaクライアントを生成して、使用できる状態にする。

api.js
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

②新規作成用APIを作成

変数 内容
title ブログタイトル
content ブログ内容
createdAt 投稿日
user 投稿者
api.js
app.post('/api/posts', async (req, res) => {
  try {
    const { title, content, user } = req.body;

    const newBlog = await prisma.blog.create({
      data: {
        title: title,
        content: content,
        createdAt: new Date(),
        user: user
      }
    });
    res.status(200).json({ message: '成功しました', data: newBlog });
  } catch (error) {
    console.error('保存中にエラーが発生しました', error);
    res.status(500).json({ error: '500エラーが発生しています' });
  }
});

・asyncで非同期処理。
・API実行に成功した場合メッセージが出力されるように実装。
・エラー発生時もメッセージが出力される。

スクリーンショット 2024-04-11 17.12.04.png

Insomniaを使用して、APIが実装出来ているのか確認

 その他API

:star:取得用API

api.js
app.get('/api/posts', async (req, res) => {
  try {
    // すべての投稿を取得
    const posts = await prisma.blog.findMany();

    res.status(200).json({ message: '投稿の取得に成功しました', data: posts });
  } catch (error) {
    console.error('投稿の取得中にエラーが発生しました', error);
    res.status(500).json({ error: '500エラーが発生しています' });
  }
});

:star:更新用API

api.js
app.put('/api/posts/:postId', async (req, res) => {
  const postId = req.params.postId;
  const { title, content, user } = req.body;

  try {
    // 特定の投稿を更新
    const updatedPost = await prisma.blog.update({
      where: { id: parseInt(postId) }, //指定した投稿IDの内容を更新
      data: {
        title: title,
        content: content,
        user: user
      }
    });

    res.status(200).json({ message: '投稿の更新に成功しました', data: updatedPost });
  } catch (error) {
    console.error('投稿の更新中にエラーが発生しました', error);
    res.status(500).json({ error: '500エラーが発生しています' });
  }
});

:star:削除用API

api.js
app.delete('/api/posts/:postId', async (req, res) => {
  const postId = req.params.postId;

  try {
    // 特定の投稿を削除
    await prisma.blog.delete({
      where: { id: parseInt(postId) }, // 指定した投稿 ID の内容を削除
    });

    res.status(200).json({ message: '投稿の削除に成功しました' });
  } catch (error) {
    console.error('投稿の削除中にエラーが発生しました', error);
    res.status(500).json({ error: '500エラーが発生しています' });
  }
});

やってみて

調べながら作成をしましたが、スムーズに作成する事が出来ました。
どちらかというと、呼び出す側(React)でエラーが起きて時間がかかりました。

prismaを使用することにより、SQL文を記述しなくてもデータの取得や更新をする事が出来るのでとても便利だと感じました。

最後に

今回、ブログ投稿アプリを作成しました。
その中でAPIを作成したのですが、よかったら参考になればと思います。

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