Xây dựng một RESTful API dễ dàng debug, dễ dàng maintain, dễ dàng scale sử dụng NodeJS (Phần 1 sử dụng boilerplate) 5/5 (1)

Hôm nay rảnh rỗi, ngồi chia sẻ với các bạn về việc Xây dựng một RESTful API dễ dàng debug, dễ dàng maintain, dễ dàng scale sử dụng NodeJS. Nói qua về dự án thực tế của công ty mình. Hiện tại trong services của bọn mình có một service  vô cùng quan trọng là Chat Services. Hiện tại số lượng users của hệ thống là khá lớn (hơn 600k users, tại thời điểm viết blog này) và hơn 50k users dùng thường xuyên. Do trong hệ thống 1 user có thể match made với nhiều user, hiện tại Chat Service đang phải quản lý hơn 5 triệu rooms & hơn 30 triệu messages. bài toán là thiết kế Chat service để các user có thể tương tác với nhau mượt mà. Và quan trọng nhất là dễ bảo trì, maintain trong tương lai.

Ứng dụng của bọn mình được xây dựng dựa trên một boilerplate application khá là có tiếng trên github:  https://github.com/kunalkapadia/express-mongoose-es6-rest-api Bạn có thể sử dụng thoải mái chỉ cần đề cập đến copyright & license noticed https://github.com/kunalkapadia/express-mongoose-es6-rest-api/blob/develop/LICENSE 

Tổng quan

Đây là một ứng dụng soạn sẵn (boilerplate) để xây dựng các API REST trong Node.js sử dụng ES6 và Express với Code Coverage và Xác thực JWT. Giúp bạn luôn tăng năng suất (productive), chất lượng code bằng cách follow theo các phương pháp hay nhất (Best Practice). Theo hướng dẫn về phong cách Javascript của Airbnb .

Lấy cảm hứng từ Egghead.io – Cách viết Thư viện JavaScript mã nguồn mở

Tính năng, đặc điểm

Feature Summary
ES6 via Babel ES6 support using Babel.
Authentication via JsonWebToken Supports authentication using jsonwebtoken.
Code Linting JavaScript code linting is done using ESLint – a pluggable linter tool for identifying and reporting on patterns in JavaScript. Uses ESLint with eslint-config-airbnb, which tries to follow the Airbnb JavaScript style guide.
Auto server restart Restart the server using nodemon in real-time anytime an edit is made, with babel compilation and eslint.
ES6 Code Coverage via istanbul Supports code coverage of ES6 code using istanbul and mocha. Code coverage reports are saved in coverage/ directory post yarn test execution. Open coverage/lcov-report/index.html to view coverage report. yarn test also displays code coverage summary on console. Code coverage can also be enforced overall and per file as well, configured via .istanbul.yml
Debugging via debug Instead of inserting and deleting console.log you can replace it with the debug function and just leave it there. You can then selectively debug portions of your code by setting DEBUG env variable. If DEBUG env variable is not set, nothing is displayed to the console.
Promisified Code via bluebird We love promise, don’t we ? All our code is promisified and even so our tests via supertest-as-promised.
API parameter validation via express-validation Validate body, params, query, headers and cookies of a request (via middleware) and return a response with errors; if any of the configured validation rules fail. You won’t anymore need to make your route handler dirty with such validations.
Pre-commit hooks Runs lint and tests before any commit is made locally, making sure that only tested and quality code is committed
Secure app via helmet Helmet helps secure Express apps by setting various HTTP headers.
Uses yarn over npm Uses new released yarn package manager by facebook. You can read more about it here
  • Hỗ trợ CORS qua cors
  • Sử dụng status http để đặt mã trạng thái http. Bạn nên sử dụng httpStatus.INTERNAL_SERVER_ERRORthay vì sử dụng trực tiếp 500khi đặt mã trạng thái.
  • Có .editorconfiggiúp các nhà phát triển xác định và duy trì phong cách mã hóa phù hợp giữa biên tập viên và IDE khác nhau.

Getting Started

Clone the repo:

git clone git@github.com:kunalkapadia/express-mongoose-es6-rest-api.git
cd express-mongoose-es6-rest-api

Install yarn:

npm install -g yarn

Install dependencies:

yarn

Set environment (vars):

cp .env.example .env

Start server:

# Start server
yarn start

# Selectively set DEBUG env var to get logs
DEBUG=express-mongoose-es6-rest-api:* yarn start

Refer debug to know how to selectively turn on logs.

Tests:

# Run tests written in ES6 
yarn test

# Run test along with code coverage
yarn test:coverage

# Run tests on file change
yarn test:watch

# Run tests enforcing code coverage (configured via .istanbul.yml)
yarn test:check-coverage

Lint:

# Lint code with ESLint
yarn lint

# Run lint on any file change
yarn lint:watch

Other gulp tasks:

# Wipe out dist and coverage directory
gulp clean

# Default task: Wipes out dist and coverage directory. Compiles using babel.
gulp
Deployment
# compile to ES5
1. yarn build

# upload dist/ to your server
2. scp -rp dist/ user@dest:/path

# install production dependencies only
3. yarn --production

# Use any process manager to start your services
4. pm2 start dist/index.js

Mình chỉ copy paste nhanh một số thông tin từ trang github của boilerplate này, các bạn có thể xem thêm chi tiết ở link cung cấp bên trên.

Trên đây là tổng hợp lại một số kinh nghiệm & kiến thức của Mình  trong việc sử dụng một noide js boilerplate có sẵn để custom, xây dựng lên Chat Service. Bài này tạm dừng ở đây, ở các bài tiếp mình sẽ đi sâu và structure của hệ thống, demo một số best practice mình đang dùng trong hệ thống thực như.

  1. Tương tác với databases (MongoDB, Casandra)
  2. Validation cho param, data input
  3. Tạo một Event hub (tương tự SQL của amazon) sử dụng Redis
  4. Migration data từ mongo => Mongo, Mongo => cassandra với dữ liệu hơn 30 triệu records

Trong quá trình hệ thống lại kinh nghiệm và kiến thức không tránh khỏi những sai sót, Rất mong các bạn đọc đóng góp ý kiến để Mình càng ngày càng hoàn thiện hơn bài viết. Bài viết được tham khảo từ một số nguồn dưới đây:

https://github.com/kunalkapadia/express-mongoose-es6-rest-api 

Cám ơn các bạn đã quan tâm và đọc đến tận đây <3 <3 <3

Nếu bạn cảm thấy bài viết này hay và hữu ích thì hãy Like, Share & Subscribe techblog của bọn mình nhé 😀 😀

Please follow and like us:

Please rate this

You May Also Like

About the Author: duong

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *