package.json
// this is to aviod CORS policy
// this method will only work in dev mode
"proxy": "http://localhost:4000",
-----------------------------------------------------------------
.env
// no space in between
PORT=4000
--------------------------------------------------------
server.js
const express = require('express');
// env package is required to load enviorment variables from env files
require('dotenv').config();
// mongoose connects to mongoDB
const mongoose = require('mongoose');
const workoutRoutes = require('./routes/workout');
// register app
const app = express();
// this checks if any req is coming into the server and if it does then it passes it and attaches it
app.use(express.json());
// connect to mongoDB
mongoose.connect(process.env.MONGO_URI)
.then(() => {
// listen to port
// process is object where all envirment variables are loaded
app.listen(process.env.PORT, () => {
console.log('listening on port', process.env.PORT);
})
})
.catch(err => {console.log(err)})
// this means when we hit '/api/workouts' url then execute workoutRoutes
app.use('/api/workouts', workoutRoutes);
-----------------------------------------------------------------
routes > workout.js
const express = require('express');
const {postWorkout, allWorkout, particularWorkout, deleteWorkout, updateWorkout} = require('../controllers/workoutController');
// this creates an instance of the router
const router = express.Router();
const requireAuth = require('../middleware/requireAuth');
router.use(requireAuth);
router.get('/', allWorkout);
router.get('/:id', particularWorkout);
router.post('/', postWorkout);
router.delete('/:id', deleteWorkout);
router.patch('/:id', updateWorkout);
module.exports = router
-----------------------------------------------------------------
models > workoutModels.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const workoutSchema = new Schema({
title: {
type: String,
required: true
},
reps: {
type: Number,
required: true
},
load: {
type: Number,
required: true
},
user_id: {
type: String,
required: true
}
}, {timestamps: true})
module.exports = mongoose.model('Workout', workoutSchema);
-----------------------------------------------------------------
controllers > workoutController.js
const Workout = require('../models/workoutModel');
const mongoose = require('mongoose');
// get all workouts
const allWorkout = async (req, res) => {
const user_id = req.user._id;
const workout = await Workout.find({user_id})
res.status(200).json(workout)
}
// get a particular workout
const particularWorkout = async (req, res) => {
const {id} = req.params;
if(!mongoose.Types.ObjectId.isValid(id)){
return res.status(404).json({error: 'No such workout found'});
}
const workout = await Workout.findById(id);
if(!workout){
return res.status(400).json({error: 'No workouts found'});
}
res.status(200).json(workout);
}
// post a workout
const postWorkout = async (req, res) => {
const {title, reps, load} = req.body
const user_id = req.user._id
try{
const workout = await Workout.create({title, reps, load, user_id})
res.status(200).json(workout)
}catch(err){
res.status(400).json({error: err.message});
}
}
// delete a workout
const deleteWorkout = async (req, res) => {
const {id} = req.params;
if(!mongoose.Types.ObjectId.isValid(id)){
return res.status(404).json({error: 'No such workout found'});
}
const workout = await Workout.findOneAndDelete({_id: id})
if(!workout){
return res.status(400).json({error: 'No workouts found'});
}
res.status(200).json(workout);
}
// update a workout
const updateWorkout = async (req, res) => {
const {id} = req.params;
if(!mongoose.Types.ObjectId.isValid(id)){
return res.status(404).json({error: 'No such workout found'});
}
const workout = await Workout.findOneAndUpdate({_id: id}, {
...req.body
})
if(!workout){
return res.status(400).json({error: 'No workouts found'});
}
res.status(200).json(workout)
}
module.exports = {
postWorkout,
allWorkout,
particularWorkout,
deleteWorkout,
updateWorkout
}
-----------------------------------------------------------
middleware > requireAuth.js
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const requireAuth = async (req, res, next) => {
const {authorization} = req.headers;
if(!authorization){
return res.status(401).json({error: 'Authorization token required'});
}
const token = authorization.split(' ')[1]
try{
const {_id} = jwt.verify(token, process.env.SECRET);
req.user = await User.findOne({_id}).select({_id})
next()
}catch(error){
console.log(error);
res.status(401).json({error: 'Request is not authorized'})
}
}
module.exports = requireAuth
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter