require("dotenv").config();
const { validationResult } = require("express-validator/check");
const mongoose = require("mongoose");
const Profile = require("../models/profile");
const ClientId = process.env.CLIENTID;
const Secret = process.env.SECRET;
const Callback = process.env.CALLBACK;
//this is the empID you're getting from AHA
const empID = 7747;
//get today's date
let date_ob = new Date();
// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);
// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year
let year = date_ob.getFullYear();
// prints date in YYYY-MM-DD format
let today = year + "-" + month + "-" + date;
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
clientId: ClientId, //client_id
clientSecret: Secret, //client secret
apiVersion: "1.2" // 1.2 is the default
});
exports.getCallback = (req, res, next) => {
const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
const yesterday = yesterday_raw.toISOString().slice(0, 10);
client.getAccessToken(req.query.code, Callback).then(result => {
var requests = [
client.get("/profile.json", result.access_token), //0
client.get("/activities/date/today.json", result.access_token), //1
//client.get("/sleep/date/" + yesterday + ".json", result.access_token), //2
client.get("/sleep/date/today.json", result.access_token), //2
//client.get("/sleep/date/2019-11-05.json", result.access_token), //2
client.get(
"/foods/log/caloriesIn/date/today/1d.json",
result.access_token
), //dailly intake of calories 3
client.get("/foods/log/water/date/today.json", result.access_token), // 4 this works!
client.get("/activities/heart/date/today/1d.json", result.access_token), //5
client.get("/body/log/weight/goal.json", result.access_token, undefined, {
"Accept-Language": "en_US"
}), //6
client.get("/activities/date/" + yesterday + ".json", result.access_token) //7
];
Promise.all(requests)
.then(data => {
//profile info
const firstName = data[0][0].user.firstName; //0
const lastName = data[0][0].user.lastName; //0
const dateOfBirth = data[0][0].user.dateOfBirth; //0
const gender = data[0][0].user.gender; //0
//calorie goals - to be burned including BMR
const calories_goal = JSON.stringify(data[1][0]["goals"].calories); //1 calorie goal
const massive_total = JSON.stringify(data[1][0].summary.calories.total); //1 big calorie total
const BMR = JSON.stringify(data[1][0].summary.calories.bmr); //1 - BMR
const calories_burned = massive_total - BMR;
//sleep
const slumber = JSON.stringify(
data[2][0].summary.totalMinutesAsleep / 60
); //2 total sleep hours
const sleep = JSON.stringify(Math.round(slumber * 10) / 10);
const rem_sleep = data[2][0]["sleep"].length
? data[2][0]["summary"].stages.rem
: 0; //minutes in deep REM sleep
//nutrition
const eating = JSON.stringify(
data[3][0]["foods-log-caloriesIn"][0].value
); //3
const caloriesIn = eating.replace(/\"/g, "");
//water
const water = JSON.stringify(data[4][0].summary.water);
//heart rate
const rhr = JSON.stringify(
data[5][0]["activities-heart"][0].value.restingHeartRate
);
//body weight goal
//res.setHeader('Accept-Language', 'en_US')
const startWeight = JSON.stringify(data[6][0].goal.startWeight);
const targetWeight = JSON.stringify(data[6][0].goal.weight);
//res.send(targetWeight);
//steps
const totalStepsYesterday = JSON.stringify(data[7][0].summary.steps);
const totalStepsSoFar = JSON.stringify(data[1][0].summary.steps);
//console.log("here's where you're putting our INSERT code");
Profile.find({ empID: empID, todaysDate: today }).then(profile => {
if (profile) {
//console.log("someone's here");
profile.empID = empID;
profile.todaysDate = today;
profile.firstName = firstName;
profile.lastName = lastName;
profile.dateOfBirth = dateOfBirth;
profile.gender = gender;
profile.bodyStartWeight = startWeight;
profile.bodyTargetWeight = targetWeight;
profile.calorieGoal = calories_goal;
profile.caloriesConsumed = caloriesIn;
profile.caloriesBurned = calories_burned;
profile.waterConsumpution = water;
profile.BMR = BMR;
profile.totalHoursSlept = sleep;
profile.REM = rem_sleep;
profile.RHR = rhr;
profile.totalStepsYesterday = totalStepsYesterday;
profile.totalStepsSoFar = totalStepsSoFar;
return Profile.save()
.then(result => {
console.log("updated row");
})
.catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
} else {
const profile = new Profile({
empID: empID,
todaysDate: today,
firstName: firstName,
lastName: lastName,
dateOfBirth: dateOfBirth,
gender: gender,
bodyStartWeight: startWeight,
bodyTargetWeight: targetWeight,
calorieGoal: calories_goal,
caloriesConsumed: caloriesIn,
caloriesBurned: calories_burned,
waterConsumpution: water,
BMR: BMR,
totalHoursSlept: sleep,
REM: rem_sleep,
RHR: rhr,
totalStepsYesterday: totalStepsYesterday,
totalStepsSoFar: totalStepsSoFar
});
profile
.save()
.then(result => {
console.log("got it done");
res.redirect("/success");
})
.catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
}
});
}) // end of update or insert
.catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
});
};
exports.getSuccess = (req, res, next) => {
console.log("hello");
res.status(200).render("authorize/success", {
pageTitle: "Success",
path: "/success"
});
};
Profile.find({ empID: empID, todaysDate: today }).then(profile => {
if (profile) {
//console.log("someone's here");
profile.empID = empID;
profile.todaysDate = today;
profile.firstName = firstName;
profile.lastName = lastName;
profile.dateOfBirth = dateOfBirth;
profile.gender = gender;
profile.bodyStartWeight = startWeight;
profile.bodyTargetWeight = targetWeight;
profile.calorieGoal = calories_goal;
profile.caloriesConsumed = caloriesIn;
profile.caloriesBurned = calories_burned;
profile.waterConsumpution = water;
profile.BMR = BMR;
profile.totalHoursSlept = sleep;
profile.REM = rem_sleep;
profile.RHR = rhr;
profile.totalStepsYesterday = totalStepsYesterday;
profile.totalStepsSoFar = totalStepsSoFar;
return Profile.save()
.then(result => {
console.log("updated row");
})
Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.
When asked, what has been your best career decision?
Deciding to stick with EE.
Being involved with EE helped me to grow personally and professionally.
Connect with Certified Experts to gain insight and support on specific technology challenges including:
We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE