All files / src/handlers foodlog.ts

97.61% Statements 41/42
96% Branches 24/25
100% Functions 2/2
97.61% Lines 41/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142                                              1x             11x 2x       9x     9x 8x   8x 8x 1x         7x 7x   7x               7x 1x 1x           6x       7x 7x 1x     6x                 1x   14x 1x       13x 13x 13x     13x 1x 1x     12x   12x 11x       6x   6x         2x         4x           3x         3x     1x   9x 9x      
import { HttpFunction } from "@google-cloud/functions-framework";
import { CreateFoodLogRequest } from "@smart-food-logger/shared";
 
import {
  getTokensFromFirestore,
  verifyFirebaseIdToken,
} from "../repositories/firebaseRepository.js";
import {
  processAndLogFoods,
  refreshFitbitAccessToken,
} from "../services/fitbitService.js";
import {
  AuthenticationError,
  FitbitApiError,
  handleError,
  MethodNotAllowedError,
  ValidationError,
} from "../utils/errors.js";
 
/**
 * トークンを検証し、Fitbitアクセストークンを取得するヘルパー関数。
 * 必要に応じてトークンをリフレッシュします。
 */
const verifyAndGetFitbitToken = async (
  authHeader: string | undefined,
): Promise<{
  accessToken: string;
  fitbitUserId: string;
  firebaseUid: string;
}> => {
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    throw new AuthenticationError(
      "Unauthorized: Authorization header is missing or invalid.",
    );
  }
  const idToken = authHeader.split("Bearer ")[1];
 
  // IDトークンを検証してFirebase UIDを取得
  const decodedToken = await verifyFirebaseIdToken(idToken);
  const firebaseUid = decodedToken.uid;
 
  const tokens = await getTokensFromFirestore(firebaseUid);
  if (!tokens) {
    throw new AuthenticationError(
      `No tokens found for user ${firebaseUid}. Please complete the OAuth flow.`,
    );
  }
 
  const clientId = process.env.FITBIT_CLIENT_ID;
  const clientSecret = process.env.FITBIT_CLIENT_SECRET;
 
  Iif (!clientId || !clientSecret) {
    throw new Error(
      "FITBIT_CLIENT_ID and FITBIT_CLIENT_SECRET environment variables must be set",
    );
  }
 
  let accessToken;
  // トークンの有効期限が切れているかチェックし、必要であればリフレッシュ
  if (new Date().getTime() >= tokens.expiresAt) {
    console.log(`Token for user ${firebaseUid} has expired. Refreshing...`);
    accessToken = await refreshFitbitAccessToken(
      firebaseUid,
      clientId,
      clientSecret,
    );
  } else {
    accessToken = tokens.accessToken;
  }
 
  // FirestoreからFitbitユーザーIDを使用
  const fitbitUserId = tokens.fitbitUserId;
  if (!fitbitUserId) {
    throw new FitbitApiError("Fitbit user ID not found in the database.", 500);
  }
 
  return { accessToken, fitbitUserId, firebaseUid };
};
 
/**
 * 食事ログの記録リクエストを処理する Cloud Function。
 *
 * @param req Express互換のリクエストオブジェクト
 * @param res Express互換のレスポンスオブジェクト
 */
export const foodLogHandler: HttpFunction = async (req, res) => {
  // 必要な環境変数のチェック
  if (!process.env.FITBIT_REDIRECT_URI) {
    throw new Error("FITBIT_REDIRECT_URI 環境変数が設定されていません。");
  }
 
  // CORSプリフライトリクエストに対応するためのヘッダーを設定
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
 
  // OPTIONSメソッドはCORSプリフライトリクエスト。ヘッダーを付与して204で即時終了する。
  if (req.method === "OPTIONS") {
    res.status(204).send("");
    return;
  }
 
  try {
    // メインロジック: 食事ログのリクエストを処理 (認証が必要)
    if (req.method === "POST") {
      const { accessToken, fitbitUserId } = await verifyAndGetFitbitToken(
        req.headers.authorization,
      );
 
      const nutritionData = req.body as CreateFoodLogRequest;
 
      if (
        !nutritionData ||
        !nutritionData.foods ||
        !Array.isArray(nutritionData.foods)
      ) {
        throw new ValidationError(
          'Invalid JSON body. Required: a non-empty "foods" array.',
        );
      }
 
      const fitbitResponses = await processAndLogFoods(
        accessToken,
        nutritionData,
        fitbitUserId,
      );
 
      res.status(200).json({
        message: "All foods logged successfully to Fitbit.",
        loggedData: nutritionData,
        fitbitResponses: fitbitResponses,
      });
      return;
    }
 
    throw new MethodNotAllowedError("Method Not Allowed");
  } catch (error: any) {
    handleError(res, error);
    return;
  }
};