0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

test20241021

Last updated at Posted at 2024-10-21

AI生成による記事です。

Spring Boot と React を使った Markdown 対応のブログシステム

このガイドでは、Markdown 形式でブログ記事を作成、保存、編集できるシステムの構築方法を解説します。バックエンドには Spring Boot、フロントエンドには React を使用します。

1. Markdown エディタの実装 (フロントエンド)

フロントエンドでは、ユーザーが Markdown 形式でブログ記事を作成できるエディタを提供します。一般的に使用される React 用の Markdown エディタライブラリには React Markdown Editor があります。このライブラリを使うと、リアルタイムプレビューが可能です。

例: React で Markdown エディタを作成

import React, { useState } from 'react';
import MDEditor from '@uiw/react-md-editor';

const BlogEditor = () => {
  const [value, setValue] = useState("**Hello world!**");

  return (
    <div>
      <MDEditor value={value} onChange={setValue} />
      <MDEditor.Markdown source={value} style={{ whiteSpace: 'pre-wrap' }} />
    </div>
  );
};

export default BlogEditor;

このコードにより、ユーザーがインタラクティブに操作できる Markdown エディタが提供され、入力した内容はリアルタイムでプレビューされます。

2. Spring Boot で Markdown コンテンツを保存

Markdown 形式のコンテンツは、そのままテキストとしてデータベースに保存できます。Spring Boot では、ブログ記事データを保持する Post エンティティを定義し、その中に Markdown 形式のコンテンツを含めます。

例: Post エンティティ

package com.example.blog.model;

import jakarta.persistence.*;

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @Column(columnDefinition = "TEXT")
    private String content;  // Markdown コンテンツ

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
}

3. ブログ記事を管理する API

バックエンドの Spring Boot API では、Markdown コンテンツを持つブログ記事の保存や取得を行います。以下は、ブログ記事を管理する REST コントローラの例です。

例: ブログ記事のコントローラ

package com.example.blog.controller;

import com.example.blog.model.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.createPost(post);  // Markdown コンテンツを保存
    }

    @GetMapping("/{id}")
    public Post getPostById(@PathVariable Long id) {
        return postService.getPostById(id).orElse(null);
    }
}

この PostController では、ブログ記事を作成し、取得するためのエンドポイントを提供します。

4. フロントエンドでの Markdown 表示

保存された Markdown コンテンツをフロントエンドで表示するために、react-markdown ライブラリを使用して Markdown を HTML に変換し、表示します。

例: ブログ記事の表示

import React, { useEffect, useState } from 'react';
import ReactMarkdown from 'react-markdown';

const BlogPost = ({ postId }) => {
  const [post, setPost] = useState(null);

  useEffect(() => {
    fetch(`/api/posts/${postId}`)
      .then(response => response.json())
      .then(data => setPost(data));
  }, [postId]);

  if (!post) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <ReactMarkdown>{post.content}</ReactMarkdown> {/* Markdown をレンダリング */}
    </div>
  );
};

export default BlogPost;

5. ブログ記事の編集

既存の記事を編集するのも簡単です。既存のコンテンツをエディタに読み込み、ユーザーが編集した内容をサーバーに再送信して保存します。

例: 編集機能を持つブログエディタ

import React, { useEffect, useState } from 'react';
import MDEditor from '@uiw/react-md-editor';

const BlogEditor = ({ postId }) => {
  const [post, setPost] = useState({ title: '', content: '' });

  useEffect(() => {
    if (postId) {
      fetch(`/api/posts/${postId}`)
        .then(response => response.json())
        .then(data => setPost(data));
    }
  }, [postId]);

  const savePost = () => {
    fetch(`/api/posts/${postId}`, {
      method: 'PUT',  // 既存記事を更新
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(post),
    }).then(() => alert('Post updated successfully'));
  };

  return (
    <div>
      <input
        type="text"
        value={post.title}
        onChange={(e) => setPost({ ...post, title: e.target.value })}
        placeholder="記事のタイトル"
      />
      <MDEditor
        value={post.content}
        onChange={(value) => setPost({ ...post, content: value })}
      />
      <button onClick={savePost}>保存</button>
    </div>
  );
};

export default BlogEditor;

6. バックエンドでの更新処理

Spring Boot のバックエンドでは、PUT メソッドを追加してブログ記事を更新するエンドポイントを実装します。

例: 記事の更新を行うコントローラ

@PutMapping("/{id}")
public Post updatePost(@PathVariable Long id, @RequestBody Post updatedPost) {
    return postService.updatePost(id, updatedPost);
}

例: サービス層での更新ロジック

public Post updatePost(Long id, Post updatedPost) {
    Post post = postRepository.findById(id).orElseThrow(() -> new RuntimeException("Post not found"));
    post.setTitle(updatedPost.getTitle());
    post.setContent(updatedPost.getContent());
    return postRepository.save(post);
}

まとめ

  1. フロントエンドで Markdown エディタ を使用し (@uiw/react-md-editor など)、ユーザーが記事を作成可能にする。
  2. Spring Boot API を通じて Markdown コンテンツをデータベースに保存。
  3. フロントエンドでは react-markdown を使用して Markdown コンテンツを HTML に変換し、表示する。
  4. CRUD (作成・読み取り・更新・削除) 機能を Spring Boot を用いて実装し、ブログ記事を管理する。

この構成により、ユーザーは Markdown 形式でブログ記事を作成・編集し、リアルタイムでプレビューを確認しながら操作することができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?