Skip to content

Commit

Permalink
Adde user status fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
rosemdev committed Feb 27, 2024
1 parent 5ea4b02 commit 1959763
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 2 deletions.
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const multer = require('multer');

const feedRoutes = require('./routes/feed');
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');

const app = express();

Expand Down Expand Up @@ -49,6 +50,7 @@ app.use((req, res, next) => {

app.use('/feed', feedRoutes);
app.use('/auth', authRoutes);
app.use('/user', userRoutes);

app.use((error, req, res, next) => {
console.log(error);
Expand Down
50 changes: 50 additions & 0 deletions controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const User = require('../models/user');
const { validationResult } = require('express-validator');

exports.getStatus = (req, res, next) => {
User.findById({ _id: req.userId })
.then((user) => {
if (!user) {
const error = new Error('No user found');
error.statusCode = 404;

throw error;
}

res.status(200).json({ status: user.status });
})
.catch((err) => next(new Error(err)));
};

exports.updateStatus = (req, res, next) => {
const errors = validationResult(req);

if (!errors.isEmpty()) {
const error = new Error('Validation Failed!');
error.statusCode = 422;

throw error;
}

const status = req.body.status;

return User.findById({ _id: req.userId })
.then((user) => {
if (!user) {
const error = new Error('No user found');
error.statusCode = 404;

throw error;
}

user.status = status;

return user.save();
})
.then((user) => {
res
.status(200)
.json({ message: 'The user`s status is updated', status: user.status });
})
.catch((err) => next(new Error(err)));
};
5 changes: 3 additions & 2 deletions models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ const userSchema = new Schema({
required: true,
},
status: {
type: Object,
required: false,
type: String,
required: true,
default: 'Newly created!',
},
posts: [
{
Expand Down
23 changes: 23 additions & 0 deletions routes/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const express = require('express');
const { body } = require('express-validator');

const userController = require('../controllers/user');
const isAuth = require('../middleware/isAuth');

const router = express.Router();

// GET /user/status
router.get('/status', isAuth, userController.getStatus);

// PUT /user/status
router.patch(
'/status',
isAuth,
body('status', 'Please enter a valid status')
.isString()
.isLength({ min: 3, max: 45 })
.trim(),
userController.updateStatus
);

module.exports = router;

0 comments on commit 1959763

Please sign in to comment.