Skip to content

Instantly share code, notes, and snippets.

@ma-9
Last active December 23, 2019 13:50
Show Gist options
  • Save ma-9/1606b27dfe3156a8d53f3ed8be9e8125 to your computer and use it in GitHub Desktop.
Save ma-9/1606b27dfe3156a8d53f3ed8be9e8125 to your computer and use it in GitHub Desktop.
365CodingPhaseChallenge

365 CodingPhaseChallenge

Hello Everyone My name is Manav Oza and I'm going to complete this 365CodingPhaseChallenge

This Gist will daily uploads my coding acitivity

// =============== Requiring Express ====================
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const productROutes = require("./api/routes/products");
const orderRoutes = require("./api/routes/orders");
const { databaseUsername, databasePWD } = require("./config/config");
// ======================= Connecting to the Database ==================
mongoose.connect(
"mongodb+srv://" +
databaseUsername +
":" +
databasePWD +
"@protrasys-admin-raot8.mongodb.net/test?retryWrites=true&w=majority",
{ useUnifiedTopology: true, useNewUrlParser: true },
err => {
if (err) {
console.log("Error is Occured ! + " + err);
} else {
console.log("DB Connected");
}
}
);
// =================== Executing express like a function =====================
const app = express();
// ======================= Body Parser ===============================
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// ====================== Logging Incoming Requests ==========================
app.use(morgan("dev"));
// ======================= CORS Setup ===============================
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Header",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT");
return res.status(200).json({});
}
next();
});
// =================== Handling a request ================================
app.use("/products", productROutes);
app.use("/orders", orderRoutes);
app.use((req, res, next) => {
const error = new Error("Not Found");
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
// ===================== Exporting app =====================
module.exports = app;
const useStyle = makeStyles(theme => ({
root: {
padding: theme.spacing(3, 2)
}
}));
deletePersonHandler = (index) => {
// const person = this.state.person.slice();
const person = [...this.state.person];
person.splice(index, 1);
this.setState({
person: person
});
};
// #Day12 #november12 #365CodingPhaseChallenge #ma9Code #ma9 #WelcomeMessageFromDreamWorld
// send mail with defined transport object
let info = transporter.sendMail({
from: `dreamworld.bpccs@gmail.com`, // sender address
to: req.body.email, // list of receivers
subject: `Welcome to Dreamworld ${req.body.name}, Buy Products with ❤`, // Subject line
html: output // html body
});
// #Day13 #november13 #365CodingPhaseChallenge #ma9Code #ma9 #ProductShowcaseUsingHandlebars
<div class="row">
<div class="col-sm-6 col-md-4 offset-md-4 offset-md-3">
<div id="success" class="alert alert-success {{#if noMessage}}d-none{{/if}}" role="alert">
{{ successMsg }}
</div>
</div>
</div>
{{#if homePage}}
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="/images/Products/winterSale.jpg" alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="/images/Products/backToCollege.jpg" alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="/images/Products/SamsungNote10Plus.jpg" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<br><br>
{{/if}}
<div class="row">
{{#each response}}
<div class="col-sm-6 col-md-4 col-lg-3">
<div id="productCard" class="card">
<img class="card-img-top img-responsive" src={{this.imagePath}} alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{this.name}}</h5>
<p class="card-text">{{ this.desc }}</p>
<div>
<div class="float-left price">₹ {{ this.price }}</div>
<a href="/add-to-cart/{{this._id}}" class="btn btn-success float-right">Add to Cart</a>
</div>
</div>
</div>
</div>
{{/each}}
</div>
// #Day14 #november14 #365CodingPhaseChallenge #ma9Code #ma9 #PassportAuthentication
var passport = require("passport");
var User = require("../models/users");
// Making Local Strategy of Passport Authentication
var Localstrategy = require("passport-local").Strategy;
// Serialize and Deserialize user
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
// Creating new User (sign up)
passport.use(
"local-signup",
new Localstrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true
},
(req, email, password, done) => {
req
.checkBody("email", "Invalid Email")
.notEmpty()
.isEmail();
req
.checkBody("password", "Invalid Password")
.notEmpty()
.isLength({ min: 6 });
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach(error => {
messages.push(error.msg);
});
return done(null, false, req.flash("error", messages));
}
User.findOne({ email: email }, (err, user) => {
if (err) {
return done(err);
}
if (user) {
return done(null, false, { message: "User is already exists" });
}
var newUser = new User();
if (req.body.name === "") {
return done(null, false, { message: "Kindly Enter User Name" });
} else {
newUser.name = req.body.name;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.save((err, result) => {
if (err) {
return done(err);
}
return done(null, newUser);
});
}
});
}
)
);
// Fetching User (Sign in)
passport.use(
"local-signin",
new Localstrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true
},
function(req, email, password, done) {
req.checkBody("email", "Invalid Email").notEmpty();
req.checkBody("password", "Invalid Password").notEmpty();
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach(err => {
messages.push(err.msg);
});
return done(null, false, req.flash("error", messages));
}
User.findOne({ email: email }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: "User Not Found !" });
}
if (!user.validPassword(password)) {
return done(null, false, { message: "Wrong Password !" });
}
return done(null, user);
});
}
)
);
{{#each products}}
<li class="list-group-item">
<strong>{{ this.title }}</strong>
<span class="badge badge-info">₹ {{this.price}}</span>
<div class="float-right">
<h5>
<a href="/reduce/{{ this.item._id }}"><i class="fas fa-minus-square"></i></a>
<i class="badge badge-primary">{{this.qty}}</i>
<a href="/addByOne/{{ this.item._id }}"><i class="fas fa-plus-square"></i></a>
</h5>
</div>
</li>
{{/each}}
module.exports = function cart(oldCart){
this.title = oldCart.title || "";
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function(item,id,title){
var storedItem = this.items[id];
if(!storedItem){
storedItem = this.items[id] = {title: title,item: item, qty: 0, price: 0};
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice = (oldCart.totalPrice || 0) + storedItem.price;
this.title = title;
};
this.reduceByOne = function(id){
this.items[id].qty--;
this.totalQty--;
this.totalPrice -= this.items[id].item.price;
if (this.items[id].qty <= 0) {
delete this.items[id];
}
};
this.addByOne = function (id) {
this.items[id].qty++;
this.totalQty ++;
this.totalPrice += this.items[id].price;
};
this.generateArray = function(){
var array = [];
for (var id in this.items){
array.push(this.items[id]);
}
return array;
};
}
const useStyles = makeStyles(theme => ({
root: {
display: "flex"
},
appBar: {
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: theme.spacing(2)
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0
},
drawerPaper: {
width: drawerWidth
},
drawerHeader: {
display: "flex",
alignItems: "center",
padding: theme.spacing(0, 1),
...theme.mixins.toolbar,
justifyContent: "flex-end"
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
marginLeft: -drawerWidth
},
contentShift: {
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
}),
marginLeft: 0
},
link: {
color: "white"
}
}));
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap>
<Link href="./../App.js" onClick={preventDefault} className={classes.link}>
MA9 Burger Builder App
</Link>
</Typography>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="persistent"
anchor="left"
open={open}
classes={{
paper: classes.drawerPaper
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "ltr" ? (
<ChevronLeftIcon />
) : (
<ChevronRightIcon />
)}
</IconButton>
</div>
<Divider />
<List>
<ListItem>
<ListItemIcon>
<Filter1Icon />
</ListItemIcon>
<ListItemText primary="Module 1" />
</ListItem>
<ListItem>
<ListItemIcon>
<Filter2Icon />
</ListItemIcon>
<ListItemText primary="Module 2" />
</ListItem>
<ListItem>
<ListItemIcon>
<Filter3Icon />
</ListItemIcon>
<ListItemText primary="Module 3" />
</ListItem>
</List>
<Divider />
<List>
<ListItem>
<ListItemIcon>
<GitHubIcon />
</ListItemIcon>
<ListItemText primary="Github (ma-9)" />
</ListItem>
</List>
</Drawer>
<main
className={clsx(classes.content, {
[classes.contentShift]: open
})}
>
<div className={classes.drawerHeader} />
<App />
</main>
</div>
class QRCODE extends Component {
static QrCode = window.QRCode;
componentDidMount(){
this.code = new QRCODE.QrCode('qrcode');
}
handleQrCode = (e)=>{
this.code.clear();
this.code.makeCode(e.target.value);
}
render() {
return (
<div>
<div id="qrcode"></div>
<input onChange={this.handleQrCode}/>
</div>
);
}
}
// ============= Importing Dependencies ==============
const router = require("express").Router();
const mongoose = require("mongoose");
const Product = require("../models/products");
// ================= Handling Requests =============
router.get("/", (req, res, next) => {
Product.find()
.select("name price _id")
.exec()
.then(docs => {
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
_id: doc._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + doc._id
}
};
})
};
if (response.count > 0) {
console.log("From Database" + docs);
res.status(200).json(response);
} else {
console.log("No Products ");
res.status(400).json({
message: "No Products"
});
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
router.post("/", (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price
});
product
.save()
.then(result => {
const response = {
message: "Product Created Successfully !!",
name: result.name,
price: result.price,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
};
console.log(result);
res.status(201).json({
CreatedProduct: response
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
router.get("/:ProductID", (req, res, next) => {
const id = req.params.ProductID;
Product.findById(id)
.select("price name _id")
.exec()
.then(doc => {
if (doc) {
console.log("From Database" + doc);
res.status(200).json({
product: doc,
request: {
type: "GET",
description: "To Get All Products Cick Below Link",
url: "http://localhost:3000/products"
}
});
} else {
console.log("404 Product Not Found ");
res.status(400).json({
message: "404 Product Not Found"
});
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
router.patch("/:ProductID", (req, res, next) => {
const id = req.params.ProductID;
const updateOps = {};
for (const Ops of req.body) {
updateOps[Ops.propName] = Ops.value;
}
Product.updateOne({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Product Updated",
More: {
updatedProduct: "http://localhost:3000/products/" + id,
seeAllProducts: "http://localhost:3000/products"
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
router.delete("/:ProductID", (req, res, next) => {
const id = req.params.ProductID;
Product.deleteOne({ _id: id })
.exec()
.then(result => {
console.log("Product Deleted");
if (result.deletedCount > 0) {
res.status(200).json({
message: "Product Deleted",
More: {
Description: "Click below to add new Product",
typeOfRequest: "POST (Must Required)",
url: "http://localhost:3000/products",
body: {
name: "String",
price: "Number"
}
}
});
} else {
res.status(404).json({
message: "No Products found to Delete"
});
}
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
// ================ Exporting Router =====================
module.exports = router;
import React, { Component } from "react";
export default class CharComponent extends Component {
render() {
const style = {
display: "inline-block",
padding: "16px",
textAlign: "center",
margin: "16px",
border: "1px solid black"
};
return (
<div style={style} onClick={this.props.removeAll}>
<h3>{this.props.character} </h3>
</div>
);
}
}
deleteCharacter = index => {
let text = this.state.value.split("");
text.splice(index, 1);
let updatedText = text.join("");
this.setState({
value: updatedText
});
};
const useStyle = makeStyles(theme => ({
root: {
padding: theme.spacing(3, 2)
}
}));
const UserInput = props => {
const paraStyle = {
"@media (min-width: 500px)": {
width: "450px"
}
};
const Classes = useStyle();
return (
<Paper className={Classes.root}>
<h1 style={paraStyle} variant="h3" onClick={props.clicked}>
{props.name}
</h1>
<Typography variant="caption">My Age is : {props.age}</Typography>
</Paper>
);
};
export default Radium(UserInput);
//#Day23 #november23 #365CodingPhaseChallenge #ma9Code #ma9 #codeOfTheDay #ErrorBoundaryToPreventFromCrash
import React, { Component } from "react";
export default class ErrorBoundary extends Component {
state = {
hasError: false,
errorMessage: ""
};
componentDidCatch = (error, info) => {
this.setState({
hasError: true,
errorMessage: error
});
};
render() {
if (this.state.hasError) {
return <div>{this.state.errorMessage}</div>;
} else {
return <div>{this.props.children}</div>;
}
}
}
// #Day24 #november24 #365CodingPhaseChallenge #ma9Code #ma9 #codeOfTheDay #AuthorizationUsingContextAPIs
import React from "react";
import AuthContext from "../auth-context";
class Login extends React.Component {
static contextType = AuthContext;
componentDidMount() {
console.log(this.context);
}
render() {
return (
<button onClick={this.context.toggleAuth}>
{this.context.isAuth ? "Logout" : "Login"}
</button>
);
}
}
export default Login;
// #Day25 #november25 #365CodingPhaseChallenge #ma9Code #ma9 #codeOfTheDay #SplitingTheReactAppWithCockpit
import React from "react";
import CSSClass from "../Containers/App.css";
import { Button } from "@material-ui/core";
const cockpit = props => {
let classes = [];
if (props.length < 3) {
classes.push(CSSClass.red);
}
if (props.length < 2) {
classes.push(CSSClass.bold);
}
if (props.length < 1) {
classes.push(CSSClass.bolder);
}
return (
<div>
<p className={classes.join(" ")}>Welcome To React</p>
<Button
variant="outlined"
color="inherit"
onClick={props.clicked}
style={props.style}
>
{props.buttonText} Component
</Button>
</div>
);
};
export default cockpit;
React.useEffect(() => {
console.log("[Cockpit.js] useEffect");
const timer = setTimeout(() => {
alert("Save Data To Cloud !!!");
}, 1000);
return () => {
clearTimeout(timer);
console.log("[Cockpit.js] Cleaning Up with React Hooks");
};
}, []);
// #Day27 #november27 #365CodingPhaseChallenge #ma9Code #ma9 #codeOfTheDay #AppOptimizationUsingShouldComponentUpdate
shouldComponentUpdate(nextProps, nextState) {
console.log("[Persons.js] shouldComponentUpdate");
if (nextProps.person !== this.props.person) {
return true;
// This will allow to Re-render Person Component
} else {
return false;
// This will never Re-render Person Component to Optimize The Speed
}
}
// ArmStrong Numbers are 0,1, 153, 370, 371 and 407
let n = 153;
let r,
temp,
sum = 0;
temp = n;
while (n > 0) {
r = n % 10;
sum = sum + r * r * r;
n = Math.floor(n / 10);
}
if (temp == sum) {
console.log('ArmStrong Number');
} else {
console.log('Non ArmStrong Number');
}
const router = require('express').Router();
const { check, validationResult } = require('express-validator');
const User = require('../../models/User');
const gravater = require('gravatar');
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');
// @route POST api/users
// @desc test Users
// @access public
router.post(
'/',
[
check('name', 'Please Enter a Name').notEmpty(),
check('email', 'Invalid Email').isEmail(),
check(
'password',
'Please enter password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
error: errors.array()
});
}
const { name, email, password } = req.body;
try {
// See if User Exists
let user = await User.findOne({ email: email });
if (user) {
return res.status(400).json([
{
msg: 'User Already Exists'
}
]);
}
// Get Users Gravatar
const avatar = gravater.url(email, {
s: '200',
r: 'pg',
d: 'mm'
});
user = new User({
name,
email,
avatar,
password
});
// Password Encryption
const Salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, Salt);
await user.save();
// Return JSON Web Token
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 3600 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
// #Day3 #november3 #365CodingPhaseChallenge #ma9Code #ma9 #PopulateQueryInMongoose
// .populate('product','name price')
router.get("/", (req, res, next) => {
Orders.find()
.select("_id product quantity")
.populate('product','name price')
.exec()
.then(result => {
res.status(200).json({
message: "All Products",
totalOrders: result.length,
Orders: result.map(docs => {
return {
_id: docs._id,
product: docs.product,
quantity: docs.quantity,
request: {
type: "GET",
url: "http://localhost:3000/orders/" + docs._id
}
};
})
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = (req, res, next) => {
const token = req.header('x-auth-token');
if (!token) {
return res.status(401).json({
msg: 'Token Not Found, Authorization Denied'
});
}
try {
const decoded = jwt.verify(token, config.get('jwtSecret'));
req.user = decoded.user;
next();
} catch (error) {
console.error(error.message);
res.status(401).json({
msg: 'Token is Not Valid'
});
}
};
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
password2: ''
});
const { name, email, password, password2 } = formData;
const onChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
try {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify(newUser);
const res = await axios.post('/api/users', body, config);
console.log(res);
} catch (err) {
console.error(err.message);
}
import { REGISTER_SUCCESS, REGISTER_FAIL } from '../actions/types';
import axios from 'axios';
import { setAlert } from './alert';
export const register = ({ name, email, password }) => async (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ name, email, password });
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
dispatch(setAlert('User Created', 'success'));
} catch (err) {
const errors = err.response.data.error;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
// console.log(err.response.data.error);
dispatch({
type: REGISTER_FAIL
});
}
};
import React, { useEffect, Fragment } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { getCurrentProfile } from '../../actions/profile';
import Spinner from '../layouts/Spinner';
const Dashboard = ({
getCurrentProfile,
auth: { user },
profile: { profile, loading }
}) => {
useEffect(() => {
getCurrentProfile();
}, []);
return loading && profile === null ? (
<Spinner />
) : (
<Fragment>
<h1 className='large text-primary'>Dashboard</h1>
<p className='lead'>
<i className='fas fa-user' /> Welcome {user && user.name}
</p>
<p>
{profile !== null ? (
<Fragment>has</Fragment>
) : (
<Fragment>
You have not setup Profile yet, Please add some info
<br />
<Link to='/create-profile' className='btn btn-primary my-1'>
Create Profile
</Link>
</Fragment>
)}
</p>
</Fragment>
);
};
Dashboard.propTypes = {
auth: PropTypes.object.isRequired,
profile: PropTypes.object.isRequired,
getCurrentProfile: PropTypes.func.isRequired
};
const mapStateToProps = (state) => ({
auth: state.auth,
profile: state.profile
});
export default connect(mapStateToProps, { getCurrentProfile })(Dashboard);
useEffect(() => {
getCurrentProfile();
setFormData({
company: loading || !profile.company ? '' : profile.company,
website: loading || !profile.website ? '' : profile.website,
location: loading || !profile.location ? '' : profile.location,
status: loading || !profile.status ? '' : profile.status,
skills: loading || !profile.skills ? '' : profile.skills.join(','),
githubusername:
loading || !profile.githubusername ? '' : profile.githubusername,
bio: loading || !profile.bio ? '' : profile.bio,
twitter: loading || !profile.social ? '' : profile.social.twitter,
facebook: loading || !profile.social ? '' : profile.social.facebook,
instagram: loading || !profile.social ? '' : profile.social.instagram,
linkedin: loading || !profile.social ? '' : profile.social.linkedin,
youtube: loading || !profile.social ? '' : profile.social.youtube
});
});
const toggleCurrent = (e) => {
setFormData({
...formData,
current: e.target.checked
});
};
{!loading && (
<Fragment>{isAuthenticated ? authLinks : guestLinks}</Fragment>
)}
// Delete Profile and Account
export const deleteAccount = () => async (dispatch) => {
if (
window.confirm(
'Are you sure? Because this is not "DELETE" this is "SHIFT + DELETE "'
)
) {
try {
const res = await axios.delete('/api/profile');
dispatch({ type: UPDATE_PROFILE });
dispatch({ type: ACCOUNT_DELETED });
dispatch(setAlert('Account Deleted Permanently', true, 1500));
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, false, 5000)));
}
// console.log(err.response.data.errors);
dispatch({
type: PROFILE_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status
}
});
}
}
};
import {
GET_PROFILE,
GET_PROFILES,
PROFILE_ERROR,
CLEAR_PROFILE,
UPDATE_PROFILE,
GET_REPOS
} from '../actions/types';
const initialState = {
profile: null,
profiles: [],
repos: [],
loading: true,
error: {}
};
export default function(state = initialState, actions) {
const { type, payload } = actions;
switch (type) {
case GET_PROFILE:
case UPDATE_PROFILE:
return {
...state,
profile: payload,
loading: false
};
case GET_PROFILES:
return {
...state,
profiles: payload,
loading: false
};
case PROFILE_ERROR:
return {
...state,
error: payload,
loading: false
};
case CLEAR_PROFILE:
return {
...state,
profile: null,
repos: [],
loading: false
};
case GET_REPOS:
return {
...state,
repos: payload,
loading: false
};
default:
return state;
}
}
// #Day4 #november4 #365CodingPhaseChallenge #ma9Code #ma9 #productUploadLogicUsingMulter
// ====== File Upload Using Multer ======================
const multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "./uploads/");
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
import axios from 'axios';
const setAuthToken = (token) => {
if (token) {
axios.defaults.headers.common['x-auth-token'] = token;
} else {
delete axios.defaults.headers.common['x-auth-token'];
}
};
export default setAuthToken;
// Add New Post
export const addPost = (formdata) => async (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
try {
const res = await axios.post(`/api/posts`, formdata, config);
dispatch({
type: ADD_POST,
payload: res.data
});
dispatch(setAlert('Post Created', true, 2500));
} catch (err) {
dispatch({
type: POST_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status
}
});
}
};
// Add like
export const addLike = (id) => async (dispatch) => {
try {
const res = await axios.put(`/api/posts/likes/${id}`);
dispatch({
type: UPDATE_LIKES,
payload: { id, likes: res.data }
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status
}
});
}
};
// Remove like
export const removeLike = (id) => async (dispatch) => {
try {
const res = await axios.put(`/api/posts/unlikes/${id}`);
dispatch({
type: UPDATE_LIKES,
payload: { id, likes: res.data }
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status
}
});
}
};
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Word Generator'),
backgroundColor: Colors.red[900],
)));
}
}
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
class RandomWords extends StatefulWidget {
@override
RandomWordState createState() => RandomWordState();
}
class RandomWordState extends State<RandomWords> {
final _randomWordGenerator = <WordPair>[];
final _savedWordPairs = Set<WordPair>();
Widget _buildList() {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, item) {
if (item.isOdd) return Divider();
final index = item ~/ 2;
if (index >= _randomWordGenerator.length) {
_randomWordGenerator.addAll(generateWordPairs().take(10));
}
return _buildRow(_randomWordGenerator[index]);
});
}
Widget _buildRow(WordPair pair) {
final alreadySaved = _savedWordPairs.contains(pair);
return ListTile(
title: Text(
pair.asPascalCase,
style: TextStyle(fontSize: 20),
),
trailing: Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.redAccent[400] : null,
),
onTap: () {
setState(() {
if (alreadySaved) {
_savedWordPairs.remove(pair);
} else {
_savedWordPairs.add(pair);
}
});
},
);
}
void _pushSaved() {
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
final Iterable<ListTile> tiles = _savedWordPairs.map((WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: TextStyle(fontSize: 20),
),
);
});
final List<Widget> divided =
ListTile.divideTiles(context: context, tiles: tiles).toList();
return Scaffold(
appBar: AppBar(
title: Text('Saved WordPairs'),
),
body: ListView(children: divided));
}));
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('WordPair Generator'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.list),
onPressed: _pushSaved,
)
],
),
body: _buildList(),
);
}
}
import React from 'react';
import { Grid } from '@material-ui/core';
import LeftPane from './LeftPane';
import RightPane from './RightPane';
const Styles = {
Paper: {
padding: 20,
marginTop: 10,
marginBottom: 10
}
};
export default () => (
<Grid container>
<Grid item xs>
<LeftPane Styles={Styles} />
</Grid>
<Grid item xs>
<RightPane Styles={Styles} />
</Grid>
</Grid>
);
export const muscles = ['shoulders', 'chest', 'arms', 'back', 'legs'];
export const exercises = [
{
id: 'overhead-press',
title: 'Overhead Press',
description: 'Delts exercise...',
muscles: 'shoulders'
},
{
id: 'dips',
title: 'Dips',
description: 'Triceps exercise...',
muscles: 'arms'
},
{
id: 'barbell-curls',
title: 'Barbell Curls',
description: 'Biceps exercise...',
muscles: 'arms'
},
{
id: 'bench-press',
title: 'Bench Press',
description: 'Chest exercise...',
muscles: 'chest'
},
{
id: 'pull-ups',
title: 'Pull Ups',
description: 'Back and biceps exercise...',
muscles: 'back'
},
{
id: 'deadlifts',
title: 'Deadlifts',
description: 'Back and leg exercise...',
muscles: 'back'
},
{
id: 'squats',
title: 'Squats',
description: 'Legs exercise...',
muscles: 'legs'
}
];
getExerciseByMuscles = () => {
return Object.entries(
this.state.exercises.reduce((exercises, exercise) => {
const { muscles } = exercise;
exercises[muscles] = exercises[muscles]
? [...exercises[muscles], exercise]
: [exercise];
return exercises;
}, {})
);
};
handleExerciseCreate = exercise => {
this.setState(({ exercises }) => ({
exercises: [...exercises, exercise]
}));
};
handleCategorySelect = category => {
this.setState({
category
});
};
handleExerciseSelect = id => {
this.setState(({ exercises }) => ({
exercise: exercises.find(ex => ex.id === id)
}));
};
return Object.entries(
this.state.exercises.reduce((exercises, exercise) => {
const { muscles } = exercise;
exercises[muscles] = [...exercises[muscles], exercise];
return exercises;
}, initExercises)
);
const dotenv = require('dotenv')
// ======================== Reading .env Variables ===============
dotenv.config()
// ================== Generating Date in dd/mm/yyyy format =======
// Adding User Login and JWT (JSON Web Token) Generated
const myDate = new Date().getUTCDate()
const myMonth = new Date().getUTCMonth() + 1
const myYear = new Date().getUTCFullYear()
const date = myDate.toString()
const month = myMonth.toString()
const year = myYear.toString()
const fullDate = date + '-' + month + '-' + year
// ===================== Exporting Credentials =========================
module.exports = {
databaseUsername: process.env.DB_USERNAME,
databasePWD: process.env.DB_PWD,
port: process.env.PORT || 3000,
JWT_KEY: process.env.JWT_KEY,
todaysDate: fullDate
}
const theme = createMuiTheme({
palette: {
primary: {
main: orange.A400,
light: orange[300],
dark: orange[900]
},
secondary: {
main: '#323648' // Dodge Blue
},
type: 'dark'
},
spacing: 10
});
import React from 'react';
import { AppBar, Tabs, Tab, withWidth } from '@material-ui/core';
export default withWidth()(({ muscles, category, onSelect, width }) => {
const index = category
? muscles.findIndex(muscle => muscle === category) + 1
: 0;
const handleIndexSelect = (e, index) => {
onSelect(index === 0 ? '' : muscles[index - 1]);
};
if (width === 'xs' || width === 'sm') {
return (
<AppBar color="secondary" position="static">
<Tabs
indicatorColor="primary"
onChange={handleIndexSelect}
value={index}
textColor="primary"
variant="scrollable"
scrollButtons="on"
>
<Tab label="ALL" />
{muscles.map(muscle => (
<Tab key={muscle} label={muscle} />
))}
</Tabs>
</AppBar>
);
}
if (width !== 'xs' || width !== 'sm') {
return (
<AppBar color="secondary" position="static">
<Tabs
indicatorColor="primary"
onChange={handleIndexSelect}
value={index}
textColor="primary"
centered
>
<Tab label="ALL" />
{muscles.map(muscle => (
<Tab key={muscle} label={muscle} />
))}
</Tabs>
</AppBar>
);
}
});
import React from 'react';
export const { Provider, Consumer } = React.createContext();
export const withContext = (Component) => (props) => (
<Consumer>{(value) => <Component {...value} {...props} />}</Consumer>
);
import React, { Fragment, Component, createContext } from 'react';
import {
Fab,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
Tooltip
} from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
import Form from './Form';
import { withContext } from '../../Context';
class CreateDialog extends Component {
state = {
open: false
};
handleToggle = () => {
this.setState({
open: !this.state.open
});
};
handleFormSubmit = (exercise) => {
this.handleToggle();
this.props.onCreate(exercise);
};
render() {
const { open } = this.state,
{ muscles } = this.props;
return (
<Fragment>
<Tooltip title='Add New Exercise' placement='left'>
<Fab color='primary' onClick={this.handleToggle} size='small'>
<AddIcon />
</Fab>
</Tooltip>
<Dialog open={open} onClose={this.handleToggle}>
<DialogTitle>Create a New Exercise</DialogTitle>
<DialogContent>
<DialogContentText>
Please Fill out the form below
</DialogContentText>
<Form muscles={muscles} onSubmit={this.handleFormSubmit} />
</DialogContent>
</Dialog>
</Fragment>
);
}
}
export default withContext(CreateDialog);
// JWT Route Protection using CheckAuth (Customized JWT Protection)
const jwt = require("jsonwebtoken");
const { JWT_KEY } = require("../../config/config");
module.exports = (req, res, next) => {
try {
const jwtToken = req.headers.authorization;
const token = jwtToken.substr(7);
const decoded = jwt.verify(token, JWT_KEY);
req.userData = decoded;
next();
} catch (error) {
return res.status(401).json({
message: "Auth Failed"
});
}
};
// Addding Controller to the Services
// ============= Importing Dependencies ==============
const router = require("express").Router();
const { todaysDate } = require("../../config/config");
const checkAuth = require("../middleware/check-auth");
const productController = require("../controllers/product");
// ====== File Upload Using Multer ======================
const multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "./uploads/");
},
filename: function(req, file, cb) {
cb(
null,
todaysDate + " " + new Date().getSeconds() + " " + file.originalname
);
}
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === "image/jpeg" ||
file.mimetype === "image/png" ||
file.mimetype === "image/jpg"
) {
cb(null, true);
} else {
cb(
new Error(
" Invalid File Type : Please Upload only JPEG,JPG or PNG files "
),
false
);
}
};
var upload = multer({
fileFilter: fileFilter,
storage: storage,
limits: { fileSize: 1024 * 1024 * 10 }
});
// ================= Handling Requests =============
router.get("/", productController.getAllProducts);
router.post(
"/",
checkAuth,
upload.single("productImage"),
productController.postNewProduct
);
router.get("/:ProductID", productController.getParticularProduct);
router.patch("/:ProductID", checkAuth, productController.patchProduct);
router.delete("/:ProductID", checkAuth, productController.deleteProduct);
// ================ Exporting Router =====================
module.exports = router;
// First Component of this Burger Builder
import React from "react";
import "./App.css";
function App() {
return (
<div className="App">
<h1> Hi I'm Going to Create App </h1>
<p> Visit me Daily </p>
</div>
);
}
export default App;
// #Day9 #november9 #365CodingPhaseChallenge #ma9Code #ma9 #UsingMaterialUI
<Paper className={Classes.root}>
<Typography variant="h3">{props.name}</Typography>
<Typography variant="caption">My Age is : {props.age}</Typography>
</Paper>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment