Building APIs with Node.js Examples
- Single-Thread Arquitecture
- Asynchronous programming: Non-Blocking IO
- Event Loop: Event-Oriented Paradigm: Responsible for noticing and triggering events
- Advantages
- Install node
-
Download from Node.js
- Linux
- MacOSX
- Windows
-
Installation via NVM
curl https://raw.githubusercontent.com/creationix/nvm/v0.3.2.1/install.sh | bash
nvm ls nvm ls-remote nvm install nvm uninstall nvm use nvm alias default
-
-
NPM
npm init npm install [-g] npm remove [-g] npm update [-g] npm list [-g] npm -v npm adduser npm whoami npm publish
-
Package.json: module attributes
- 3 levels of versioning
- Major
- Minor
- Patch
- 3 levels of versioning
-
Task Automation:
npm run <command>
-
Express Framework
- Views
- Controllers
- Routers
- Optional:
- ORMs
- ODMs
-
Characteristics
- Robust routing
- Easy integration to Template engines
- Minimalist code
- Easy Middleware Concept implementation
- Huge amount of readily available middleware
- Content negotiation
- Adopts REST API standards and best practices
-
ntask-api
npm init npm install —save-dev @babel/core @babel/cli @bable/preset-env package.json :: ‘start’: ‘node index.js’ npm install —save consign npm start
- SQLite3
- Sequelize
/libs/config.js
: line: 11: Params.operatorsAliases: false // Get rid of Warnings due to use of newest Sequelize versiondb.js
: Load DB configuration as Singleton connection to ensure connections is ONLY instantiate onceapp.js
: Alter the loading sequence to now include the DB connection to SQLIte3- Models: Users 1-N Tasks models/tasks.js and models/users.js
db.js
: Modify to read ALL model definitions undermodels/*.js
- Changes in newest Sequelize version impact
db.js
: line 28:db.models[key].options.classMethods.associate(db.models);
- Now EMPTY tasks results since we have not added (dummy) data
- Modify the
routes/tasks.js
to handle get, post, put, and delete- Refactor the
routes/tasks.js
moving theapp.all
function tolibs/middlewares.js
- Refactor the
- Create the
routes/users.js
to handle get, delete, and post - Test the task endpoints with Postman application
- Refactor replacing double quotes with single quotes on all applicable files
- Install Passport framework for user authentication:
npm install passport passport-jwt jwt-simple --save
- Create the
auth.js
middleware and add it to the boot sequence inindex.js
- Passport library change amends
auth.js
to change the following line to:jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')
- Passport library change amends
- Authentication is then initialize in
middlewares.js
- Install the encryption library:
npm install bcrypt --save
- Update
models/users.js
to encrypt the users password before storing itbeforeCreate
- Also, the
isPassword
will allow validating the supplied user password with the password already stored
- Also, the
- Create the
/token
endpoint inroutes/token.js
with the logic for suplying the JWT to be used - Update
routes/tasks.js
with the authentication verification adding the.all(app.auth.authenticate())
- Refactor
routes/users.js
to use.all(app.auth.authenticate())
and verify againstreq.user.id
- Move
libs/config.js
tolibs/config.development.js
then duplicate it aslibs/config.test.js
- Add to the
libs/config.test.js
thelogging: false
parameter
- Add to the
- Create the
libs/config.js
file for use of theprocess.env.NODE_ENV
variable - Install new development packages:
npm install babel-register mocha chai supertest --save-dev
- Update
package.json
with a new run scritp:"test": "NODE_ENV=test mocha test/**/*.js
- Update
index.js
withmodule.exports = app;
andconsign({ verbose: false })
- Update
libs/boot.js
to use theprocess.env.NODE_ENV
variable - Create
test/helpers.js
andtest/mocha.opts
- Create the first test
test/routes/index.js
- Execute the first test:
npm test
- Update
- Fixes due to used of latest
Sequelize
ORM- Now the
Tasks
modelassociate
attribute is redefined as:Tasks.associate
- The same goes for
Users
model attributess:Users.associate
andUsers.isPassowrd
- Now the
- Create
test/routes/tasks.js
andtest/routes/users.js
- Create test cases for GET, POST, PUT, and DELETE
- Fixes due to latest
Sequelize
ORM- Change deprecated
findById
to latestfindByPk
inroutes/tasks.js
androutes/users.js
- Fix
expected
clauses to useres.text
instead ofres.body
- Fix
- Add
passport.serializeUser
andpassport.deserializeUser
- Fix
find*
methods withwhere
clause, changinguser_id
toUserId
- Change deprecated
- Install
npm install apidoc --save-dev
- Update
package.json
to add the apidoc command - Create
public/
folder and updatemiddleware.js
- Add APIdoc on API implementations
- Install CORS middleware
npm install cors --save
- Initialize CORS updating
libs/middleware.js
- Initialize CORS updating
- Install
Winston
andMorgan
for log processingnpm install winston morgan --save
- Update
libs/config.development.js
andlibs/middlewares.js
- Change
new winston.Logger
tonew winston.createLogger
- Change
- Create Clusters middleware
clusters.js
- Update
package.json
with cluster script command
- Update
- Install GZIP middleware
npm install compression --save
- Update to HTTPS generating the self signed certificate
- Download the
.key
and.cert
, rename and put the files in the root directory - Update
libs/boot.js
to use the self signed credentials
- Download the
- Install HELMET
npm install helmet --save