backedn converted to ts

This commit is contained in:
QkoSad
2023-07-27 15:58:35 +03:00
parent 3bf4e9fc56
commit 40051f9d5e
18 changed files with 1394 additions and 29668 deletions
+2 -1
View File
@@ -48,5 +48,6 @@
}, },
"devDependencies": { "devDependencies": {
"@types/uuid": "^9.0.2" "@types/uuid": "^9.0.2"
} },
"proxy": "http://localhost:5000"
} }
+2 -7
View File
@@ -9,11 +9,6 @@ const Login = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated); const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated);
const onChangeEmail = () =>
setEmail(email)
const onChangePasword = () =>
setPassword(password)
const onSubmit = async (e: React.SyntheticEvent) => { const onSubmit = async (e: React.SyntheticEvent) => {
e.preventDefault(); e.preventDefault();
await dispatch(login(email, password)); await dispatch(login(email, password));
@@ -36,7 +31,7 @@ const Login = () => {
placeholder="Email Address" placeholder="Email Address"
name="email" name="email"
value={email} value={email}
onChange={onChangeEmail} onChange={(e) => setEmail(e.target.value)}
/> />
</div> </div>
<div className="form-group"> <div className="form-group">
@@ -45,7 +40,7 @@ const Login = () => {
placeholder="Password" placeholder="Password"
name="password" name="password"
value={password} value={password}
onChange={onChangePasword} onChange={(e)=>setPassword(e.target.value)}
//used to be "6" //used to be "6"
minLength={6} minLength={6}
/> />
+4 -4
View File
@@ -40,7 +40,7 @@ const Register = () => {
placeholder="Name" placeholder="Name"
name="name" name="name"
value={name} value={name}
onChange={() => setName(name)} onChange={(e) => setName(e.target.value)}
/> />
</div> </div>
<div className="form-group"> <div className="form-group">
@@ -49,7 +49,7 @@ const Register = () => {
placeholder="Email Address" placeholder="Email Address"
name="email" name="email"
value={email} value={email}
onChange={() => setEmail(email)} onChange={(e) => setEmail(e.target.value)}
/> />
<small className="form-text"> <small className="form-text">
This site uses Gravatar so if you want a profile image, use a This site uses Gravatar so if you want a profile image, use a
@@ -62,7 +62,7 @@ const Register = () => {
placeholder="Password" placeholder="Password"
name="password" name="password"
value={password} value={password}
onChange={() => setPassword(password)} onChange={(e) => setPassword(e.target.value)}
/> />
</div> </div>
<div className="form-group"> <div className="form-group">
@@ -71,7 +71,7 @@ const Register = () => {
placeholder="Confirm Password" placeholder="Confirm Password"
name="password2" name="password2"
value={password2} value={password2}
onChange={() => setPassword2(password2)} onChange={(e) => setPassword2(e.target.value)}
/> />
</div> </div>
<input type="submit" className="btn btn-primary" value="Register" /> <input type="submit" className="btn btn-primary" value="Register" />
+11 -10
View File
@@ -1,20 +1,21 @@
const mongoose = require('mongoose'); import mongoose from "mongoose";
const config = require('config'); import config from 'config'
const db = config.get('mongoURI'); const db = config.get('mongoURI');
const connectDB = async () => { const connectDB = async () => {
try { try {
await mongoose.connect(db, { if (typeof db === 'string')
useNewUrlParser: true, await mongoose.connect(db);
useUnifiedTopology: true
});
console.log('MongoDB Connected...'); console.log('MongoDB Connected...');
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
// Exit process with failure console.error(err)
else if (err instanceof Error)
console.error(err.message);
process.exit(1); process.exit(1);
} }
}; };
module.exports = connectDB; export default connectDB
+10 -7
View File
@@ -1,8 +1,9 @@
const config = require('config'); import config from 'config'
const jwt = require('jsonwebtoken'); import jwt from 'jsonwebtoken'
import type { Request, Response, NextFunction } from 'express';
function auth(req: Request, res: Response, next: NextFunction) {
module.exports = function (req, res, next) {
// Get token from header // Get token from header
const token = req.header('x-auth-token'); const token = req.header('x-auth-token');
// Check if not token // Check if not token
@@ -16,7 +17,8 @@ module.exports = function (req, res, next) {
if (error) { if (error) {
return res.status(401).json({ msg: 'Token is not valid' }); return res.status(401).json({ msg: 'Token is not valid' });
} else { } else {
req.user = decoded.user; if ('user' in req && decoded && typeof decoded !== "string")
req.user = decoded?.user;
next(); next();
} }
}); });
@@ -24,5 +26,6 @@ module.exports = function (req, res, next) {
console.error('something wrong with auth middleware'); console.error('something wrong with auth middleware');
res.status(500).json({ msg: 'Server Error' }); res.status(500).json({ msg: 'Server Error' });
} }
}; };
export default auth
+4 -3
View File
@@ -1,9 +1,10 @@
const mongoose = require('mongoose'); import mongoose from "mongoose";
// middleware to check for a valid object id // middleware to check for a valid object id
const checkObjectId = (idToCheck) => (req, res, next) => { import type { Request, Response, NextFunction } from "express";
const checkObjectId = (idToCheck: string) => (req: Request, res: Response, next: NextFunction) => {
if (!mongoose.Types.ObjectId.isValid(req.params[idToCheck])) if (!mongoose.Types.ObjectId.isValid(req.params[idToCheck]))
return res.status(400).json({ msg: 'Invalid ID' }); return res.status(400).json({ msg: 'Invalid ID' });
next(); next();
}; };
module.exports = checkObjectId; export default checkObjectId
+4 -2
View File
@@ -1,4 +1,5 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const Schema = mongoose.Schema; const Schema = mongoose.Schema;
const PostSchema = new Schema({ const PostSchema = new Schema({
@@ -49,4 +50,5 @@ const PostSchema = new Schema({
}, },
}); });
module.exports = mongoose.model("post", PostSchema); const Post = mongoose.model("post", PostSchema);
export default Post
+3 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const ProfileSchema = new mongoose.Schema({ const ProfileSchema = new mongoose.Schema({
user: { user: {
@@ -110,4 +110,5 @@ const ProfileSchema = new mongoose.Schema({
}, },
}); });
module.exports = mongoose.model("profile", ProfileSchema); const Profile = mongoose.model("profile", ProfileSchema);
export default Profile
+4 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({ const UserSchema = new mongoose.Schema({
name: { name: {
@@ -23,4 +23,6 @@ const UserSchema = new mongoose.Schema({
}, },
}); });
module.exports = mongoose.model("user", UserSchema); const User = mongoose.model("user", UserSchema);
export default User
+845 -29380
View File
File diff suppressed because it is too large Load Diff
+21 -15
View File
@@ -1,11 +1,11 @@
{ {
"name": "mern-stack-front-to-back", "name": "devconnectts",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "server.js", "main": "server.ts",
"scripts": { "scripts": {
"start": "node server", "start": "ts-node server.ts",
"server": "nodemon server", "server": "ts-node-dev server.ts",
"client": "npm start --prefix client --trace-depracation", "client": "npm start --prefix client --trace-depracation",
"dev": "concurrently \"npm run server\" \"npm run client\"", "dev": "concurrently \"npm run server\" \"npm run client\"",
"render": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client" "render": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
@@ -13,19 +13,25 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"axios": "^0.21.0", "axios": "^1.4.0",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"client": "file:client", "config": "^3.3.9",
"config": "^3.3.3", "cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.18.2",
"express-validator": "^6.8.1", "express-validator": "^7.0.1",
"gravatar": "^1.8.1", "gravatar": "^1.8.2",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^9.0.1",
"mongoose": "^5.11.8", "mongoose": "^7.4.1",
"normalize-url": "^5.3.0" "normalize-url": "^5.0.0",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0"
}, },
"devDependencies": { "devDependencies": {
"concurrently": "^5.3.0", "@types/bcryptjs": "^2.4.2",
"nodemon": "^2.0.6" "@types/config": "^3.3.0",
"@types/express": "^4.17.17",
"@types/gravatar": "^1.8.3",
"@types/jsonwebtoken": "^9.0.2",
"@types/uuid": "^9.0.2"
} }
} }
+37 -21
View File
@@ -1,22 +1,34 @@
const express = require("express"); import express from 'express'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken';
import auth from '../../middleware/auth'
import config from 'config'
import { check, validationResult } from "express-validator";
import User from '../../models/User'
import type { Request, Response } from 'express';
import { isUserId } from '../../utils';
const router = express.Router(); const router = express.Router();
const bcrypt = require("bcryptjs");
const auth = require("../../middleware/auth");
const jwt = require("jsonwebtoken");
const config = require("config");
const { check, validationResult } = require("express-validator");
const User = require("../../models/User");
// @route GET api/auth // @route GET api/auth
// @desc Get user by token // @desc Get user by token
// @access Private // @access Private
router.get("/", auth, async (req, res) => { router.get("/", auth, async (req: Request, res) => {
try { try {
const user = await User.findById(req.user.id).select("-password"); let user: unknown = null
res.json(user); if (isUserId(req)) {
} catch (err) { user = await User.findById(req.user.id).select("-password");
console.error(err.message); res.json(user);
}
else {
throw new Error('missing id in request')
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
}); });
@@ -30,7 +42,7 @@ router.post(
check("email", "Please include a valid email").isEmail(), check("email", "Please include a valid email").isEmail(),
check("password", "Password is required").exists(), check("password", "Password is required").exists(),
], ],
async (req, res) => { async (req: Request, res: Response) => {
const errors = validationResult(req); const errors = validationResult(req);
if (!errors.isEmpty()) { if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() }); return res.status(400).json({ errors: errors.array() });
@@ -60,21 +72,25 @@ router.post(
id: user.id, id: user.id,
}, },
}; };
const jwtSecret = config.get('jwtSecret')
jwt.sign( if (typeof jwtSecret === 'string') jwt.sign(
payload, payload,
config.get("jwtSecret"), jwtSecret,
{ expiresIn: 360000 }, { expiresIn: 360000 },
(err, token) => { (err, token) => {
if (err) throw err; if (err) throw err;
res.json({ token }); res.json({ token });
} }
); );
} catch (err) { else throw new Error('Error signing the jwt token')
console.error(err.message); } catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server error"); res.status(500).send("Server error");
} }
} }
); );
module.exports = router; module.exports = router
+148 -92
View File
@@ -1,11 +1,14 @@
const express = require("express");
const router = express.Router();
const { check, validationResult } = require("express-validator");
const auth = require("../../middleware/auth");
const Post = require("../../models/Post"); import express, { Request, Response } from 'express'
const User = require("../../models/User"); import { check, validationResult } from "express-validator";
const checkObjectId = require("../../middleware/checkObjectId"); import auth from "../../middleware/auth";
import Post from "../../models/Post";
import User from "../../models/User";
import checkObjectId from "../../middleware/checkObjectId";
import { isUserId } from '../../utils';
const router = express.Router();
// @route POST api/posts // @route POST api/posts
// @desc Create a post // @desc Create a post
@@ -22,20 +25,30 @@ router.post(
} }
try { try {
const user = await User.findById(req.user.id).select("-password"); if (isUserId(req)) {
const user = await User.findById(req.user.id).select("-password");
const newPost = new Post({ if (user) {
text: req.body.text, const newPost = new Post({
name: user.name, text: req.body.text,
avatar: user.avatar, name: user.name,
user: req.user.id, avatar: user.avatar,
}); user: req.user.id,
});
const post = await newPost.save(); const post = await newPost.save();
res.json(post);
res.json(post); }
} catch (err) { else {
console.error(err.message); throw new Error('Error finding the user')
}
}
else {
throw new Error('Error finding the user')
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
} }
@@ -48,8 +61,11 @@ router.get("/", auth, async (req, res) => {
try { try {
const posts = await Post.find().sort({ date: -1 }); const posts = await Post.find().sort({ date: -1 });
res.json(posts); res.json(posts);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
}); });
@@ -66,8 +82,11 @@ router.get("/:id", auth, checkObjectId("id"), async (req, res) => {
} }
res.json(post); res.json(post);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
@@ -76,25 +95,32 @@ router.get("/:id", auth, checkObjectId("id"), async (req, res) => {
// @route DELETE api/posts/:id // @route DELETE api/posts/:id
// @desc Delete a post // @desc Delete a post
// @access Private // @access Private
router.delete("/:id", [auth, checkObjectId("id")], async (req, res) => { router.delete("/:id", [auth, checkObjectId("id")], async (req: Request, res: Response) => {
try { try {
const post = await Post.findById(req.params.id); const post = await Post.findOne({ _id: req.params.id });
if (!post) { if (!post) {
return res.status(404).json({ msg: "Post not found" }); return res.status(404).json({ msg: "Post not found" });
} }
// Check user // Check user
if (post.user.toString() !== req.user.id) { if (post.user && isUserId(req)) {
return res.status(401).json({ msg: "User not authorized" }); if (post.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
} }
else {
await post.remove(); throw new Error('Error in req.user')
}
await post.deleteOne();
res.json({ msg: "Post removed" }); res.json({ msg: "Post removed" });
} catch (err) {
console.error(err.message);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
}); });
@@ -107,17 +133,24 @@ router.put("/like/:id", auth, checkObjectId("id"), async (req, res) => {
const post = await Post.findById(req.params.id); const post = await Post.findById(req.params.id);
// Check if the post has already been liked // Check if the post has already been liked
if (post.likes.some((like) => like.user.toString() === req.user.id)) { if (post && isUserId(req)) {
return res.status(400).json({ msg: "Post already liked" }); if (post.likes.some((like) => like.user?.toString() === req.user.id)) {
} return res.status(400).json({ msg: "Post already liked" });
}
post.likes.unshift({ user: req.user.id }); const user: any = req.user.id
// can't make string into ObjectID
post.likes.unshift({ user });
await post.save(); await post.save();
return res.json(post.likes); return res.json(post.likes)
} catch (err) { };
console.error(err.message); } catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
}); });
@@ -130,20 +163,30 @@ router.put("/unlike/:id", auth, checkObjectId("id"), async (req, res) => {
const post = await Post.findById(req.params.id); const post = await Post.findById(req.params.id);
// Check if the post has not yet been liked // Check if the post has not yet been liked
if (!post.likes.some((like) => like.user.toString() === req.user.id)) { if (post && isUserId(req)) {
return res.status(400).json({ msg: "Post has not yet been liked" });
if (!post.likes.some((like) => like.user?.toString() === req.user.id)) {
return res.status(400).json({ msg: "Post has not yet been liked" });
}
// remove the like
post.likes = post.likes.filter(
({ user }) => {
if (user)
return user.toString() !== req.user.id
return false
}
);
await post.save();
return res.json(post.likes);
} }
} catch (err: unknown) {
// remove the like if (typeof err === 'string')
post.likes = post.likes.filter( console.error(err)
({ user }) => user.toString() !== req.user.id else if (err instanceof Error)
); console.error(err.message);
await post.save();
return res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
}); });
@@ -163,23 +206,31 @@ router.post(
} }
try { try {
const user = await User.findById(req.user.id).select("-password"); if (isUserId(req) && req.params) {
const post = await Post.findById(req.params.id); const user = await User.findById(req.user.id).select("-password");
const post = await Post.findById(req.params.id);
const newComment = { if (user) {
text: req.body.text, const newComment = {
name: user.name, text: req.body.text,
avatar: user.avatar, name: user.name,
user: req.user.id, avatar: user.avatar,
}; user: req.user.id,
};
post.comments.unshift(newComment); if (post) {
post.comments.unshift(newComment as any);
await post.save(); await post.save();
res.json(post.comments);
res.json(post.comments); }
} catch (err) { throw new Error('Error in finding post')
console.error(err.message); }
throw new Error('Error in finding user')
}
throw new Error('Error in parsing the req')
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error"); res.status(500).send("Server Error");
} }
} }
@@ -193,29 +244,34 @@ router.delete("/comment/:id/:comment_id", auth, async (req, res) => {
const post = await Post.findById(req.params.id); const post = await Post.findById(req.params.id);
// Pull out comment // Pull out comment
const comment = post.comments.find( if (post) {
(comment) => comment.id === req.params.comment_id const comment = post.comments.find(
); (comment: any) => comment.id === req.params.comment_id
// Make sure comment exists );
if (!comment) { // Make sure comment exists
return res.status(404).json({ msg: "Comment does not exist" }); if (!comment) {
return res.status(404).json({ msg: "Comment does not exist" });
}
// Check user
if ('user' in comment && comment.user && isUserId(req) && comment.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
post.comments = post.comments.filter(
({ id }: any) => id !== req.params.comment_id
);
await post.save();
return res.json(post.comments);
} }
// Check user } catch (err: unknown) {
if (comment.user.toString() !== req.user.id) { if (typeof err === 'string')
return res.status(401).json({ msg: "User not authorized" }); console.error(err)
} else if (err instanceof Error)
console.error(err.message);
post.comments = post.comments.filter(
({ id }) => id !== req.params.comment_id
);
await post.save();
return res.json(post.comments);
} catch (err) {
console.error(err.message);
return res.status(500).send("Server Error"); return res.status(500).send("Server Error");
} }
}); });
module.exports = router; module.exports = router
+148 -98
View File
@@ -1,32 +1,40 @@
const express = require('express'); import express from 'express';
const axios = require('axios'); import axios from 'axios';
const config = require('config'); import config from 'config';
const router = express.Router();
const auth = require('../../middleware/auth');
const { check, validationResult } = require('express-validator');
// bring in normalize to give us a proper url, regardless of what user entered
const normalize = require('normalize-url');
const checkObjectId = require('../../middleware/checkObjectId');
const Profile = require('../../models/Profile'); import auth from '../../middleware/auth';
const User = require('../../models/User'); import { check, validationResult } from 'express-validator';
const Post = require('../../models/Post');
// bring in normalize to give us a proper url, regardless of what user entered
import normalize from 'normalize-url';
import checkObjectId from '../../middleware/checkObjectId';
import Profile from '../../models/Profile';
import User from '../../models/User';
import Post from '../../models/Post';
import { isUserId } from '../../utils';
const router = express.Router();
// @route GET api/profile/me // @route GET api/profile/me
// @desc Get current users profile // @desc Get current users profile
// @access Private // @access Private
router.get('/me', auth, async (req, res) => { router.get('/me', auth, async (req, res) => {
try { try {
const profile = await Profile.findOne({ if (isUserId(req)) {
user: req.user.id const profile = await Profile.findOne({
}).populate('user', ['name', 'avatar']); user: req.user.id
}).populate('user', ['name', 'avatar']);
if (!profile) { if (!profile) {
return res.status(400).json({ msg: 'There is no profile for this user' }); return res.status(400).json({ msg: 'There is no profile for this user' });
}
res.json(profile);
} }
} catch (err: unknown) {
res.json(profile); if (typeof err === 'string')
} catch (err) { console.error(err)
console.error(err.message); else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error'); res.status(500).send('Server Error');
} }
}); });
@@ -59,40 +67,45 @@ router.post(
} = req.body; } = req.body;
// build a profile // build a profile
const profileFields = { if (isUserId(req)) {
user: req.user.id, const profileFields = {
website: user: req.user.id,
website && website !== '' website:
? normalize(website, { forceHttps: true }) website && website !== ''
: '', ? normalize(website, { forceHttps: true })
skills: Array.isArray(skills) : '',
? skills skills: Array.isArray(skills)
: skills.split(',').map((skill) => ' ' + skill.trim()), ? skills
...rest : skills.split(',').map((skill: string) => ' ' + skill.trim()),
}; ...rest
};
// Build socialFields object // Build socialFields object
const socialFields = { youtube, twitter, instagram, linkedin, facebook }; const socialFields: { [key: string]: any } = { youtube, twitter, instagram, linkedin, facebook };
// normalize social fields to ensure valid url // normalize social fields to ensure valid url
for (const [key, value] of Object.entries(socialFields)) { for (const [key, value] of Object.entries(socialFields)) {
if (value && value.length > 0) if (value && value.length > 0)
socialFields[key] = normalize(value, { forceHttps: true }); socialFields[key] = normalize(value, { forceHttps: true });
} }
// add to profileFields // add to profileFields
profileFields.social = socialFields; profileFields.social = socialFields;
try { try {
// Using upsert option (creates new doc if no match is found): // Using upsert option (creates new doc if no match is found):
let profile = await Profile.findOneAndUpdate( let profile = await Profile.findOneAndUpdate(
{ user: req.user.id }, { user: req.user.id },
{ $set: profileFields }, { $set: profileFields },
{ new: true, upsert: true, setDefaultsOnInsert: true } { new: true, upsert: true, setDefaultsOnInsert: true }
); );
return res.json(profile); return res.json(profile);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
return res.status(500).send('Server Error'); console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).send('Server Error');
}
} }
} }
); );
@@ -104,8 +117,11 @@ router.get('/', async (req, res) => {
try { try {
const profiles = await Profile.find().populate('user', ['name', 'avatar']); const profiles = await Profile.find().populate('user', ['name', 'avatar']);
res.json(profiles); res.json(profiles);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error'); res.status(500).send('Server Error');
} }
}); });
@@ -125,8 +141,11 @@ router.get(
if (!profile) return res.status(400).json({ msg: 'Profile not found' }); if (!profile) return res.status(400).json({ msg: 'Profile not found' });
return res.json(profile); return res.json(profile);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' }); return res.status(500).json({ msg: 'Server error' });
} }
} }
@@ -140,15 +159,19 @@ router.delete('/', auth, async (req, res) => {
// Remove user posts // Remove user posts
// Remove profile // Remove profile
// Remove user // Remove user
await Promise.all([ if (isUserId(req))
Post.deleteMany({ user: req.user.id }), await Promise.all([
Profile.findOneAndRemove({ user: req.user.id }), Post.deleteMany({ user: req.user.id }),
User.findOneAndRemove({ _id: req.user.id }) Profile.findOneAndRemove({ user: req.user.id }),
]); User.findOneAndRemove({ _id: req.user.id })
]);
res.json({ msg: 'User deleted' }); res.json({ msg: 'User deleted' });
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error'); res.status(500).send('Server Error');
} }
}); });
@@ -171,15 +194,21 @@ router.put(
} }
try { try {
const profile = await Profile.findOne({ user: req.user.id }); if (isUserId(req)) {
const profile = await Profile.findOne({ user: req.user.id });
profile.experience.unshift(req.body); if (profile) {
profile.experience.unshift(req.body);
await profile.save(); await profile.save();
}
res.json(profile); res.json(profile);
} catch (err) { }
console.error(err.message); } catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error'); res.status(500).send('Server Error');
} }
} }
@@ -191,16 +220,22 @@ router.put(
router.delete('/experience/:exp_id', auth, async (req, res) => { router.delete('/experience/:exp_id', auth, async (req, res) => {
try { try {
const foundProfile = await Profile.findOne({ user: req.user.id }); if (isUserId(req)) {
const foundProfile = await Profile.findOne({ user: req.user.id });
if (foundProfile) {
foundProfile.experience = foundProfile.experience.filter(
(exp: any) => exp._id.toString() !== req.params.exp_id
);
foundProfile.experience = foundProfile.experience.filter( await foundProfile.save();
(exp) => exp._id.toString() !== req.params.exp_id }
); return res.status(200).json(foundProfile);
}
await foundProfile.save(); } catch (err: unknown) {
return res.status(200).json(foundProfile); if (typeof err === 'string')
} catch (error) { console.error(err)
console.error(error); else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' }); return res.status(500).json({ msg: 'Server error' });
} }
}); });
@@ -224,15 +259,20 @@ router.put(
} }
try { try {
const profile = await Profile.findOne({ user: req.user.id }); if (isUserId(req)) {
const profile = await Profile.findOne({ user: req.user.id });
if (profile) {
profile.education.unshift(req.body);
profile.education.unshift(req.body); await profile.save();
}
await profile.save(); res.json(profile);
}
res.json(profile); } catch (err: unknown) {
} catch (err) { if (typeof err === 'string')
console.error(err.message); console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error'); res.status(500).send('Server Error');
} }
} }
@@ -244,14 +284,21 @@ router.put(
router.delete('/education/:edu_id', auth, async (req, res) => { router.delete('/education/:edu_id', auth, async (req, res) => {
try { try {
const foundProfile = await Profile.findOne({ user: req.user.id }); if (isUserId(req)) {
foundProfile.education = foundProfile.education.filter( const foundProfile = await Profile.findOne({ user: req.user.id });
(edu) => edu._id.toString() !== req.params.edu_id if (foundProfile) {
); foundProfile.education = foundProfile.education.filter(
await foundProfile.save(); (edu: any) => edu._id.toString() !== req.params.edu_id
return res.status(200).json(foundProfile); );
} catch (error) { await foundProfile.save();
console.error(error); }
return res.status(200).json(foundProfile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' }); return res.status(500).json({ msg: 'Server error' });
} }
}); });
@@ -271,10 +318,13 @@ router.get('/github/:username', async (req, res) => {
const gitHubResponse = await axios.get(uri, { headers }); const gitHubResponse = await axios.get(uri, { headers });
return res.json(gitHubResponse.data); return res.json(gitHubResponse.data);
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(404).json({ msg: 'No Github profile found' }); return res.status(404).json({ msg: 'No Github profile found' });
} }
}); });
module.exports = router; module.exports = router
+21 -14
View File
@@ -1,12 +1,15 @@
const express = require("express"); import express from "express";
import gravatar from "gravatar";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import config from "config";
import { check, validationResult } from "express-validator";
import User from "../../models/User";
import normalizeUrl from "normalize-url";
const router = express.Router(); const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("config");
const { check, validationResult } = require("express-validator");
const User = require("../../models/User");
const normalize = require('normalize-url');
// @route POST api/users // @route POST api/users
// @desc Register user // @desc Register user
@@ -36,7 +39,7 @@ router.post(
.json({ errors: [{ msg: "User already exists" }] }); .json({ errors: [{ msg: "User already exists" }] });
} }
const avatar = normalize( const avatar = normalizeUrl(
gravatar.url(email, { gravatar.url(email, {
s: "200", s: "200",
r: "pg", r: "pg",
@@ -64,20 +67,24 @@ router.post(
}, },
}; };
jwt.sign( const jwtSecret = config.get('jwtSecret')
if (typeof jwtSecret === 'string') jwt.sign(
payload, payload,
config.get("jwtSecret"), jwtSecret,
{ expiresIn: "5 days" }, { expiresIn: "5 days" },
(err, token) => { (err, token) => {
if (err) throw err; if (err) throw err;
res.json({ token }); res.json({ token });
} }
); );
} catch (err) { } catch (err: unknown) {
console.error(err.message); if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server error"); res.status(500).send("Server error");
} }
} }
); );
module.exports = router; module.exports = router
+12 -10
View File
@@ -1,12 +1,14 @@
const express = require('express'); import express from 'express'
const connectDB= require('./config/db')
const path = require('path') import connectDB from './config/db'
import path from 'path'
const app = express(); const app = express();
connectDB(); connectDB();
app.use(express.json({extended:false})); app.use(express.json());
app.use('/api/users', require('./routers/api/users')) app.use('/api/users', require('./routers/api/users'))
@@ -15,13 +17,13 @@ app.use('/api/profile', require('./routers/api/profile'))
app.use('/api/posts', require('./routers/api/posts')) app.use('/api/posts', require('./routers/api/posts'))
// Serve static assets in production // Serve static assets in production
if (process.env.NODE_ENV==='production'){ if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build')); app.use(express.static('client/build'));
app.get('*',(req, res)=>[ app.get('*', (req, res) => [
res.sendFile(path.resolve(__dirname, 'client', 'build','index.html')) res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
]) ])
} }
const PORT = process.env.PORT || 5000; const PORT = process.env.PORT || 5000;
app.listen(PORT,()=> console.log(`Server started on port ${PORT}`)); app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
+103
View File
@@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
+15
View File
@@ -0,0 +1,15 @@
export const isUserId = function(req: unknown): req is { user: { id: string } } {
let user: unknown = null
let id: unknown = null
if (typeof req === 'object' && req)
if ('user' in req) {
user = req.user
if (typeof user === 'object' && user && 'id' in user) {
id = user.id
if (typeof id === 'string') {
return true
}
}
}
return false
}