Compare commits

...

4 Commits

@ -15,7 +15,7 @@ mongoose.connect(MONGODB_URI, {
const exerciseLogsSchema = new mongoose.Schema({
username: { type: String, required: true },
logs: [
log: [
{
description: { type: String, required: true },
duration: { type: Number, required: true },
@ -65,12 +65,7 @@ app.get("/api/users", (req, res) => {
});
});
app.post("/api/users/:_id/exercises", (req, res) => {
const _id = req.params._id;
const description = req.body.description;
const duration = req.body.duration;
let date = req.body.date;
const getDateInTicks = (date) => {
// current time in tick if no date specified
if (!date) date = new Date().getTime();
// Convert String to Number if date specified in ticks
@ -78,6 +73,15 @@ app.post("/api/users/:_id/exercises", (req, res) => {
// get date ticks from ticks Number or date String
date = new Date(date).getTime();
// date will be NaN if invalid date String is provided
return date;
};
app.post("/api/users/:_id/exercises", (req, res) => {
const _id = req.params._id;
const description = req.body.description;
const duration = req.body.duration;
let date = getDateInTicks(req.body.date);
if (Number.isNaN(Number(date))) {
res.status(400);
return res.json({ error: `Input date: '${req.body.date}' is not valid` });
@ -92,7 +96,7 @@ app.post("/api/users/:_id/exercises", (req, res) => {
{ _id: _id },
{
$push: {
logs: {
log: {
description: description,
duration: duration,
date: date,
@ -135,14 +139,44 @@ app.post("/api/users/:_id/exercises", (req, res) => {
app.get("/api/users/:_id/logs", (req, res) => {
const _id = req.params._id;
const limit = req.query.limit
? Math.trunc(Number(req.query.limit))
: Number.MAX_SAFE_INTEGER;
if (Number.isNaN(limit)) {
res.status(400);
return res.json({
error: `Query key 'limit''s value '${req.query.limit}' is not a number`,
});
}
const from = req.query.from ? getDateInTicks(req.query.from) : 0;
if (Number.isNaN(from)) {
res.status(400);
return res.json({
error: `Query key 'from''s value '${req.query.from}' is invalid for date`,
});
}
const to = req.query.to
? getDateInTicks(req.query.to)
: Number.MAX_SAFE_INTEGER;
if (Number.isNaN(to)) {
res.status(400);
return res.json({
error: `Query key 'to''s value '${req.query.to}' is invalid for date`,
});
}
exerciseLogs
.findById(_id)
.select({ "logs._id": false })
.select({ "log._id": false, __v: false })
.then((excLogs) => {
if (excLogs) {
let excLogsJson = excLogs.toJSON();
excLogsJson.count = excLogsJson.logs.length;
excLogsJson.logs = excLogsJson.logs.map((log) => {
excLogsJson.log = excLogsJson.log.filter(
(log) => log.date >= from && log.date <= to
);
excLogsJson.log.sort((a, b) => a.date - b.date);
excLogsJson.log = excLogsJson.log.slice(0, limit);
excLogsJson.count = excLogsJson.log.length;
excLogsJson.log = excLogsJson.log.map((log) => {
log.date = new Date(log.date).toDateString();
return log;
});

Loading…
Cancel
Save