-
npm init
-
create -> /src/appp.js & /src/index.js
-
npm i express mongoose dotenv
-
.gitignore -> create and also do git works (optional)
-
update index.js -
goto - https://mongoosejs.com/ goto - https://mongoosejs.com/docs/connections.html#error-handling mongoose connection
(async () => {
try {
await mongoose.connect('');
} catch (err) {
console.error("ERROR: ", err)
throw err
}
})()
- check express is connected with mongoDB -
app.on("error", (err) => {
console.log("ERROR: ", err);
throw err;
});
// listening here
const onListening = () => {
console.log("Listening on port ", process.env.PORT);
};
app.listen(process.env.PORT, onListening);
-
create .env -> for envirnment variables -
check .env
-
create /src/config/index.js -> for configuration in one place and export that so we can use it anywhere on our project -
-
create /src/utils/AuthRoles.js -> for user roles which we can access from anywhere
-
create /src/models/collection.schema.js -> for collection schema
-
create /src/models/user.schema.js -> for user schema
-
encryption of password - install bcryptjs for encryption purpose -
import bcrypt from "bcryptjs";
..
..
userSchema.pre("save", async function (params) {
if (this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 10);
next()
});
- Provide methods - for checking or updating things under DB before update or after update ->
- Comparing password -
comparePassword: async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
}
- Now we need to generate token if all things correct and password matched ->
-
-
-
Usage read docs -
jwt.sign(payload, secretOrPrivateKey, [options, callback])
-
- add to .env
JWT_SECRET=mysecret
JWT_EXPIRY=7d
- update src/config/index.js we need to use this values -
JWT_SECRET: process.env.JWT_SECRET || "mysecret",
JWT_EXPIRY: process.env.JWT_EXPIRY || "10d",
- update src/models/user.schema.js add method for JWT -
import JWT from "jsonwebtoken"
import config from "../config/index"
import crypto from "crypto";
...
...
// method - generate JWT token
getJWTToken: async function () {
JWT.sign({ _id: this._id }, config.JWT_SECRET, {
expiresIn: config.JWT_EXPIRY,
});
},
- add method - generateForgotPasswordToken and expiry
// method - generate forgot password token
generateForgotPasswordToken: function () {
// generating random token string
const forgotToken = crypto.randomBytes(20).toString("hex");
// encrypting string generated by crypto
this.forgotPasswordToken = crypto
.createHash("sha256")
.update(forgotToken)
.digest("hex");
// time for token to expire - 20min here
this.forgotPasswordExpiry = Date.now() + 20 * 60 * 1000;
// don't forgot to return - forgotToken
return forgotToken;
},
-
Create product schema -
-
Create order Schema alongwith orderStatus -
note - there is multiple websites for make models(they can be paid) like - moon modeler (datensen.com)
-
Create coupon schema -
-
Create asynchandler - which is an HOF with try catch(for run to all DB things) -
const asyncHandler = (fn) => async (req, res, next) => {
try {
await fn(req, res, next);
} catch (error) {
res.status(error.code || 500).json({
success: false,
message: error.message,
});
}
};
export default asyncHandler;
-
Added function for customError -
-
we need to configure express for different methods and data to use -
goto - src/app.js , because this configurations added under that
-
different type of data like - json (this method is given by express)
app.use(express.json());
-
urlEncode method - (for accepting urlencoded data)
app.use(express.urlencoded({ extended: true }));
-
CORS configure - (for cross origin resource sharing)
-
app.use(cors())
-
cookie parser - with this package we can access users browsers cookies
-
app.use(cookieParser());
-
Started Controller methods from here - signup -
-
login -
-
signout -
-
logout -
-
getProfile -
-
Middlewares - for authentication - isLoggedIn , authorize
-
Controllers for collection - create, update, delete, get, getAll
-
Moving for uploading other file types rather than text or json (image, video, pdf etc)
- S3 - configuration (.env s3 secret and bucket added)
-
Create image upload service -
-
Now we need a srvice for upload media files because express not support direct upload -
-
-
Formidable - npm - we are using this in this project
-
-
Formidable - files uploader (used in this project)
-
Added product controllers -
-
Method has been added are - addProduct, getAllProducts, getProduct, getProductsByCollectionId, deleteProduct
-
TODO - updateProduct
-
Work on routes -
- Created coupon controller - create, get, getAll, update, delete
- We need to use mailing services sometime - like mail for forgot password or order related mail(for that we need to test mail or debug email things on development time) - some services are here
Professinal services to use
-
aws (mailing services)
-
mailchimp
-
sendinblue
for testing mail services we can use
-
goto - https://mailtrap.io/ - (we are using this)
Module for nodejs application to send email
-
Create mailHelper.js - (responsible for sending mail, creating it as universal service, whereever we need to send email just pass parameter and suit the email) - login on mailHelper and then use credentials given
-
Updated config/index.js -
-
Created transporter for mailing service -
-
created mailHelper - (for handle to all mailing things) -
- Created forgotPassword controller - under auth.controller which will use this mailing service