Added meal service

This commit is contained in:
= 2020-12-28 22:32:46 +01:00
parent 0674b1aa2c
commit cffb99ed7d
45 changed files with 288 additions and 1169 deletions

View File

@ -1,17 +0,0 @@
const roles = ['user', 'admin'];
const allRights = [
'getUsers', 'manageUsers',
'getActivities', 'manageActivities',
'getProfiles', 'manageProfiles',
'getUnits', 'manageUnits',
];
const roleRights = new Map();
roleRights.set(roles[0], allRights);
roleRights.set(roles[1], allRights);
module.exports = {
roles,
roleRights,
};

View File

@ -1,25 +0,0 @@
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { activityService } = require('../services');
const getActivities = catchAsync(async (req, res) => {
const filter = pick(req.query, ['name', 'factor']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await activityService.queryActivities(filter, options);
res.send(result);
});
const getActivity = catchAsync(async (req, res) => {
const activity = await activityService.getActivityById(req.params.activityId);
if (!activity) {
throw new ApiError(httpStatus.NOT_FOUND, 'Activity not found');
}
res.send(activity);
});
module.exports = {
getActivities,
getActivity,
};

View File

@ -1,25 +0,0 @@
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { genderService } = require('../services');
const getGenders = catchAsync(async (req, res) => {
const filter = pick(req.query, ['name']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await genderService.queryGenders(filter, options);
res.send(result);
});
const getGender = catchAsync(async (req, res) => {
const gender = await genderService.getGenderById(req.params.genderId);
if (!gender) {
throw new ApiError(httpStatus.NOT_FOUND, 'Activity not found');
}
res.send(gender);
});
module.exports = {
getGenders,
getGender,
};

View File

@ -1,25 +0,0 @@
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { goalService } = require('../services');
const getGoals = catchAsync(async (req, res) => {
const filter = pick(req.query, ['name', 'value']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await goalService.queryGoals(filter, options);
res.send(result);
});
const getGoal = catchAsync(async (req, res) => {
const goal = await goalService.getGoalById(req.params.goalId);
if (!goal) {
throw new ApiError(httpStatus.NOT_FOUND, 'Gaol not found');
}
res.send(goal);
});
module.exports = {
getGoals,
getGoal,
};

View File

@ -1,6 +1,4 @@
module.exports.authController = require('./auth.controller');
module.exports.userController = require('./user.controller');
module.exports.profileController = require('./profile.controller');
module.exports.activityController = require('./activity.controller');
module.exports.unitController = require('./unit.controller');
module.exports.goalController = require('./goal.controller');
module.exports.mealController = require('./meal.controller');

View File

@ -0,0 +1,44 @@
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { mealService } = require('../services');
const createMeal = catchAsync(async (req, res) => {
req.body.userId = req.user._id;
const meal = await mealService.createMeal(req.body);
res.status(httpStatus.CREATED).send(meal);
});
const getMeals = catchAsync(async (req, res) => {
const filter = pick(req.query, ['label']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await mealService.queryProfiles(filter, options);
res.send(result);
});
const getMeal = catchAsync(async (req, res) => {
const meal = await mealService.getMealById(req.user._id);
if (!meal) {
throw new ApiError(httpStatus.NOT_FOUND, 'Meal not found');
}
res.send(meal);
});
const updateMeal = catchAsync(async (req, res) => {
const meal = await mealService.getMealById(req.params.mealId, req.body);
res.send(meal);
});
const deleteMeal = catchAsync(async (req, res) => {
await mealService.deleteMealById(req.params.mealId);
res.status(httpStatus.NO_CONTENT).send();
});
module.exports = {
createMeal,
getMeals,
getMeal,
updateMeal,
deleteMeal,
};

View File

@ -18,7 +18,7 @@ const getProfiles = catchAsync(async (req, res) => {
});
const getProfile = catchAsync(async (req, res) => {
const profile = await profileService.getProfileById(req.params.profileId);
const profile = await profileService.getProfileByUserId(req.user._id);
if (!profile) {
throw new ApiError(httpStatus.NOT_FOUND, 'Profile not found');
}

View File

@ -1,25 +0,0 @@
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { unitService } = require('../services');
const getUnits = catchAsync(async (req, res) => {
const filter = pick(req.query, ['name']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await unitService.queryUnits(filter, options);
res.send(result);
});
const getUnit = catchAsync(async (req, res) => {
const unit = await unitService.getUnitById(req.params.unitId);
if (!unit) {
throw new ApiError(httpStatus.NOT_FOUND, 'Unit not found');
}
res.send(unit);
});
module.exports = {
getUnits,
getUnit,
};

View File

@ -10,7 +10,7 @@ const createUser = catchAsync(async (req, res) => {
});
const getUsers = catchAsync(async (req, res) => {
const filter = pick(req.query, ['role']);
const filter = pick(req.query, ['email']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
const result = await userService.queryUsers(filter, options);
res.send(result);

View File

@ -1,22 +1,13 @@
const passport = require('passport');
const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const { roleRights } = require('../config/roles');
const verifyCallback = (req, resolve, reject, requiredRights) => async (err, user, info) => {
const verifyCallback = (req, resolve, reject) => async (err, user, info) => {
if (err || info || !user) {
return reject(new ApiError(httpStatus.UNAUTHORIZED, 'Please authenticate'));
}
req.user = user;
if (requiredRights.length) {
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every((requiredRight) => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
return reject(new ApiError(httpStatus.FORBIDDEN, 'Forbidden'));
}
}
resolve();
};

View File

@ -1,43 +0,0 @@
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const activitySchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
required: true,
trim: true,
index: true,
},
factor: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
// add plugin that converts mongoose to json
activitySchema.plugin(toJSON);
activitySchema.plugin(paginate);
/**
* Check if name is taken
* @param {string} name - The activity's name
* @param {ObjectId} [excludeActivityId] - The id of the activity to be excluded
* @returns {Promise<boolean>}
*/
activitySchema.statics.isNameTaken = async function (name, excludeActivityId) {
const activity = await this.findOne({ name, _id: { $ne: excludeActivityId } });
return !!activity;
};
/**
* @typedef Activity
*/
const Activity = mongoose.model('Activity', activitySchema);
module.exports = Activity;

View File

@ -1,28 +0,0 @@
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const genderSchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
required: true,
trim: true,
},
},
{
timestamps: true,
}
);
genderSchema.plugin(toJSON);
genderSchema.plugin(paginate);
genderSchema.statics.isNameTaken = async function (name, excludeUnitId) {
const gender = await this.findOne({ name, _id: { $ne: excludeUnitId } });
return !!gender;
};
const Gender = mongoose.model('Gender', genderSchema);
module.exports = Gender;

View File

@ -1,33 +0,0 @@
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const goalSchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
required: true,
trim: true,
index: true,
},
value: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
goalSchema.plugin(toJSON);
goalSchema.plugin(paginate);
goalSchema.statics.isNameTaken = async function (name, excludeGoalId) {
const goal = await this.findOne({ name, _id: { $ne: excludeGoalId } });
return !!goal;
};
const Goal = mongoose.model('Goal', goalSchema);
module.exports = Goal;

View File

@ -1,8 +1,5 @@
module.exports.Token = require('./token.model');
module.exports.User = require('./user.model');
module.exports.Profile = require('./profile.model');
module.exports.Activity = require('./activity.model');
module.exports.Product = require('./product.model');
module.exports.Unit = require('./unit.model');
module.exports.Gender = require('./gender.model');
module.exports.Goal = require('./goal.model');
module.exports.Meal = require('./meal.model');

50
src/models/meal.model.js Normal file
View File

@ -0,0 +1,50 @@
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const mealSchema = mongoose.Schema(
{
user: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User',
required: true,
},
label: {
type: String,
emin: ['breakfast', 'lunch', 'dinner', 'supper', 'snack I', 'snack II', 'snack III'],
required: true,
},
products: [
{
product: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Product',
required: true,
},
quantity: {
type: Number,
required: true,
},
unit: {
type: String,
emin: ['g', 'ml', 'portion'],
required: true,
},
},
],
date: {
type: Date,
default: Date.now(),
required: true,
},
},
{
timestamps: true,
}
);
mealSchema.plugin(toJSON);
mealSchema.plugin(paginate);
const Meal = mongoose.model('Meal', mealSchema);
module.exports = Meal;

View File

@ -14,6 +14,14 @@ const productSchema = mongoose.Schema(
type: String,
trim: true,
},
verified: {
type: Boolean,
default: false,
},
eco: {
type: Boolean,
default: false,
},
barcode: {
type: Number,
unique: true,
@ -24,22 +32,11 @@ const productSchema = mongoose.Schema(
ref: 'Unit',
required: true,
},
capacity: {
servingCapacity: {
type: Number,
required: true,
},
package: {
capacity: {
type: Number,
required: true,
},
unit: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Unit',
required: true,
},
},
kcal: {
calories: {
type: Number,
required: true,
},

View File

@ -4,8 +4,13 @@ const { toJSON, paginate } = require('./plugins');
const profileSchema = mongoose.Schema(
{
gender: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Gender',
type: String,
enum: ['male', 'female'],
required: true,
},
goal: {
type: String,
enum: ['lose_weight', 'maintain_weight', 'put_on_weight'],
required: true,
},
birthday: {
@ -20,15 +25,18 @@ const profileSchema = mongoose.Schema(
type: Number,
required: true,
},
targetWeight: {
goalWeight: {
type: Number,
required: true,
},
rateOfChange: {
type: Number,
required: true,
default: 0,
},
activityId: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Activity',
activity: {
type: Number,
enum: [1.2, 1.375, 1.55, 1.725, 1.9],
required: true,
},
userId: {
@ -43,25 +51,14 @@ const profileSchema = mongoose.Schema(
}
);
// add plugin that converts mongoose to json
profileSchema.plugin(toJSON);
profileSchema.plugin(paginate);
/**
* Check if user has profile
* @param {ObjectId} userId - The user's id
* @param {ObjectId} [excludeProfileId] - The id of the profile to be excluded
* @returns {Promise<boolean>}
*/
profileSchema.statics.hasUser = async function (userId, excludeProfileId) {
const user = await this.findOne({ userId, _id: { $ne: excludeProfileId } });
return !!user;
};
/**
* @typedef Profile
*/
const Profile = mongoose.model('Profile', profileSchema);
module.exports = Profile;

View File

@ -1,32 +0,0 @@
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const unitSchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
required: true,
trim: true,
index: true,
},
},
{
timestamps: true,
}
);
unitSchema.plugin(toJSON);
unitSchema.plugin(paginate);
unitSchema.statics.isNameTaken = async function (name, excludeUnitId) {
const unit = await this.findOne({ name, _id: { $ne: excludeUnitId } });
return !!unit;
};
/**
* @typedef Unit
*/
const Unit = mongoose.model('Unit', unitSchema);
module.exports = Unit;

View File

@ -2,7 +2,6 @@ const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const { toJSON, paginate } = require('./plugins');
const { roles } = require('../config/roles');
const userSchema = mongoose.Schema(
{
@ -31,11 +30,6 @@ const userSchema = mongoose.Schema(
},
private: true, // used by the toJSON plugin
},
role: {
type: String,
enum: roles,
default: 'admin',
},
},
{
timestamps: true,

View File

@ -1,228 +0,0 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const activityValidation = require('../../validations/activity.validation');
const activityController = require('../../controllers/activity.controller');
const router = express.Router();
router
.route('/')
.get(auth(), validate(activityValidation.getActivities), activityController.getActivities);
router
.route('/:activityId')
.get(auth(), validate(activityValidation.getActivity), activityController.getActivity)
module.exports = router;
/**
* @swagger
* tags:
* name: Activities
* description: Activity management
*/
/**
* @swagger
* path:
* /activities:
* post:
* summary: Create a activity
* description: Only admins can create activities.
* tags: [Activities]
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* - factor
* properties:
* name:
* type: string
* description: must be unique
* factor:
* type: number
* example:
* name: g
* factor: 1
* responses:
* "201":
* description: Created
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Activity'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*
* get:
* summary: Get all activities
* description: Only admins can retrieve all activities.
* tags: [Activities]
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: name
* schema:
* type: string
* description: Activity name
* - in: query
* name: factor
* schema:
* type: number
* description: Activity factor
* - in: query
* name: sortBy
* schema:
* type: string
* description: sort by query in the form of field:desc/asc (ex. name:asc)
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* default: 10
* description: Maximum number of activities
* - in: query
* name: page
* schema:
* type: integer
* minimum: 1
* default: 1
* description: Page number
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* type: object
* properties:
* results:
* type: array
* items:
* $ref: '#/components/schemas/Activity'
* page:
* type: integer
* example: 1
* limit:
* type: integer
* example: 10
* totalPages:
* type: integer
* example: 1
* totalResults:
* type: integer
* example: 1
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*/
/**
* @swagger
* path:
* /activities/{id}:
* get:
* summary: Get a activity
* description: Only admins can fetch activities.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: Activity id
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Activity'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* patch:
* summary: Update a activity
* description: Only admins can update activities.
* tags: [Activities]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: Activity id
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* description: must be unique
* factor:
* type: number
* example:
* name: normal
* factor: 1
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Activity'
* "400":
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* delete:
* summary: Delete a activity
* description: Only admins can delete activities.
* tags: [Activities]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: Activity id
* responses:
* "200":
* description: No content
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*/

View File

@ -1,17 +0,0 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const genderValidation = require('../../validations/gender.validation');
const genderController = require('../../controllers/gender.controller');
const router = express.Router();
router
.route('/')
.get(auth(), validate(genderValidation.getGenders), genderController.getGenders);
router
.route('/:genderId')
.get(auth(), validate(genderValidation.getGender), genderController.getGender)
module.exports = router;

View File

@ -1,17 +0,0 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const goalValidation = require('../../validations/goal.validation');
const goalController = require('../../controllers/goal.controller');
const router = express.Router();
router
.route('/')
.get(auth(), validate(goalValidation.getGoals), goalController.getGoals);
router
.route('/:goalId')
.get(auth(), validate(goalValidation.getGoal), goalController.getGoal)
module.exports = router;

View File

@ -2,21 +2,15 @@ const express = require('express');
const authRoute = require('./auth.route');
const userRoute = require('./user.route');
const profileRoute = require('./profile.route');
const activityRoute = require('./activity.route');
const unitRoute = require('./unit.route');
const genderRoute = require('./gender.route');
const goalRoute = require('./goal.route');
const docsRoute = require('./docs.route');
const meal = require('./meal.route');
const router = express.Router();
router.use('/auth', authRoute);
router.use('/users', userRoute);
router.use('/profiles', profileRoute);
router.use('/activities', activityRoute);
router.use('/units', unitRoute);
router.use('/genders', genderRoute);
router.use('/goals', goalRoute);
router.use('/docs', docsRoute);
router.use('/meals', meal);
module.exports = router;

View File

@ -0,0 +1,20 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const mealValidation = require('../../validations/meal.validation');
const mealController = require('../../controllers/meal.controller');
const router = express.Router();
router
.route('/')
.post(auth(), validate(mealValidation.createMeal), mealController.createMeal)
.get(auth(), validate(mealValidation.getMeals), mealController.getMeals);
router
.route('/:mealId')
.get(auth(), validate(mealValidation.getMeal), mealController.getMeal)
.patch(auth(), validate(mealValidation.updateMeal), mealController.updateMeal)
.delete(auth(), validate(mealValidation.deleteMeal), mealController.deleteMeal);
module.exports = router;

View File

@ -9,246 +9,13 @@ const router = express.Router();
router
.route('/')
.post(auth(), validate(profileValidation.createProfile), profileController.createProfile)
.get(auth('getProfiles'), validate(profileValidation.getProfiles), profileController.getProfiles);
.get(auth(), validate(profileValidation.getProfile), profileController.getProfile)
.patch(auth(), validate(profileValidation.updateProfile), profileController.updateProfile)
.delete(auth(), validate(profileValidation.deleteProfile), profileController.deleteProfile);
router
.route('/:profileId')
.get(auth('getProfiles'), validate(profileValidation.getProfile), profileController.getProfile)
.patch(auth('manageProfiles'), validate(profileValidation.updateProfile), profileController.updateProfile)
.delete(auth('manageProfiles'), validate(profileValidation.deleteProfile), profileController.deleteProfile);
.route('/admin')
.get(auth(), validate(profileValidation.getProfiles), profileController.getProfiles);
module.exports = router;
/**
* @swagger
* tags:
* name: Profiles
* description: Profile management and retrieval
*/
/**
* @swagger
* path:
* /profiles:
* post:
* summary: Create a user
* description: Only admins can create other users.
* tags: [Users]
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* - email
* - password
* - role
* properties:
* name:
* type: string
* email:
* type: string
* format: email
* description: must be unique
* password:
* type: string
* format: password
* minLength: 8
* description: At least one number and one letter
* role:
* type: string
* enum: [user, admin]
* example:
* name: fake name
* email: fake@example.com
* password: password1
* role: user
* responses:
* "201":
* description: Created
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "400":
* $ref: '#/components/responses/DuplicateEmail'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*
* get:
* summary: Get all profiles
* description: Only admins can retrieve all profiles.
* tags: [Profiles]
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: name
* schema:
* type: string
* description: User name
* - in: query
* name: role
* schema:
* type: string
* description: User role
* - in: query
* name: sortBy
* schema:
* type: string
* description: sort by query in the form of field:desc/asc (ex. name:asc)
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* default: 10
* description: Maximum number of users
* - in: query
* name: page
* schema:
* type: integer
* minimum: 1
* default: 1
* description: Page number
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* type: object
* properties:
* results:
* type: array
* items:
* $ref: '#/components/schemas/User'
* page:
* type: integer
* example: 1
* limit:
* type: integer
* example: 10
* totalPages:
* type: integer
* example: 1
* totalResults:
* type: integer
* example: 1
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*/
/**
* @swagger
* path:
* /profiles/{id}:
* get:
* summary: Get a profile
* description: Logged in users can fetch only their own profile information. Only admins can fetch other profiles.
* tags: [Profiles]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* patch:
* summary: Update a profile
* description: Logged in users can only update their own information. Only admins can update other profiles.
* tags: [Profiles]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* email:
* type: string
* format: email
* description: must be unique
* password:
* type: string
* format: password
* minLength: 8
* description: At least one number and one letter
* example:
* name: fake name
* email: fake@example.com
* password: password1
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* "400":
* $ref: '#/components/responses/DuplicateEmail'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*
* delete:
* summary: Delete a profile
* description: Logged in users can delete only themselves. Only admins can delete other users.
* tags: [Users]
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User id
* responses:
* "200":
* description: No content
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
* "404":
* $ref: '#/components/responses/NotFound'
*/

View File

@ -1,17 +0,0 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const unitValidation = require('../../validations/unit.validation');
const unitController = require('../../controllers/unit.controller');
const router = express.Router();
router
.route('/')
.get(auth(), validate(unitValidation.getUnits), unitController.getUnits);
router
.route('/:activityId')
.get(auth(), validate(unitValidation.getUnit), unitController.getUnit)
module.exports = router;

View File

@ -1,39 +0,0 @@
const { Seeder } = require('mongoose-data-seed');
const { Activity } = require('../models');
const data = [
{
name: 'very low',
factor: 1.2,
},
{
name: 'low',
factor: 1.375,
},
{
name: 'average',
factor: 1.55,
},
{
name: 'high',
factor: 1.725,
},
{
name: 'very high',
factor: 1.9,
},
];
class ActivitySeeder extends Seeder {
async shouldRun() {
return Activity.countDocuments()
.exec()
.then((count) => count === 0);
}
async run() {
return Activity.create(data);
}
}
module.exports = ActivitySeeder;

View File

@ -1,25 +0,0 @@
const { Seeder } = require('mongoose-data-seed');
const { Gender } = require('../models');
const data = [
{
name: 'male',
},
{
name: 'female',
},
];
class GenderSeeder extends Seeder {
async shouldRun() {
return Gender.countDocuments()
.exec()
.then((count) => count === 0);
}
async run() {
return Gender.create(data);
}
}
module.exports = GenderSeeder;

View File

@ -1,31 +0,0 @@
const { Seeder } = require('mongoose-data-seed');
const { Goal } = require('../models');
const data = [
{
name: 'lose weight',
value: -1,
},
{
name: 'maintain weight',
value: 0,
},
{
name: 'put on weight',
value: 1,
},
];
class GoalSeeder extends Seeder {
async shouldRun() {
return Goal.countDocuments()
.exec()
.then((count) => count === 0);
}
async run() {
return Goal.create(data);
}
}
module.exports = GoalSeeder;

View File

@ -1,31 +0,0 @@
const { Seeder } = require('mongoose-data-seed');
const { Unit } = require('../models');
const data = [
{
name: 'kcal',
},
{
name: 'g',
},
{
name: 'ml',
},
{
name: 'l',
},
];
class UnitSeeder extends Seeder {
async shouldRun() {
return Unit.countDocuments()
.exec()
.then((count) => count === 0);
}
async run() {
return Unit.create(data);
}
}
module.exports = UnitSeeder;

View File

@ -1,15 +0,0 @@
const { Activity } = require('../models');
const queryActivities = async (filter, options) => {
const activities = await Activity.paginate(filter, options);
return activities;
};
const getActivityById = async (id) => {
return Activity.findById(id);
};
module.exports = {
queryActivities,
getActivityById,
};

View File

@ -1,15 +0,0 @@
const { Gender } = require('../models');
const queryGenders = async (filter, options) => {
const genders = await Gender.paginate(filter, options);
return genders;
};
const getGenderById = async (id) => {
return Gender.findById(id);
};
module.exports = {
queryGenders,
getGenderById,
};

View File

@ -1,15 +0,0 @@
const { Goal } = require('../models');
const queryGoals = async (filter, options) => {
const goals = await Goal.paginate(filter, options);
return goals;
};
const getGoalById = async (id) => {
return Goal.findById(id);
};
module.exports = {
queryGoals,
getGoalById,
};

View File

@ -3,7 +3,4 @@ module.exports.emailService = require('./email.service');
module.exports.tokenService = require('./token.service');
module.exports.userService = require('./user.service');
module.exports.profileService = require('./profile.service');
module.exports.activityService = require('./activity.service');
module.exports.unitService = require('./unit.service');
module.exports.genderService = require('./gender.service');
module.exports.goalService = require('./goal.service');
module.exports.mealService = require('./meal.service');

View File

@ -0,0 +1,49 @@
const httpStatus = require('http-status');
const { Meal } = require('../models');
const ApiError = require('../utils/ApiError');
const createMeal = async (mealBody) => {
const meal = await Meal.create(mealBody);
return meal;
};
const queryMeals = async (filter, options) => {
const meals = await Meal.paginate(filter, options);
return meals;
};
const getMealById = async (id) => {
return Meal.findById(id);
};
const getMealByUserId = async (userId) => {
return Meal.findOne({ userId });
};
const updateProfileById = async (mealId, updateBody) => {
const meal = await getMealById(mealId);
if (!meal) {
throw new ApiError(httpStatus.NOT_FOUND, 'Meal not found');
}
Object.assign(meal, updateBody);
await meal.save();
return meal;
};
const deleteMealById = async (mealId) => {
const meal = await getMealById(mealId);
if (!meal) {
throw new ApiError(httpStatus.NOT_FOUND, 'Meal not found');
}
await meal.remove();
return meal;
};
module.exports = {
createMeal,
queryMeals,
getMealById,
getMealByUserId,
updateProfileById,
deleteMealById,
};

View File

@ -2,11 +2,6 @@ const httpStatus = require('http-status');
const { Profile } = require('../models');
const ApiError = require('../utils/ApiError');
/**
* Create a profile
* @param {Object} profileBody
* @returns {Promise<Profile>}
*/
const createProfile = async (profileBody) => {
if (await Profile.hasUser(profileBody.userId)) {
throw new ApiError(httpStatus.BAD_REQUEST, 'User already has a profile');
@ -15,44 +10,19 @@ const createProfile = async (profileBody) => {
return profile;
};
/**
* Query for profiles
* @param {Object} filter - Mongo filter
* @param {Object} options - Query options
* @param {string} [options.sortBy] - Sort option in the format: sortField:(desc|asc)
* @param {number} [options.limit] - Maximum number of results per page (default = 10)
* @param {number} [options.page] - Current page (default = 1)
* @returns {Promise<QueryResult>}
*/
const queryProfiles = async (filter, options) => {
const profiles = await Profile.paginate(filter, options);
return profiles;
};
/**
* Get profile by id
* @param {ObjectId} id
* @returns {Promise<Profile>}
*/
const getProfileById = async (id) => {
return Profile.findById(id);
};
/**
* Get profile by user id
* @param {ObjectId} id
* @returns {Promise<User>}
*/
const getProfileByUserId = async (id) => {
return Profile.findOne({ user: id });
const getProfileByUserId = async (userId) => {
return Profile.findOne({ userId });
};
/**
* Update profile by id
* @param {ObjectId} profileId
* @param {Object} updateBody
* @returns {Promise<Profile>}
*/
const updateProfileById = async (profileId, updateBody) => {
const profile = await getProfileById(profileId);
if (!profile) {
@ -63,11 +33,6 @@ const updateProfileById = async (profileId, updateBody) => {
return profile;
};
/**
* Delete profile by id
* @param {ObjectId} profileId
* @returns {Promise<User>}
*/
const deleteProfileById = async (profileId) => {
const profile = await getProfileById(profileId);
if (!profile) {

View File

@ -1,15 +0,0 @@
const { Unit } = require('../models');
const queryUnits = async (filter, options) => {
const units = await Unit.paginate(filter, options);
return units;
};
const getUnitById = async (id) => {
return Unit.findById(id);
};
module.exports = {
queryUnits,
getUnitById,
};

View File

@ -1,22 +0,0 @@
const Joi = require('joi');
const { objectId } = require('./custom.validation');
const getActivities = {
query: Joi.object().keys({
name: Joi.string(),
factor: Joi.number(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getActivity = {
params: Joi.object().keys({
activityId: Joi.string().custom(objectId),
}),
};
module.exports = {
getActivities,
getActivity,
};

View File

@ -1,21 +0,0 @@
const Joi = require('joi');
const { objectId } = require('./custom.validation');
const getGenders = {
query: Joi.object().keys({
name: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getGender = {
params: Joi.object().keys({
genderId: Joi.string().custom(objectId),
}),
};
module.exports = {
getGenders,
getGender,
};

View File

@ -1,22 +0,0 @@
const Joi = require('joi');
const { objectId } = require('./custom.validation');
const getGoals = {
query: Joi.object().keys({
name: Joi.string(),
value: Joi.number(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getGaol = {
params: Joi.object().keys({
goalId: Joi.string().custom(objectId),
}),
};
module.exports = {
getGoals,
getGaol,
};

View File

@ -1,7 +1,5 @@
module.exports.authValidation = require('./auth.validation');
module.exports.userValidation = require('./user.validation');
module.exports.profileValidation = require('./profile.validation');
module.exports.activityValidation = require('./activity.validation');
module.exports.unitValidation = require('./unit.validation');
module.exports.productValidation = require('./product.validation');
module.exports.goalValidation = require('./goal.validation');
module.exports.mealValidation = require('./meal.validation');

View File

@ -0,0 +1,60 @@
const Joi = require('joi');
const { objectId } = require('./custom.validation');
const products = Joi.object().keys({
product: Joi.string().custom(objectId).required(),
quantity: Joi.number().required(),
unit: Joi.string().required().valid('g', 'ml', 'portion'),
});
const createMeal = {
body: Joi.object().keys({
user: Joi.string().custom(objectId).required(),
label: Joi.string().required().valid('breakfast', 'lunch', 'dinner', 'supper', 'snack I', 'snack II', 'snack III'),
products: Joi.array().items(products).required(),
date: Joi.date().required(),
}),
};
const getMeals = {
query: Joi.object().keys({
label: Joi.string().required().valid('breakfast', 'lunch', 'dinner', 'supper', 'snack I', 'snack II', 'snack III'),
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getMeal = {
params: Joi.object().keys({
mealId: Joi.string().custom(objectId),
}),
};
const updateMeal = {
params: Joi.object().keys({
mealId: Joi.required().custom(objectId),
}),
body: Joi.object()
.keys({
user: Joi.string().custom(objectId).required(),
label: Joi.string().required().valid('breakfast', 'lunch', 'dinner', 'supper', 'snack I', 'snack II', 'snack III'),
products: Joi.array().items(products).required(),
date: Joi.date().required(),
})
.min(1),
};
const deleteMeal = {
params: Joi.object().keys({
mealId: Joi.string().custom(objectId).required(),
}),
};
module.exports = {
createMeal,
getMeals,
getMeal,
updateMeal,
deleteMeal,
};

View File

@ -4,9 +4,11 @@ const { objectId } = require('./custom.validation');
const createProduct = {
body: Joi.object().keys({
barcode: Joi.number(),
verified: Joi.boolean(),
eco: Joi.boolean(),
name: Joi.string().required(),
capacity: Joi.number().required(),
kcal: Joi.number().required(),
servingCapacity: Joi.number().required(),
calories: Joi.number().required(),
fat: Joi.number().required(),
carbohydrates: Joi.number().required(),
protein: Joi.number().required(),
@ -19,6 +21,8 @@ const getProducts = {
query: Joi.object().keys({
barcode: Joi.number(),
name: Joi.string(),
verified: Joi.boolean(),
eco: Joi.boolean(),
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
@ -38,9 +42,11 @@ const updateProduct = {
body: Joi.object()
.keys({
barcode: Joi.number(),
verified: Joi.boolean(),
eco: Joi.boolean(),
name: Joi.string().required(),
capacity: Joi.number().required(),
kcal: Joi.number().required(),
servingCapacity: Joi.number().required(),
calories: Joi.number().required(),
fat: Joi.number().required(),
carbohydrates: Joi.number().required(),
protein: Joi.number().required(),

View File

@ -3,19 +3,19 @@ const { objectId } = require('./custom.validation');
const createProfile = {
body: Joi.object().keys({
sex: Joi.string().required().valid('male', 'female'),
gender: Joi.string().required().valid('male', 'female'),
goal: Joi.string().required().valid('lose_weight', 'maintain_weight', 'put_on_weight'),
birthday: Joi.date().required(),
height: Joi.number().required(),
currentWeight: Joi.number().required(),
targetWeight: Joi.number(),
rateOfChange: Joi.number(),
activityId: Joi.string().custom(objectId).required(),
goalWeight: Joi.number().required(),
rateOfChange: Joi.number().required(),
activity: Joi.number().required().valid(1.2, 1.375, 1.55, 1.725, 1.9),
}),
};
const getProfiles = {
query: Joi.object().keys({
sex: Joi.string(),
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
@ -32,17 +32,16 @@ const updateProfile = {
params: Joi.object().keys({
profileId: Joi.required().custom(objectId),
}),
body: Joi.object()
.keys({
sex: Joi.string().required().valid('male', 'female'),
birthday: Joi.date().required(),
height: Joi.number().required(),
currentWeight: Joi.number().required(),
targetWeight: Joi.number(),
rateOfChange: Joi.number(),
activityId: Joi.string().custom(objectId).required(),
})
.min(1),
body: Joi.object().keys({
gender: Joi.string().required().valid('male', 'female'),
goal: Joi.string().required().valid('lose_weight', 'maintain_weight', 'put_on_weight'),
birthday: Joi.date().required(),
height: Joi.number().required(),
currentWeight: Joi.number().required(),
goalWeight: Joi.number().required(),
rateOfChange: Joi.number(),
activity: Joi.number().required().valid(1.2, 1.375, 1.55, 1.725, 1.9),
}).min(1),
};
const deleteProfile = {

View File

@ -1,21 +0,0 @@
const Joi = require('joi');
const { objectId } = require('./custom.validation');
const getUnits = {
query: Joi.object().keys({
name: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getUnit = {
params: Joi.object().keys({
unitId: Joi.string().custom(objectId),
}),
};
module.exports = {
getUnits,
getUnit,
};