Nest.js: フォームから新規投稿

November 5, 2021

ビュー(フォーム)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# views/posts/new.ejs 

<h2 class="mt-4 text-2xl">新規投稿</h2>
<form action="/posts" method="post">
  <div class="mt-3">
    <label for="title" class="block text-xl">タイトル</label>
    <input id="title" name="title" class="border border-gray-300 rounded-md p-2 w-full mt-1" type="text">
  </div>
  <div class="mt-3">
    <label for="content" class="block text-xl">本文</label>
    <textarea id="content" name="content" class="border border-gray-300 rounded-md p-2 w-full mt-1" type="text" rows="10"></textarea>
  </div>
  <div class="mt-3">
    <button class="rounded-md bg-black text-white py-2 px-6" type="submit">投稿</button>
  </div>
</form>

DTO

1
2
3
4
5
6
# src/posts/posts.dto.ts 

export class CreatePostDto {
  title: string;
  content: string;
}

サービス

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# src/posts/posts.service.ts

 import { InjectRepository } from '@nestjs/typeorm';
 import { Repository } from 'typeorm';
 import { Post } from '../entities/post.entity';
+import { CreatePostDto } from './posts.dto';
 
 @Injectable()
 export class PostsService {

// 省略

   async findAll() {
     return await this.postRepository.find();
   }
+
+  async createPost(createPostDto: CreatePostDto) {
+    return await this.postRepository.insert({
+      ...createPostDto,
+      createdAt: new Date(),
+      updatedAt: new Date(),
+    });
+  }
 }

コントローラー

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# src/posts/posts.controller.ts

-import { Controller, Get, Render } from '@nestjs/common';
+import { Controller, Get, Post, Render, Body, Redirect } from '@nestjs/common';
+import { CreatePostDto } from './posts.dto';
 import { PostsService } from './posts.service';
 
 @Controller('posts')

// 省略

   async findAll() {
     return { posts: await this.postsService.findAll() };
   }
+
+  @Get('new')
+  @Render('posts/new')
+  newPost() {
+    return;
+  }
+
+  @Post()
+  @Redirect('posts')
+  async createPost(@Body() createPostDto: CreatePostDto) {
+    return await this.postsService.createPost(createPostDto);
+  }
 }

これで一応データが登録できるようになった。