### Start Development Server with pnpm Source: https://github.com/hengnix/health-management/blob/main/README.md Starts the Nuxt development server for local development. Configuration can be done via environment variables (refer to .env.example). The application will be accessible at http://localhost:3000. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/hengnix/health-management/blob/main/README.md Installs project dependencies using the pnpm package manager. Ensure Node.js and pnpm are installed and meet the required versions before running. ```bash pnpm install ``` -------------------------------- ### Authentication Middleware in Nuxt Source: https://github.com/hengnix/health-management/blob/main/README.md An example of an authentication middleware in Nuxt. This middleware can be used to protect routes by checking authentication status before navigating. ```typescript // Middleware to check authentication status // Example: navigateTo('/login') if not authenticated // export default defineNuxtRouteMiddleware((to, from) => { // const auth = useAuth(); // Assuming a composable for auth // if (!auth.isLoggedIn.value && to.path !== '/login') { // return navigateTo('/login'); // } // }); ``` -------------------------------- ### Date Utilities with @internationalized/date Source: https://context7.com/hengnix/health-management/llms.txt TypeScript examples demonstrating the use of date utility functions, likely from a library like @internationalized/date. Functions include getting the current date, converting between DateValue objects and strings, creating specific dates, formatting dates for display and short formats, and checking if a date is the current day. ```typescript import { getTodayDateValue, dateValueToString, stringToDateValue, createCalendarDate, formatDisplayDate, formatShortDate, isTodayDateValue } from '~/utils/dateUtils' // Get today's date in local timezone const today = getTodayDateValue() console.log(today) // CalendarDate { year: 2025, month: 10, day: 22 } // Convert DateValue to string (YYYY-MM-DD) const dateStr = dateValueToString(today) console.log(dateStr) // "2025-10-22" // Convert string to DateValue const dateValue = stringToDateValue('2025-10-22') // Create specific date const customDate = createCalendarDate(2025, 10, 22) // Format for display (中文) const display = formatDisplayDate(today) console.log(display) // "2025 年 10 月 22 日" const displayFromStr = formatDisplayDate('2025-10-22') console.log(displayFromStr) // "2025/10/22" (localized) // Format short date (MM/DD) const shortDate = formatShortDate(today) console.log(shortDate) // "10/22" // Check if date is today const isToday = isTodayDateValue(dateValue) console.log(isToday) // true or false ``` -------------------------------- ### Client-Side Only Component Example Source: https://github.com/hengnix/health-management/blob/main/README.md Defines a Nuxt component that is exclusively rendered on the client-side. Files with the `.client.vue` suffix are automatically treated as client-only components. ```vue ``` -------------------------------- ### Streaming AI Chat with Server-Sent Events (SSE) Source: https://context7.com/hengnix/health-management/llms.txt TypeScript code demonstrating how to interact with an AI chat API using Server-Sent Events (SSE). It shows how to send messages, process streaming responses chunk by chunk, handle completion, and cancel the stream. It also includes an example using EventSource for GET-based SSE. ```typescript import { ssePost } from '~/utils/sse' // Setup abort controller for cancellation const abortController = new AbortController() const messages = ref>([]) // Send chat message with streaming response try { const stream = await ssePost<{ content: string; done?: boolean }>( '/api/ai/chat', { params: { messages: messages.value, question: '如何科学减肥?' }, signal: abortController.signal } ) let responseContent = '' // Process streaming chunks for await (const chunk of stream) { if (chunk.done) { // Stream completed messages.value.push({ role: 'assistant', content: responseContent }) break } // Append chunk content responseContent += chunk.content console.log('Received:', chunk.content) } } catch (error) { if (error.message === 'Aborted') { console.log('Stream cancelled by user') } else { console.error('Chat error:', error) } } // Cancel streaming function cancelStream() { abortController.abort() } // Alternative: GET-based SSE with EventSource import { sse } from '~/utils/sse' const getStream = await sse<{ content: string }>( '/api/ai/stream', { params: { query: 'health tips' }, signal: abortController.signal } ) for await (const data of getStream) { console.log(data.content) } ``` -------------------------------- ### Preview Production Version with pnpm Source: https://github.com/hengnix/health-management/blob/main/README.md Previews the production build locally. This command is useful for testing the built application before deploying it to a live environment. ```bash pnpm preview ``` -------------------------------- ### Exercise Tracking API Operations (Create & Query) Source: https://context7.com/hengnix/health-management/llms.txt Demonstrates cURL commands for the exercise tracking API. Includes creating new exercise records with details like duration and calories burned, and querying exercise history with date filters. Requires authentication and specifies JSON content type for requests. ```bash curl -X POST http://localhost:8080/exercise-items \ -H "Authorization: Bearer ${TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "userID": "123e4567-e89b-12d3-a456-426614174000", "exerciseType": "跑步", "durationMinutes": 30, "estimatedCaloriesBurned": 300, "recordDate": "2025-10-22" }' ``` ```bash curl -X GET "http://localhost:8080/exercise-items?page=1&pageSize=10&userID=123e4567-e89b-12d3-a456-426614174000&startDate=2025-10-21&endDate=2025-10-22" \ -H "Authorization: Bearer ${TOKEN}" ``` -------------------------------- ### Build Production Version with pnpm Source: https://github.com/hengnix/health-management/blob/main/README.md Builds the production-ready version of the Nuxt application. This command generates optimized static assets and server code for deployment. ```bash pnpm build ``` -------------------------------- ### Nuxt Composables for State Management Source: https://github.com/hengnix/health-management/blob/main/README.md Demonstrates the use of Nuxt 4's native composables for state management, including `useState` for SSR-friendly state and `useCookie` for cookie management. `readonly()` is used for state protection. ```typescript // Example usage in a component or composable: // import { useState, useCookie, readonly } from '#imports'; // const count = useState('counter', () => 0); // const userToken = useCookie('auth_token'); // const readOnlyCount = readonly(count); ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/hengnix/health-management/blob/main/README.md Automatically formats the code using Prettier according to the defined style. This command ensures consistent code formatting across the project. ```bash pnpm format:fix ``` -------------------------------- ### Diet Management API Operations (CRUD & Query) Source: https://context7.com/hengnix/health-management/llms.txt Provides cURL commands for interacting with the diet management API. Supports querying with filters, retrieving single records, updating existing records, and deleting records. Requires authentication via a bearer token. ```bash curl -X GET "http://localhost:8080/diet-items?page=1&pageSize=10&userID=123e4567-e89b-12d3-a456-426614174000&mealType=早餐&startDate=2025-10-21&endDate=2025-10-22" \ -H "Authorization: Bearer ${TOKEN}" ``` ```bash curl -X GET http://localhost:8080/diet-items/1 \ -H "Authorization: Bearer ${TOKEN}" ``` ```bash curl -X PUT http://localhost:8080/diet-items/1 \ -H "Authorization: Bearer ${TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "午餐", "foodName": "更新后的食物", "estimatedCalories": 500, "recordDate": "2025-10-22" }' ``` ```bash curl -X DELETE http://localhost:8080/diet-items/1 \ -H "Authorization: Bearer ${TOKEN}" ``` -------------------------------- ### Lint Code with ESLint Source: https://github.com/hengnix/health-management/blob/main/README.md Runs ESLint to check code for style and potential errors according to the configured rules. This command helps maintain code quality and consistency. ```bash pnpm lint ``` -------------------------------- ### Diet Tracking API Management (cURL) Source: https://context7.com/hengnix/health-management/llms.txt Contains cURL commands for managing diet records, including creating entries for meals (breakfast, lunch, dinner, snacks) with calorie estimations and specifying the record date. Requires JWT authentication. ```bash # Create diet record curl -X POST http://localhost:8080/diet-items \ -H "Authorization: Bearer ${TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "午餐", "foodName": "鸡胸肉沙拉", "estimatedCalories": 450, "recordDate": "2025-10-22" }' # Response { "code": 1, "data": { "dietItemID": 1, "userID": "123e4567-e89b-12d3-a456-426614174000", "recordDate": "2025-10-22", "foodName": "鸡胸肉沙拉", "mealType": "午餐", "estimatedCalories": 450, "createdAt": "2025-10-22T12:30:00Z" } } ``` -------------------------------- ### Date Utilities Source: https://context7.com/hengnix/health-management/llms.txt Helper functions for working with DateValue objects, including creation, formatting, and comparison. ```APIDOC ## Date Utilities ### Description Provides a set of utility functions for manipulating and formatting dates using the `@internationalized/date` library, with timezone support. ### Functions - **getTodayDateValue()** - **Description**: Gets today's date in the local timezone as a `CalendarDate` object. - **Returns**: `CalendarDate` - **dateValueToString(dateValue: CalendarDate): string** - **Description**: Converts a `CalendarDate` object to a string in 'YYYY-MM-DD' format. - **Parameters**: - **dateValue** (CalendarDate) - The date value to convert. - **Returns**: `string` - **stringToDateValue(dateString: string): CalendarDate** - **Description**: Converts a date string ('YYYY-MM-DD') to a `CalendarDate` object. - **Parameters**: - **dateString** (string) - The date string to convert. - **Returns**: `CalendarDate` - **createCalendarDate(year: number, month: number, day: number): CalendarDate** - **Description**: Creates a specific `CalendarDate` object. - **Parameters**: - **year** (number) - The year. - **month** (number) - The month (1-12). - **day** (number) - The day. - **Returns**: `CalendarDate` - **formatDisplayDate(dateValue: CalendarDate | string): string** - **Description**: Formats a date for display according to the user's locale. - **Parameters**: - **dateValue** (CalendarDate | string) - The date value or string to format. - **Returns**: `string` - **formatShortDate(dateValue: CalendarDate): string** - **Description**: Formats a date to a short representation (e.g., 'MM/DD'). - **Parameters**: - **dateValue** (CalendarDate) - The date value to format. - **Returns**: `string` - **isTodayDateValue(dateValue: CalendarDate): boolean** - **Description**: Checks if a given `CalendarDate` object represents today's date. - **Parameters**: - **dateValue** (CalendarDate) - The date value to check. - **Returns**: `boolean` ### Usage Example ```typescript import { getTodayDateValue, dateValueToString, stringToDateValue, createCalendarDate, formatDisplayDate, formatShortDate, isTodayDateValue } from '~/utils/dateUtils'; // Get today's date const today = getTodayDateValue(); console.log(today); // Example: CalendarDate { year: 2025, month: 10, day: 22 } // Convert to string const dateStr = dateValueToString(today); console.log(dateStr); // "2025-10-22" // Convert string to DateValue const dateValue = stringToDateValue('2025-10-22'); // Create a specific date const customDate = createCalendarDate(2025, 10, 22); // Format for display (locale-dependent) const display = formatDisplayDate(today); console.log(display); // Example (en-US): "10/22/2025", (zh-CN): "2025年10月22日" // Format short date const shortDate = formatShortDate(today); console.log(shortDate); // "10/22" // Check if it's today const isToday = isTodayDateValue(dateValue); console.log(isToday); // true or false ``` ``` -------------------------------- ### Exercise Tracking API Source: https://context7.com/hengnix/health-management/llms.txt Endpoints for logging and querying exercise activities, including creating new records and retrieving historical data. ```APIDOC ## POST /exercise-items ### Description Logs a new exercise activity. ### Method POST ### Endpoint /exercise-items ### Parameters #### Request Body - **userID** (string) - Required - The UUID of the user. - **exerciseType** (string) - Required - The type of exercise (e.g., "跑步", "游泳"). - **durationMinutes** (integer) - Required - The duration of the exercise in minutes. - **estimatedCaloriesBurned** (integer) - Required - The estimated calories burned. - **recordDate** (string) - Required - The date the exercise was performed (YYYY-MM-DD). ### Request Example { "userID": "123e4567-e89b-12d3-a456-426614174000", "exerciseType": "跑步", "durationMinutes": 30, "estimatedCaloriesBurned": 300, "recordDate": "2025-10-22" } ### Response #### Success Response (200) - **Created Exercise Item** (object) - The details of the newly created exercise record. #### Response Example { "code": 1, "data": { "exerciseItemID": 1, "userID": "123e4567-e89b-12d3-a456-426614174000", "exerciseType": "跑步", "durationMinutes": 30, "estimatedCaloriesBurned": 300, "recordDate": "2025-10-22T00:00:00Z", "createdAt": "2025-10-22T18:00:00Z" } } ## GET /exercise-items ### Description Queries exercise records with optional filtering by user and date range. ### Method GET ### Endpoint /exercise-items ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **pageSize** (integer) - Optional - The number of items per page. - **userID** (string) - Optional - The UUID of the user. - **startDate** (string) - Optional - The start date for the filter (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for the filter (YYYY-MM-DD). ### Response #### Success Response (200) - **Array of Exercise Items** (object) - A list of exercise records matching the query. #### Response Example { "items": [ { "exerciseItemID": 1, "userID": "123e4567-e89b-12d3-a456-426614174000", "exerciseType": "跑步", "durationMinutes": 30, "estimatedCaloriesBurned": 300, "recordDate": "2025-10-22T00:00:00Z", "createdAt": "2025-10-22T18:00:00Z" } ], "totalItems": 5, "currentPage": 1, "pageSize": 10 } ``` -------------------------------- ### User Authentication with JWT Tokens (TypeScript) Source: https://context7.com/hengnix/health-management/llms.txt Handles user login, registration, profile management, and logout using JWT tokens stored in secure HTTP cookies. It leverages composables for state management and provides automatic token refresh and route protection. ```typescript import { useAuth } from '~/composables/useAuth' const auth = useAuth() const loginData = { email: 'user@example.com', password: 'securepassword123' } const success = await auth.login(loginData) if (success) { // Automatically redirects to dashboard // Token stored in HttpOnly cookie (7 days expiry) console.log('User:', auth.user.value) console.log('Is logged in:', auth.isLoggedIn.value) } // Register new user const registerData = { email: 'newuser@example.com', password: 'securepassword123', nickname: 'John Doe', gender: '男', dateOfBirth: '1990-01-15' } const registered = await auth.register(registerData) // Fetch user profile await auth.fetchUserProfile() // Update user profile const updated = await auth.updateProfile({ nickname: 'Jane Doe', gender: '女' }) // Logout auth.logout() ``` -------------------------------- ### Integrate ECharts for Weight Trend Visualization Source: https://context7.com/hengnix/health-management/llms.txt This TypeScript code integrates ECharts for creating interactive charts, specifically a weight trend visualization. It uses a composable for initialization and disposal, handles chart options, and manages responsive resizing. The component is marked as client-only. ```typescript import { useECharts } from '~/composables/useECharts' const { initChart, disposeChart } = useECharts() // In component const chartContainer = ref() let chartInstance = null onMounted(() => { if (!chartContainer.value) return // Initialize chart chartInstance = initChart(chartContainer.value) // Configure chart chartInstance.setOption({ title: { text: 'Weight Trend' }, tooltip: { trigger: 'axis', formatter: '{b}: {c} kg' }, xAxis: { type: 'category', data: ['10/15', '10/16', '10/17', '10/18', '10/19'] }, yAxis: { type: 'value', name: 'Weight (kg)' }, series: [{ name: 'Weight', type: 'line', smooth: true, data: [70.5, 70.2, 69.8, 69.5, 69.3] }] }) // Responsive resize window.addEventListener('resize', handleResize) }) function handleResize() { chartInstance?.resize() } onBeforeUnmount(() => { window.removeEventListener('resize', handleResize) disposeChart(chartInstance) chartInstance = null }) // Client-only component with hydration strategy // File: CaloriesChart.client.vue // Automatically client-side only due to .client.vue suffix ``` -------------------------------- ### AI Chat API Source: https://context7.com/hengnix/health-management/llms.txt Provides real-time AI health consultations using Server-Sent Events (SSE) for streaming responses. ```APIDOC ## POST /api/ai/chat ### Description Sends a chat message to the AI and receives a streaming response. Uses SSE for real-time updates. ### Method POST ### Endpoint /api/ai/chat ### Parameters #### Request Body - **messages** (Array) - Required - An array of message objects, where each object has `role` (string) and `content` (string) properties. - **question** (string) - Required - The user's question for the AI. ### Request Example ```json { "messages": [ {"role": "user", "content": "What are the benefits of drinking water?"} ], "question": "What are the benefits of drinking water?" } ``` ### Response #### Success Response (200) - **Streaming Chunks** (object) - Server-Sent Events containing chunks of the AI's response. Each chunk has a `content` (string) and an optional `done` (boolean) property. #### Response Example (for each chunk) ```json { "content": "Drinking water is essential for...", "done": false } ``` ## GET /api/ai/stream ### Description An alternative endpoint for receiving streaming AI responses using SSE via `EventSource`. ### Method GET ### Endpoint /api/ai/stream ### Parameters #### Query Parameters - **query** (string) - Required - The query parameter for the AI stream. ### Response #### Success Response (200) - **Streaming Data** (object) - Server-Sent Events containing data from the AI stream. Each event has a `content` (string) property. #### Response Example (for each event) ```json { "content": "Here are some health tips..." } ``` ``` -------------------------------- ### Configure API Proxy in Nuxt Config Source: https://github.com/hengnix/health-management/blob/main/README.md Configures Vite's server proxy in the Nuxt configuration file (`nuxt.config.ts`) to forward API requests during development. This is enabled via environment variables like `ENABLE_API_PROXY` and `API_TARGET`. ```typescript vite: { server: { proxy: process.env.ENABLE_API_PROXY === 'true' ? { '/api': { target: process.env.API_TARGET || 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } : undefined } } ``` -------------------------------- ### Nuxt.js API Proxy Configuration (TypeScript) Source: https://context7.com/hengnix/health-management/llms.txt Configures the development proxy for API requests in a Nuxt.js application using Vite. It allows setting up a proxy to a backend API during development, with options to enable/disable and specify the target URL. Production deployment considerations for Nginx are also noted. ```typescript // nuxt.config.ts export default defineNuxtConfig({ runtimeConfig: { public: { apiBase: '/api' } }, vite: { server: { proxy: process.env.ENABLE_API_PROXY === 'true' ? { '/api': { target: process.env.API_TARGET || 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^/api/, ''), configure: (proxy) => { proxy.on('proxyReq', (proxyReq) => { proxyReq.setHeader('Accept-Encoding', 'identity') }) } } } : undefined } } }) ``` ```dotenv // .env configuration // ENABLE_API_PROXY=true // API_TARGET=http://localhost:8080 ``` ```javascript // Usage in application const config = useRuntimeConfig() const response = await $fetch(`${config.public.apiBase}/body-metrics`, { headers: { Authorization: `Bearer ${token.value}` } }) ``` ```nginx // Production deployment // Frontend served by Nginx, proxy to backend: // location /api { // proxy_pass http://backend:8080; // proxy_set_header Host $host; // proxy_set_header X-Real-IP $remote_addr; // } ``` -------------------------------- ### Check Code Formatting with Prettier Source: https://github.com/hengnix/health-management/blob/main/README.md Runs Prettier to check if the code is formatted according to the defined style. This command identifies files that do not adhere to the formatting rules. ```bash pnpm format ``` -------------------------------- ### Body Metrics API Management (cURL) Source: https://context7.com/hengnix/health-management/llms.txt Provides cURL commands for interacting with the Body Metrics API. This includes creating, querying with pagination, updating, and deleting body measurement records. Requires JWT authentication. ```bash # Create body metric record curl -X POST http://localhost:8080/body-metrics \ -H "Authorization: Bearer ${TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "userID": "123e4567-e89b-12d3-a456-426614174000", "heightCM": 175.5, "weightKG": 70.2, "recordDate": "2025-10-22" }' # Response { "code": 1, "data": { "bodyMetricID": 1, "userID": "123e4567-e89b-12d3-a456-426614174000", "heightCM": 175.5, "weightKG": 70.2, "bmi": 22.8, "recordDate": "2025-10-22", "createdAt": "2025-10-22T10:30:00Z" } } # Query with pagination curl -X GET "http://localhost:8080/body-metrics?page=1&pageSize=10&userID=123e4567-e89b-12d3-a456-426614174000" \ -H "Authorization: Bearer ${TOKEN}" # Update record curl -X PUT http://localhost:8080/body-metrics/1 \ -H "Authorization: Bearer ${TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "userID": "123e4567-e89b-12d3-a456-426614174000", "heightCM": 175.5, "weightKG": 69.8, "recordDate": "2025-10-22" }' # Delete record curl -X DELETE http://localhost:8080/body-metrics/1 \ -H "Authorization: Bearer ${TOKEN}" ``` -------------------------------- ### CSS Loading Spinner Animation Source: https://github.com/hengnix/health-management/blob/main/app/spa-loading-template.html This CSS code defines a reusable loading spinner animation using keyframes. It sets up styles for the spinner's size, border, and animation, and also includes styles for the surrounding text. The styles are designed to be responsive to color schemes. ```css *, ::before, ::after { box-sizing: border-box; border-width: 0; border-style: solid; } html { line-height: 1.5; -webkit-text-size-adjust: 100%; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; } body { margin: 0; line-height: inherit; } @media (prefers-color-scheme: light) { :root { --bg: #fff; --text: #18181b; --border: #e4e4e7; --ring: rgb(0 0 0/0.1); } } @media (prefers-color-scheme: dark) { :root { --bg: #18181b; --text: #fafafa; --border: #27272a; --ring: rgb(255 255 255/0.1); } } body { display: flex; align-items: center; justify-content: center; min-height: 100vh; background-color: var(--bg); color: var(--text); } .loader { text-align: center; } .spinner { width: 48px; height: 48px; border: 3px solid var(--border); border-top-color: var(--text); border-radius: 50%; animation: spin 0.8s linear infinite; margin: 0 auto 1rem; } @keyframes spin { to { transform: rotate(360deg); } } .text { font-size: 0.875rem; color: var(--text); opacity: 0.6; } ``` -------------------------------- ### Diet Items API Source: https://context7.com/hengnix/health-management/llms.txt Endpoints for managing diet items, including querying with filters, retrieving single records, updating records, and deleting records. ```APIDOC ## GET /diet-items ### Description Retrieves a list of diet items, with options to filter by user, date range, and meal type. ### Method GET ### Endpoint /diet-items ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **pageSize** (integer) - Optional - The number of items per page. - **userID** (string) - Optional - The UUID of the user. - **mealType** (string) - Optional - The type of meal (e.g., "早餐", "午餐", "晚餐", "加餐"). - **startDate** (string) - Optional - The start date for the filter (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for the filter (YYYY-MM-DD). ### Response #### Success Response (200) - **Array of Diet Items** (object) - Details of diet items matching the query. #### Response Example { "items": [ { "dietItemID": "some-uuid", "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "早餐", "foodName": "Oatmeal", "estimatedCalories": 350, "recordDate": "2025-10-21T00:00:00Z", "createdAt": "2025-10-21T08:00:00Z" } ], "totalItems": 10, "currentPage": 1, "pageSize": 10 } ## GET /diet-items/{id} ### Description Retrieves a single diet item by its ID. ### Method GET ### Endpoint /diet-items/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the diet item to retrieve. ### Response #### Success Response (200) - **Diet Item** (object) - The details of the requested diet item. #### Response Example { "dietItemID": "some-uuid", "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "早餐", "foodName": "Oatmeal", "estimatedCalories": 350, "recordDate": "2025-10-21T00:00:00Z", "createdAt": "2025-10-21T08:00:00Z" } ## PUT /diet-items/{id} ### Description Updates an existing diet item. ### Method PUT ### Endpoint /diet-items/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the diet item to update. #### Request Body - **userID** (string) - Required - The UUID of the user. - **mealType** (string) - Required - The type of meal (e.g., "早餐", "午餐", "晚餐", "加餐"). - **foodName** (string) - Required - The name of the food. - **estimatedCalories** (integer) - Required - The estimated calorie count. - **recordDate** (string) - Required - The date the meal was recorded (YYYY-MM-DD). ### Request Example { "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "午餐", "foodName": "Updated Salad", "estimatedCalories": 450, "recordDate": "2025-10-22" } ### Response #### Success Response (200) - **Updated Diet Item** (object) - The details of the updated diet item. #### Response Example { "dietItemID": "some-uuid", "userID": "123e4567-e89b-12d3-a456-426614174000", "mealType": "午餐", "foodName": "Updated Salad", "estimatedCalories": 450, "recordDate": "2025-10-22T00:00:00Z", "createdAt": "2025-10-22T12:30:00Z", "updatedAt": "2025-10-22T12:35:00Z" } ## DELETE /diet-items/{id} ### Description Deletes a diet item by its ID. ### Method DELETE ### Endpoint /diet-items/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the diet item to delete. ### Response #### Success Response (200) - **Message** (string) - Confirmation of deletion. #### Response Example { "message": "Diet item with ID 1 deleted successfully." } ``` -------------------------------- ### Fix Linting Errors with ESLint Source: https://github.com/hengnix/health-management/blob/main/README.md Automatically attempts to fix linting errors found by ESLint. This command helps enforce code style guidelines automatically. ```bash pnpm lint:fix ``` -------------------------------- ### Implement Authentication Middleware with JWT Source: https://context7.com/hengnix/health-management/llms.txt This TypeScript middleware protects routes by validating JWT tokens. It redirects unauthenticated users to the login page. Configuration options include setting a token cookie and an environment variable to skip authentication during development. ```typescript // middleware/auth.ts - automatically applied via Nuxt routing // Protected routes (require authentication): // /dashboard, /body-data, /diet, /exercise, /chat, /profile // Public routes (no authentication required): // /, /login, /register // Usage in page components definePageMeta({ middleware: 'auth' }) // Skip authentication check (for development) // Set environment variable: // SKIP_AUTH=true // In nuxt.config.ts runtimeConfig: { public: { SKIP_AUTH: process.env.SKIP_AUTH || 'false' } } // Cookie configuration const token = useCookie('token', { maxAge: 60 * 60 * 24 * 7, // 7 days sameSite: 'lax', secure: import.meta.env.PROD // HTTPS in production }) // Access token in middleware if (!token.value && !publicRoutes.includes(to.path)) { return navigateTo('/login') } ``` -------------------------------- ### BMI Calculation Utilities (TypeScript) Source: https://context7.com/hengnix/health-management/llms.txt Provides utility functions for calculating, formatting, and determining the health status of Body Mass Index (BMI). It handles raw calculation, string formatting, and categorization based on standard BMI ranges. ```typescript import { calcBMI, formatBMI, getBMIStatus } from '~/utils/metricUtils' const bodyData = { weightKG: 70.2, heightCM: 175.5 } // Calculate raw BMI const bmi = calcBMI(bodyData) console.log(bmi) // 22.791 // Get formatted BMI string const formatted = formatBMI(bodyData) console.log(formatted) // "22.8" // Get BMI health status const status = getBMIStatus(bmi) console.log(status) // { // status: '正常', // color: 'text-green-600' // } // BMI categories: // < 18.5: 偏瘦 (blue) // 18.5-24: 正常 (green) // 24-28: 偏胖 (yellow) // >= 28: 肥胖 (red) // Handle invalid data const invalid = calcBMI({ weightKG: 0, heightCM: 175 }) console.log(invalid) // null console.log(formatBMI({ weightKG: 0, heightCM: 175 })) // "--" ``` -------------------------------- ### Check TypeScript Types Source: https://github.com/hengnix/health-management/blob/main/README.md Runs the TypeScript compiler to check for type errors in the codebase. This command ensures type safety and helps catch potential bugs during development. ```bash pnpm typecheck ``` -------------------------------- ### Define TypeScript Types for API Entities Source: https://context7.com/hengnix/health-management/llms.txt Provides comprehensive TypeScript type definitions for various API entities including User, BodyData, DietRecord, and ExerciseRecord. It also includes types for API responses and errors, supporting backend field name variations. ```typescript // User types const user: User = { userID: '123e4567-e89b-12d3-a456-426614174000', email: 'user@example.com', nickname: 'John Doe', gender: '男', dateOfBirth: '1990-01-15', createdAt: '2025-01-01T00:00:00Z' } // Body data types const bodyData: BodyData = { bodyMetricID: 1, userID: '123e4567-e89b-12d3-a456-426614174000', heightCM: 175.5, weightKG: 70.2, bmi: 22.8, recordDate: '2025-10-22', createdAt: '2025-10-22T10:00:00Z' } // Diet record types const dietRecord: DietRecord = { dietItemID: 1, userID: '123e4567-e89b-12d3-a456-426614174000', recordDate: '2025-10-22', foodName: '鸡胸肉沙拉', mealType: '午餐', estimatedCalories: 450 } // Exercise record types const exerciseRecord: ExerciseRecord = { exerciseItemID: 1, userID: '123e4567-e89b-12d3-a456-426614174000', exerciseType: '跑步', durationMinutes: 30, estimatedCaloriesBurned: 300, recordDate: '2025-10-22' } // API response wrapper const apiResponse: ApiResponse = { success: true, data: bodyData, message: 'Success' } // API error handling const error: ApiError = { response: { status: 401, data: { message: 'Unauthorized', error: 'Invalid token' } }, message: 'Request failed' } // Statistics dashboard const stats: Statistics = { totalCaloriesConsumed: 2000, totalCaloriesBurned: 500, netCalories: 1500, averageWeight: 70.0, exerciseCount: 5, dietRecordCount: 12 } ``` -------------------------------- ### SSE Stream Request Utility Source: https://github.com/hengnix/health-management/blob/main/README.md A utility function (`sse.ts`) for handling Server-Sent Events (SSE) streams. This is typically used for real-time communication from the server, such as AI chat responses. ```typescript // Example of how sse.ts might be used: // import { streamSSE } from '~/utils/sse'; // async function fetchAiResponse(prompt: string) { // await streamSSE('/api/chat', { method: 'POST', body: JSON.stringify({ prompt }) }, (data) => { // // Process incoming data chunks // console.log('Received:', data); // }); // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.