### 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
This component only renders on the client.
```
--------------------------------
### 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