iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
Mobile Development

開除老闆計劃系列 第 15

[Day-15] 後端與資料庫設計 – 運動紀錄 Schema 與 API

  • 分享至 

  • xImage
  •  

昨天在前端把運動紀錄的體驗做了優化,包含日曆、快速自訂動作、重量輸入的計算機。今天要把這些功能「落地」到後端,才能真正把資料存起來,未來還能做分析。

為什麼要先設計資料結構?

對健身紀錄來說,資料不只是「今天做了幾下 bench press」,而是要能支援未來的各種分析:

  • 單次訓練細節(set × reps × weight)
  • 長期進步曲線(1RM、總量、訓練頻率)
  • 類別分析(重量訓練、有氧、伸展)

所以資料結構必須 既能記錄細節,又能彈性擴充


MongoDB Schema 設計

我這邊用 Mongoose 來舉例:

// workout-log.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

@Schema({ timestamps: true })
export class WorkoutLog extends Document {
  @Prop({ type: Types.ObjectId, ref: 'User', required: true })
  userId: Types.ObjectId;

  @Prop({ type: String, required: true })
  exerciseName: string; // e.g. Bench Press, Squat

  @Prop({ type: String, enum: ['strength', 'cardio', 'stretch'], required: true })
  category: string;

  @Prop([
    {
      set: { type: Number, required: true },
      reps: { type: Number, required: true },
      weight: { type: Number }, // 可選,跑步就不需要
      note: { type: String },
    },
  ])
  sets: {
    set: number;
    reps: number;
    weight?: number;
    note?: string;
  }[];

  @Prop({ type: Date, required: true })
  date: Date;
}

export const WorkoutLogSchema = SchemaFactory.createForClass(WorkoutLog);

👉 這樣的設計,一筆紀錄可以包含多組 set/reps,非常貼近實際健身的紀錄方式。


API 設計

1. 建立運動紀錄

POST /workouts
Content-Type: application/json

{
  "exerciseName": "Bench Press",
  "category": "strength",
  "sets": [
    { "set": 1, "reps": 10, "weight": 60 },
    { "set": 2, "reps": 8, "weight": 65 }
  ],
  "date": "2025-09-28"
}

2. 取得某天紀錄

GET /workouts?date=2025-09-28

3. 取得某位使用者的歷史紀錄

GET /workouts/user/:userId

4. 更新某筆紀錄

PATCH /workouts/:id

5. 刪除紀錄

DELETE /workouts/:id

資料流程圖

flowchart LR
    A[使用者輸入紀錄] --> B[前端 UI]
    B --> C[呼叫 API /workouts]
    C --> D[後端 Controller]
    D --> E[Service 處理邏輯]
    E --> F[(MongoDB)]
    F --> E
    E --> D
    D --> C
    C --> B
    B --> A

延伸思考

  • 計算 1RM
    可以在後端加一個 util function,根據不同公式(Epley、Brzycki)自動推算。
  • 分析報表
    例如:某段時間內總重量、訓練頻率,甚至能用來提醒「你已經 7 天沒練胸了」。
  • 社交或遊戲化
    未來可以加「排行榜」、「挑戰任務」,用這些紀錄直接做出有趣的功能。

心得

前端的 UI 只是「輸入器」,真正有價值的是背後的資料。
今天的 Schema + API 設計就是這個系統的基礎,未來無論要做 AI 分析、進度追蹤或排行榜,都是靠這些紀錄才能實現。


上一篇
Day-14 賺錢的方法
下一篇
[Day-16] 遇到 AI 鬼打牆該怎辦?程式開發心得
系列文
開除老闆計劃21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言