Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Retrieve health data from Google Fit REST API every 10 seconds

I'm new to Node.js and I'm going to implement Google Fit REST API to my Node.js project and I wish to make it to update health data every 5 seconds (refer to const aggregated_data)

Here is my .get() method:

app.get("/starter", async (req, res) => {
  const patientID = req.query.id;

  /**
   * If user record exists. Proceed without reuqesting authorisation again
   */
    if (db.find((item) => item.id === patientID)) {
      const user = db.find((item) => item.id === patientID);
      let tokens = user.tokens;

      let healthDataArray = [];
      let allSessions = [];

      console.log("isTokenExpired :>> ", isTokenExpired(tokens.tokens));
      console.log("Now is ", Date.now());
      
      if (isTokenExpired(tokens.tokens)) {
        const result = await axios({
          method: "POST",
          url: "https://oauth2.googleapis.com/token", "Content-Type": "application/x-www-form-urlencoded",
          data: {
            client_id: process.env.CLIENT_ID,
            client_secret: process.env.CLIENT_SECRET,
            refresh_token: tokens.tokens.refresh_token,
            grant_type: "refresh_token",
          },
        });

        console.log("Updated Token :>> ", result.data);
        const patient_index = db.findIndex((item) => item.id === patientID);

        let updated_patient_token = db[patient_index];

        updated_patient_token.tokens.tokens.access_token = result.data.access_token;
        updated_patient_token.tokens.tokens.expiry_date = Date.now() + result.data.expires_in * 1000;
        updated_patient_token.tokens.tokens.scope = result.data.scope;
        updated_patient_token.tokens.tokens.token_type = result.data.token_type;

        console.log("Not-updated Database Token :>> ", tokens.tokens);

        db[patient_index] = updated_patient_token;
        tokens = db[patient_index];

        console.log("Updated Database Token :>> ", tokens.tokens);
      }

      try {
        const result = await axios({
          method: "POST",
          headers: {
            authorization: "Bearer " + tokens.tokens.access_token,
          },
          "Content-Type": "application/json",
          url: `https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate`,
          data: {
            aggregateBy: [
              {
                dataTypeName: "com.google.step_count.delta",
                dataSourceId: "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps",
              },
              {
                dataTypeName: "com.google.calories.expended",
                dataSourceId: "derived:com.google.calories.expended:com.google.android.gms:merge_calories_expended",
              },
              {
                dataTypeName: "com.google.heart_minutes",
                dataSourceId: "derived:com.google.heart_minutes:com.google.android.gms:from_steps<-estimated_steps",
              },
            ],
            bucketByTime: { durationMillis: 86400000 },
            startTimeMillis: Date.now() - 30 * 86400000,
            endTimeMillis: Date.now(),
          },
        });

        const sessions = await axios({
          method: "GET",
          headers: {
            authorization: "Bearer " + tokens.tokens.access_token,
          },
          "Content-Type": "application/json",
          url: `https://fitness.googleapis.com/fitness/v1/users/me/sessions`,
        });

        healthDataArray = result.data.bucket;
        allSessions = sessions.data.session;

      }catch (error) {
        console.log("error :>> ", error.response);
      }

       const aggregated_data = {
          non_session: healthDataArray,
          session: allSessions,
        };
        console.log("New data fetched");
        return res.json(aggregated_data);
      }catch(error1){
        console.log("error fetch new data :>> ", error1.response);
      }
    }else {
      res.cookie("id", patientID).redirect("http://localhost:5000/auth");
    }
});

My task is to use Cron Job to loop this method (which getting and posting the user's health data) once I getting into http://localhost:{PORT}/starter but I don't know how to call it into my cron.schedule and run correctly. Anyone can help?

question from:https://stackoverflow.com/questions/65856658/retrieve-health-data-from-google-fit-rest-api-every-10-seconds

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...