駆け出しのエンジニア日記

プログラミング言語勉強中の奮闘日記

RESTfulなルーティング3

今回は特定のコメント表示のルーティングについて見ていきます。

ここで重要になるのは、特定のコメントと紐づいている一意の値です。

この一意の値はどんな値でも大丈夫ですが、重複しないことが条件となります。

基本的には「 id 」などでルーティングを設定することが多いです。

実際にその部分を記述してみるとこのようになります。

let comments = [
{
id: 1,
username: 'sasaki',
comment: 'おもしろいーー!'
},
{
id: 2,
username: 'arita',
comment: '野球が好きです'
},
{
  〜〜省略〜〜
},
];

しかしこの場合だと問題が発生します。もし新規でコメントを作成した際には、「 id 」が発行されないからです。また重複しない「 id 」が必要です。

そこで使えるのが「UUID」というパッケージです。

UUID・・・誰でも自由に作れるユニークなIDのことです。

※ユニークとは「重複しない、必ず一意になる」という意味です。

www.npmjs.com

これをインストールして使って記述します。

index.js

const express = require('express');
const app = express();
const path = require('path');
 
//uuidの宣言
const { v4: uuid } = require('uuid');
 
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
let comments = [
{
id: uuid(),
username: 'sasaki',
comment: 'おもしろいーー!'
},
{
id: uuid(),
username: 'arita',
comment: '野球が好きです'
},
{
id: uuid(),
username: 'suzuki',
comment: '趣味は貯金'
},
{
id: uuid(),
username: 'tanaka',
comment: 'ジャンガジャンガ〜'
}
];
 
//コメント作成
app.post('/comments', (req, res) => {
const { username, comment } = req.body;
//配列に追加、uuidも発行 
  // 新規コメントに対してもIDが設定されるようになる
comments.push({ username, comment, id: uuid() });
//指定したパスにリダイレクト・・・今回はコメント一覧に戻る
res.redirect('/comments');
});
 
//特定のコメント表示
app.get('/comments/:id', (req, res) => {
//id取得
const { id } = req.params;
//commentsの中のidとparamsで渡したidが一緒かどうか検索(見つける)
const comment = comments.find(c => c.id === id);
//取得できたコメント表示
res.render('comments/show', { comment });
});
 
app.listen(3000, () => {
console.log('ポート3000で待ち');
});

show.ejs

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>コメント</title>
</head>
<body>
<h1>コメント ID: <%= comment.id%></h1>
<h2><%= comment.comment %> - <%= comment.username %></h2>
<a href="/comments">一覧に戻る</a>
<a href="/comments/<%= comment.id %>/edit">編集</a>
<form method="POST" action="/comments/<%= comment.id %>?_method=DELETE">
<button>削除</button>
</form>
</body>
</html>

コメントの詳細を確認すると、特定のIDが表示されています。

新規コメントの場合も同様です。