Một thủ thuật nhỏ để tối ưu code nodejs

8700

Bài viết được sự cho phép của tác giả Phạm Công Sơn

Tôi code web asp.net c# đã lâu năm rồi, giờ có nhiều framework mới, công nghệ mới nên đôi khi cũng chưa có cơ hội để trải qua. Dù sao cũng là tầng lớp già rồi, khó có thời gian học được cái mới. Chính vì vậy, lựa chọn chơi với các bạn trẻ cũng là một cách học hỏi. Bạn trẻ thì có kiến thức mới nhưng lại thiếu kinh nghiệm. Mình già rồi có kinh nghiệm nhưng lại thiếu kiến thức mới. Già, trẻ chơi với nhau chắc chắn sẽ có bù đắp qua lại. Qua đó mà học hỏi đôi bên với nhau.

Tuyển dụng NodeJS lương cao hấp dẫn cho bạn

  Mẫu bảng mô tả công việc lập trình NodeJS

Hôm nay thằng cu em cho xem project code bằng nodejs. Có đọc qua vài file controller thì thấy một điều thế này. Đúng là hầu hết các bạn trẻ code static quá nhiều và hơn nữa là copy code đã thành tư tưởng cố hữu. Code cứ dài lê thê mà không đóng gói lại thành hàm, thành đối tượng để tái sử dụng lại. Điều mà tôi có nói tới trong bài viết Tại sao code của tôi thường ngắn gọn như vậy.

Đây là file controller history.js mà tôi đã đọc của thằng cu em.

const History = require("../services/history");
const { handleResponse, handleError } = require("../helpers/responseHandler");

const getHistoriesByBet = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.getHistoriesByBet(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

const getHistories = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.getHistories(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

const getBalance = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.getBalance(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

const createHistory = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.createHistory(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

const createWithdrawHistory = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.createWithdrawHistory(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

const getWithdraws = async (request, response, next) => {
  // console.log('request.body',request.body);
  return History.getWithdraws(request.body)
    .then((result) => handleResponse({ result, response }))
    .catch((error) => next(handleError({ error, response })));
};

module.exports = {
  getHistories,
  getBalance,
  createHistory,
  getHistoriesByBet,
  createWithdrawHistory,
  getWithdraws
};

Ở đây có thể hiểu là các hàm api ở controller sẽ gọi đến tầng lấy data để gửi xuống client. Nhưng mà có thể thấy. các hàm getHistoriesgetBalancecreateHistorygetHistoriesByBet,   createWithdrawHistorygetWithdraws cũng cùng một dạng mà copy đi copy lại.

Chính vì vậy mà tôi dù chưa code NodeJs nhưng cũng đã từng code javascript nên thêm một hàm getResponse như sau

class Controllers {
  //   constructor() {}

  constructor(service) {
    this.Service = service;
  }

  ////
  //// code code
  ////

  getResponse(method, request, response, next) {
    // console.log('request.body',request.body);
    const service = new this.Service();
    return service[method](request.body) // ddc ko ta?
      .then((result) => this.handleResponse({ result, response }))
      .catch((error) => next(this.handleError({ error, response })));
  }
}

Hàm getResponse trong đó có tham số method, còn Controller có thuộc tính this.Service. Và qua đó sẽ truy vấn this.Service thông qua key là method để lấy được hàm cần gọi. Và cuối cùng file History.js sẽ còn về được như sau

const History = require("../services/history");
const Controller = require("./Controllers");

class HistoryCtrl extends Controller
{
    constructor() { super(History) }

    getHistoriesByBet = async (request, response, next) => this.getResponse("getHistoriesByBet", request, response, next);
    getBalance = async (request, response, next) => this.getResponse("getBalance", request, response, next);
    createHistory = async (request, response, next) => this.getResponse("createHistory", request, response, next);
    getHistoriesByBet = async (request, response, next) => this.getResponse("getHistoriesByBet", request, response, next);
    createWithdrawHistory = async (request, response, next) => this.getResponse("createWithdrawHistory", request, response, next);
    getWithdraws = async (request, response, next) => this.getResponse("getWithdraws", request, response, next);
}

module.exports = HistoryCtrl;

Đơn giản vậy thui. Mà đã giảm đi phải tới 80% code ấy chứ. Chưa kể các file controller khác cũng tối ưu tương tự thì cũng một lượng code thừa tương đối được loại bỏ. Đây chỉ một trong rất nhỏ các thủ thuật để tối ưu code cho đơn giản và gọn gàng hơn. Còn nhiều thủ thuật khác mà gặp tùy từng tình huống thì tôi sẽ post để chia sẻ thêm.

Chúc các bạn code ngày càng tốt hơn

Bài viết gốc được đăng tải tại sonpc20.com

Có thể bạn quan tâm:

Xem thêm việc làm IT hấp dẫn tại TopDev