/Backend_FSJS

Learning once again backend form fsjs

Primary LanguageJavaScript

All process goes here -

  1. npm init

  2. create -> /src/appp.js & /src/index.js

  3. npm i express mongoose dotenv

  4. .gitignore -> create and also do git works (optional)

  5. 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
    }
})()
  1. 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);
  1. create .env -> for envirnment variables -

    check .env

  2. create /src/config/index.js -> for configuration in one place and export that so we can use it anywhere on our project -

    Goto - src/config/index.js

  3. create /src/utils/AuthRoles.js -> for user roles which we can access from anywhere

    goto - src/utils/AuthRoles.js

  4. create /src/models/collection.schema.js -> for collection schema

    go to - /src/models/collection.schema.js

  5. create /src/models/user.schema.js -> for user schema

    goto - /src/models/user.schema.js

  6. 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()
});
  1. Provide methods - for checking or updating things under DB before update or after update ->

    goto site for schema.prototype

  • Comparing password -
comparePassword: async function (enteredPassword) {
    return await bcrypt.compare(enteredPassword, this.password);
  }
  1. Now we need to generate token if all things correct and password matched ->
  • 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;
},
  1. Create product schema -

    goto file - src/models/product.schema.js

  2. Create order Schema alongwith orderStatus -

note - there is multiple websites for make models(they can be paid) like - moon modeler (datensen.com)

  1. Create coupon schema -

    goto file - src/models/coupon.schema.js

  2. Create asynchandler - which is an HOF with try catch(for run to all DB things) -

    goto file - src/service/asyncHandler.js

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;
  1. Added function for customError -

    got file - src/utils/customError.js

  2. 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

    goto - cookie-parser-npm

  • app.use(cookieParser());

  1. Started Controller methods from here - signup -

    goto signup - src/controllers/auth.controller.js

  2. login -

    goto - src/controllers/auth.controller.js

  3. signout -

    goto - src/controllers/auth.controller.js

  4. logout -

    goto - src/controllers/auth.controller.js

  5. getProfile -

    goto - src/controllers/auth.controller.js

  6. Middlewares - for authentication - isLoggedIn , authorize

    goto - src/middlewares/auth.middleware.js

  7. Controllers for collection - create, update, delete, get, getAll

    goto - src/controllers/collection.controler.js

  8. Moving for uploading other file types rather than text or json (image, video, pdf etc)

  1. S3 - configuration (.env s3 secret and bucket added)
  1. Create image upload service -

    goto - src/service/imageUpload.js

  2. Now we need a srvice for upload media files because express not support direct upload -

  1. Formidable - files uploader (used in this project)

    Formidable - npm

  2. Added product controllers -

    goto - product.controller.js

  3. Method has been added are - addProduct, getAllProducts, getProduct, getProductsByCollectionId, deleteProduct

  4. TODO - updateProduct

  5. Work on routes -

  1. Created coupon controller - create, get, getAll, update, delete

goto - src/controllers/coupon.controller.js

  1. 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

Module for nodejs application to send email

  1. 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

  2. Updated config/index.js -

goto - src/config/index.js

  1. Created transporter for mailing service -

    goto - transporter

  2. created mailHelper - (for handle to all mailing things) -

goto - src/utils/mailHelper.js

  1. Created forgotPassword controller - under auth.controller which will use this mailing service

goto - src/controllers/auth.controller.js