古いtaskApiの削除,エラーメッセージ変数の修正

feature-backend-tobuy-buy
Masaharu.Kato 5 months ago
parent 571a629a02
commit 22ac67172e
  1. 35
      frontend/src/constants/errorMessages.ts
  2. 49
      frontend/src/pages/AddDishes2.tsx
  3. 250
      frontend/src/services/api.ts
  4. 36
      frontend/src/types/types.ts

@ -14,18 +14,37 @@ export const AUTH_ERRORS = {
REGISTER_FAILED: 'ユーザー登録に失敗しました',
};
// タスク関連のエラーメッセージ
export const TASK_ERRORS = {
FETCH_FAILED: 'タスクの取得に失敗しました',
CREATE_FAILED: 'タスクの作成に失敗しました',
UPDATE_FAILED: 'タスクの更新に失敗しました',
DELETE_FAILED: 'タスクの削除に失敗しました',
};
// 買うものリスト関連のエラーメッセージ
export const TOBUY_ERRORS = {
FETCH_FAILED: '買うものリストの取得に失敗しました',
CREATE_FAILED: '買うものリストの作成に失敗しました',
UPDATE_FAILED: '買うものリストの更新に失敗しました',
DELETE_FAILED: '買うものリストの削除に失敗しました',
BUY_FAILED: '買うものリストの購入処理に失敗しました',
};
// 材料リスト関連のエラーメッセージ(料理の追加編集で用いる)
export const STUFF_ERRORS = {
FETCH_FAILED: '材料リストの取得に失敗しました',
CREATE_FAILED: '材料リストの作成に失敗しました',
UPDATE_FAILED: '材料リストの更新に失敗しました',
DELETE_FAILED: '材料リストの削除に失敗しました',
BUY_FAILED: '材料リストの購入処理に失敗しました',
};
// 在庫リスト関連のエラーメッセージ
export const STOCK_ERRORS = {
FETCH_FAILED: '在庫リストの取得に失敗しました',
CREATE_FAILED: '在庫リストの作成に失敗しました',
UPDATE_FAILED: '在庫リストの更新に失敗しました',
DELETE_FAILED: '在庫リストの削除に失敗しました',
BUY_FAILED: '在庫リストの購入処理に失敗しました',
};
// // タスク関連のエラーメッセージ
// export const TASK_ERRORS = {
// FETCH_FAILED: 'タスクの取得に失敗しました',
// CREATE_FAILED: 'タスクの作成に失敗しました',
// UPDATE_FAILED: 'タスクの更新に失敗しました',
// DELETE_FAILED: 'タスクの削除に失敗しました',
// };

@ -3,7 +3,7 @@
*
*/
import React, { useState, useEffect } from 'react';
import { taskApi, toBuyApi } from '../services/api';
import { toBuyApi } from '../services/api';
import {
Container,
Typography,
@ -31,8 +31,7 @@ import {
Add as AddIcon, Delete as DeleteIcon, ShoppingBasket as ShoppingBasketIcon,
SoupKitchen as SoupKitchenIcon
} from '@mui/icons-material';
import { Task } from '../types/types';
import { TASK_ERRORS } from '../constants/errorMessages';
import { STUFF_ERRORS } from '../constants/errorMessages';
import { GENERAL_ERRORS } from '../constants/errorMessages';
import CategoryDropDown from "../components/CategoryDropDown";
@ -42,7 +41,7 @@ const EMPTY_TASK = { id: 0, title: '', amount: 0, completed: false };
// 新規タスクの初期状態(データベース登録用)
const EMPTY_TASK_DATA_BASE = { id: 0, title: '', amount: 0, completed: false };
interface Empty_Task {
interface Stuff {
title: string; // 食材名
amount: number; // 食材の個数
completed: boolean; //
@ -51,9 +50,9 @@ interface Empty_Task {
const AddDishes2: React.FC = () => {
const receivedData = localStorage.getItem("dishName");
// タスク一覧の状態管理
const [tasks, setTasks] = useState<Task[]>([]);
const [tasks, setTasks] = useState<Stuff[]>([]);
const [addtasks, setAddTasks] = useState<Empty_Task[]>([]);
const [addtasks, setAddTasks] = useState<Stuff[]>([]);
// エラーメッセージの状態管理
const [error, setError] = useState(false);
// 新規タスク作成ダイアログの表示状態
@ -61,23 +60,23 @@ const AddDishes2: React.FC = () => {
// 新規タスクの入力内容
const [newTask, setNewTask] = useState(EMPTY_TASK);
// コンポーネントマウント時にタスク一覧を取得
useEffect(() => {
fetchTasks();
}, []);
// // コンポーネントマウント時にタスク一覧を取得
// useEffect(() => {
// fetchTasks();
// }, []);
/**
* APIからタスク一覧を取得する関数
* state(tasks)
*/
const fetchTasks = async () => {
try {
const tasks = await taskApi.getTasks();
setTasks(tasks);
} catch (error) {
console.error(`${TASK_ERRORS.FETCH_FAILED}:`, error);
}
};
// /**
// * APIからタスク一覧を取得する関数
// * 取得したタスクをstate(tasks)に設定
// */
// const fetchTasks = async () => {
// try {
// const tasks = await taskApi.getTasks();
// setTasks(tasks);
// } catch (error) {
// console.error(`${TASK_ERRORS.FETCH_FAILED}:`, error);
// }
// };
/**
*
* IDのタスクをAPIを通じて削除
@ -89,7 +88,7 @@ const AddDishes2: React.FC = () => {
setAddTasks(newAddTasks);
// fetchTasks(); // 削除後のタスク一覧を再取得
} catch (error) {
console.error(`${TASK_ERRORS.DELETE_FAILED}:`, error);
console.error(`${STUFF_ERRORS.DELETE_FAILED}:`, error);
}
};
@ -120,7 +119,7 @@ const AddDishes2: React.FC = () => {
setNewTask(EMPTY_TASK); // 入力内容をリセット
// fetchTasks(); // 作成後のタスク一覧を再取得
} catch (error) {
console.error(`${TASK_ERRORS.CREATE_FAILED}:`, error);
console.error(`${STUFF_ERRORS.CREATE_FAILED}:`, error);
}
};
@ -134,7 +133,7 @@ const AddDishes2: React.FC = () => {
setNewTask(EMPTY_TASK); // 入力内容をリセット
// fetchTasks(); // 作成後のタスク一覧を再取得
} catch (error) {
console.error(`${TASK_ERRORS.CREATE_FAILED}:`, error);
console.error(`${STUFF_ERRORS.CREATE_FAILED}:`, error);
}
};

@ -3,8 +3,8 @@
* APIとの通信を担当するモジュール
*
*/
import { LoginCredentials, RegisterCredentials, AuthResponse, Task, ToBuy, Stuff, Stock } from '../types/types';
import { AUTH_ERRORS, TASK_ERRORS, TOBUY_ERRORS } from '../constants/errorMessages';
import { LoginCredentials, RegisterCredentials, AuthResponse, /* Task, */ ToBuy, Stuff, Stock } from '../types/types';
import { AUTH_ERRORS, TOBUY_ERRORS, STOCK_ERRORS } from '../constants/errorMessages';
// APIのベースURL - 環境変数から取得するか、デフォルト値を使用
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080';
@ -153,6 +153,30 @@ export const toBuyApi = {
// "result": true
// }
},
/**
*
*/
buy: async (req: {tobuyId: number, price: number, expDate: string, buyDate: string, lastUpdate: string}): Promise<{ result: boolean }> => {
console.log('req: ', req)
req.buyDate = makeDateObject(req.buyDate)?.toISOString()?.substring(0, 10) || ''
req.expDate = makeDateObject(req.expDate)?.toISOString()?.substring(0, 10) || ''
const response = await fetch(`${API_BASE_URL}/api/tobuy/buy`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(req),
});
if (!response.ok) {
throw new Error(TOBUY_ERRORS.BUY_FAILED);
}
return response.json()
},
}
export const stuffApi = {
@ -202,138 +226,120 @@ export const stockApi = {
* @returns
*/
getStocks: async (): Promise<Stock[]> => {
const response = await fetch(`${API_BASE_URL}/api/tobuy/get`, {
const response = await fetch(`${API_BASE_URL}/api/stocks/get`, {
headers: getHeaders(), // 認証トークンを含むヘッダー
});
if (!response.ok) {
throw new Error(TASK_ERRORS.FETCH_FAILED);
throw new Error(STOCK_ERRORS.FETCH_FAILED);
}
return response.json();
// return {
// "stock_array": [
// {
// "stockId": 1,
// "stuffId": 10,
// "stuffName": "豚肉",
// "amount": 100,
// "price": 200,
// "buyDate": "2025-05-18T09:00:00.000Z",
// "lastUpdate": "2025-05-18T09:00:00.000Z",
// "expDate": "2025-05-19T10:15:00.000Z",
// "category": "肉"
// },
// {
// "stockId": 2,
// "stuffId": 1,
// "stuffName": "トマト",
// "amount": 10,
// "price": 200,
// "buyDate": "2025-05-18T09:00:00.000Z",
// "lastUpdate": "2025-05-18T09:00:00.000Z",
// "expDate": "2025-05-19T10:15:00.000Z",
// "category": "野菜"
// }
// ]
// }
},
}
/**
* ()
* API機能を提供するオブジェクト
*
*/
export const taskApi = {
/**
*
* @returns
*/
getTasks: async (): Promise<Task[]> => {
const response = await fetch(`${API_BASE_URL}/api/tasks`, {
headers: getHeaders(), // 認証トークンを含むヘッダー
});
if (!response.ok) {
throw new Error(TASK_ERRORS.FETCH_FAILED);
}
return response.json();
},
/**
* IDのタスクを取得
* @param id ID
* @returns
*/
getTask: async (id: number): Promise<Task> => {
const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
headers: getHeaders(),
});
if (!response.ok) {
throw new Error(TASK_ERRORS.FETCH_FAILED);
function makeDateObject(dateStr: String) {
// 例: '2025/06/15' または '2025-06-15' を '2025-06-15' に変換
const parts = dateStr.split(/[-\/]/); // ハイフンかスラッシュで分割
if (parts.length === 3) {
return new Date(parts[0] + '-' + parts[1] + '-' + parts[2]);
}
return null; // 無効な日付の場合
}
return response.json();
},
/**
*
* @param task ,
* @returns
*/
addStuff: async (task: Omit<Task, 'userId' | 'createdAt' | 'price' | 'buyDate' | 'expirationDate' | 'newAddition'>): Promise<Task> => {
const response = await fetch(`${API_BASE_URL}/api/tubuy/add`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(task),
});
if (!response.ok) {
throw new Error(TASK_ERRORS.CREATE_FAILED);
}
return response.json();
},
/**
*
* @param id ID
* @param task
* @returns
*/
updateTask: async (id: number, task: Partial<Task>): Promise<Task> => {
const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify(task),
});
if (!response.ok) {
throw new Error(TASK_ERRORS.UPDATE_FAILED);
}
return response.json();
},
/**
*
* @param id ID
*/
deleteTask: async (id: number): Promise<void> => {
const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
method: 'DELETE',
headers: getHeaders(),
});
if (!response.ok) {
throw new Error(TASK_ERRORS.DELETE_FAILED);
}
},
};
// /**
// * (サンプル,実際には不要)
// * タスク管理関連のAPI機能を提供するオブジェクト
// * タスクの取得、作成、更新、削除などの機能を含む
// */
// export const taskApi = {
// /**
// * 全タスクを取得
// * @returns タスク一覧
// */
// getTasks: async (): Promise<Task[]> => {
// const response = await fetch(`${API_BASE_URL}/api/tasks`, {
// headers: getHeaders(), // 認証トークンを含むヘッダー
// });
// if (!response.ok) {
// throw new Error(TASK_ERRORS.FETCH_FAILED);
// }
// return response.json();
// },
// /**
// * 指定IDのタスクを取得
// * @param id タスクID
// * @returns 単一のタスク情報
// */
// getTask: async (id: number): Promise<Task> => {
// const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
// headers: getHeaders(),
// });
// if (!response.ok) {
// throw new Error(TASK_ERRORS.FETCH_FAILED);
// }
// return response.json();
// },
// /**
// * 新規材料を作成
// * @param task 作成するタスク情報(価格,作成日時、更新日時は除外)
// * @returns 作成されたタスク情報
// */
// addStuff: async (task: Omit<Task, 'userId' | 'createdAt' | 'price' | 'buyDate' | 'expirationDate' | 'newAddition'>): Promise<Task> => {
// const response = await fetch(`${API_BASE_URL}/api/tubuy/add`, {
// method: 'POST',
// headers: getHeaders(),
// body: JSON.stringify(task),
// });
// if (!response.ok) {
// throw new Error(TASK_ERRORS.CREATE_FAILED);
// }
// return response.json();
// },
// /**
// * タスクを更新
// * @param id 更新対象のタスクID
// * @param task 更新するタスク情報(部分的な更新も可能)
// * @returns 更新後のタスク情報
// */
// updateTask: async (id: number, task: Partial<Task>): Promise<Task> => {
// const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
// method: 'PUT',
// headers: getHeaders(),
// body: JSON.stringify(task),
// });
// if (!response.ok) {
// throw new Error(TASK_ERRORS.UPDATE_FAILED);
// }
// return response.json();
// },
// /**
// * タスクを削除
// * @param id 削除対象のタスクID
// */
// deleteTask: async (id: number): Promise<void> => {
// const response = await fetch(`${API_BASE_URL}/api/tasks/${id}`, {
// method: 'DELETE',
// headers: getHeaders(),
// });
// if (!response.ok) {
// throw new Error(TASK_ERRORS.DELETE_FAILED);
// }
// },
// };

@ -1,21 +1,21 @@
/**
*
*
*/
export interface Task {
id: number; // タスクの一意識別子
stuffName: string; // タスクのタイトル
amount: number; //材料の数量
price: number; //材料の値段
buyDate:Date; //購入日時
expirationDate: Date; //賞味・消費期限
//description?: string; // タスクの詳細説明(任意)
completed: boolean; // タスクの完了状態
userId: number; // タスクの所有者ID
createdAt: string; // タスク作成日時
newAddition: boolean //材料を新規追加するかどうか
//updatedAt: string; // タスク更新日時
}
// /**
// * タスク情報を表す型定義
// * タスクの基本情報と状態を管理
// */
// export interface Task {
// id: number; // タスクの一意識別子
// stuffName: string; // タスクのタイトル
// amount: number; //材料の数量
// price: number; //材料の値段
// buyDate:Date; //購入日時
// expirationDate: Date; //賞味・消費期限
// //description?: string; // タスクの詳細説明(任意)
// completed: boolean; // タスクの完了状態
// userId: number; // タスクの所有者ID
// createdAt: string; // タスク作成日時
// newAddition: boolean //材料を新規追加するかどうか
// //updatedAt: string; // タスク更新日時
// }
/**
*

Loading…
Cancel
Save