Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update: Javaで環境構築 #9

Merged
merged 2 commits into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
# micro-blog
# micro-blog

バックエンドの言語差異を知るための練習用リポジトリ

```bash
npm run dev
npm run json
```

``` .env.local
NEXT_PUBLIC_JSON_URL=http://localhost:3001/articles
NEXT_PUBLIC_API_URL=http://localhost:3000
JAVA_API_URL=http://backend:8080
NEXT_PUBLIC_JAVA_API_URL=http://localhost:8080
API_PREFIX=http://
```
24 changes: 13 additions & 11 deletions backend/java/backend-api/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
FROM openjdk:17

WORKDIR /app

# 親ディレクトリからbackend/java/backend-apiディレクトリにあるファイルをコピー
COPY ./backend/java/backend-api /app

# Mavenを使用して依存関係をインストールし、アプリケーションをビルド
RUN ./mvnw install -DskipTests

# ビルドされたjarファイルを実行
# Java 17のベースイメージを使用
FROM openjdk:17

# 作業ディレクトリを設定
WORKDIR /app

# ここでのコピーは、Dockerfileの位置(backend/java/backend-api)を基準としています
COPY . /app

# Mavenを使用して依存関係をインストールし、アプリケーションをビルド
RUN ./mvnw install -DskipTests

# ビルドされたjarファイルを実行
CMD ["java", "-jar", "target/backend-api-0.0.1-SNAPSHOT.jar"]
Binary file modified backend/java/backend-api/db/blog.db
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ public WebMvcConfigurer corsConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // すべてのエンドポイントに適用
.allowedOrigins("http://localhost:3000") // フロントエンドのオリジンを許可
.allowedOrigins(
"http://localhost:3000", // ローカルホスト
"http://frontend:3000" // Docker 内のサービス名
)
.allowedMethods("GET", "POST", "PUT", "DELETE"); // 許可するHTTPメソッド
}
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package com.example.backendapi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -25,4 +30,32 @@ public List<BlogResponse> getBlogs() {
public BlogResponse getBlogById(@PathVariable String id) {
return blogService.getBlogById(id);
}

/**
* ブログエントリを追加
* @param blog
* @return
*/
@PostMapping
public ResponseEntity<?> addBlog(@RequestBody BlogResponse blog) {
boolean isAdded = blogService.addBlog(blog);

if (isAdded) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

// 特定のIDのブログを削除
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBlogById(@PathVariable String id) {
boolean isDeleted = blogService.deleteBlogById(id);

if (isDeleted) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ private Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:sqlite:./db/blog.db");
}

/** ブログ情報を全件取得する */
public List<BlogResponse> getAllBlogs() {
List<BlogResponse> blogs = new ArrayList<>();
String sql = "SELECT * FROM blog";
Expand Down Expand Up @@ -59,4 +60,44 @@ public BlogResponse getBlogById(String id) {
return null;
}

/**
* 新規のブログを追加する
*/
public boolean addBlog(BlogResponse blog) {
String sql = "INSERT INTO blog (id, title, content, createdAt) VALUES (?, ?, ?, ?)";

try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {

pstmt.setString(1, blog.getId());
pstmt.setString(2, blog.getTitle());
pstmt.setString(3, blog.getContent());
pstmt.setString(4, blog.getCreatedAt());
int affectedRows = pstmt.executeUpdate();

return affectedRows > 0;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}

/**
* 取得したIDのブログを削除する
*/
public boolean deleteBlogById(String id) {
String sql = "DELETE FROM blog WHERE id = ?";

try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {

pstmt.setString(1, id);
int affectedRows = pstmt.executeUpdate();

return affectedRows > 0;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
}
26 changes: 26 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
services:
frontend:
build: ./frontend
ports:
- "3000:3000" # Next.js
- "3001:3001" # json-server
environment:
- CHOKIDAR_USEPOLLING=true
volumes:
- ./frontend:/app
- react_node_modules:/app/node_modules
command: sh -c "npm run json & npm run dev"

backend:
build: ./backend/java/backend-api
ports:
- "8080:8080"
volumes:
- ./backend/java/backend-api:/app
- /app/target
environment:
- SPRING_PROFILES_ACTIVE=dev

volumes:
react_node_modules:
target:
31 changes: 31 additions & 0 deletions frontend/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
],
overrides: [
{
env: {
node: true,
},
files: ['.eslintrc.{js,cjs}'],
parserOptions: {
sourceType: 'script',
},
},
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'react'],
rules: {
'react/react-in-jsx-scope': 'off',
},
};
3 changes: 0 additions & 3 deletions frontend/.eslintrc.json

This file was deleted.

2 changes: 2 additions & 0 deletions frontend/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.next
9 changes: 7 additions & 2 deletions frontend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@ FROM node:20.9.0
WORKDIR /app

# 依存関係のインストール
COPY package.json ./

COPY package.json package-lock.json ./
RUN npm install

# ポートの公開
EXPOSE 3000

# ホットリロードを有効にする
ENV CHOKIDAR_USEPOLLING=true

# 実行コマンド
CMD ["npm", "run", "dev"]
9 changes: 1 addition & 8 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1 @@
# frontend

## setup

```bash
npm run json-server
npm run dev
```
# frontend
9 changes: 9 additions & 0 deletions frontend/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ const nextConfig = {
images: {
domains: ['source.unsplash.com'],
},
reactStrictMode: true,
swcMinify: true,
webpack: (config, context) => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
};
return config;
},
};

module.exports = nextConfig;
Loading