$ npm init
$ npm init -y
$ npm start
"scripts": { "start": "node index.js",
$ npm run dev
"scripts": { "dev": "nodemon index.js",
Global Examples
$ sudo npm install -g nodemon
$ sudo npm install -g typescrypt
$ sudo npm install -g ts-node
$ sudo npm install -g express-generator
$ sudo npm install -g lite-server
Dependencies
$ npm install mustache-express
DevDependencies
$ npm install --save-dev @types/node
$ npm install --save-dev @types/mustache-express
$ npm install --save-dev @types/validator
$ npm install --save-dev @types/express
$ npm i -D @types/body-parser
$ sudo npm cache clean -f
$ sudo npm install -g n
$ sudo n stable
Enforce HTTPS in Express Localhost
sudo openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
sudo openssl rsa -in keytmp.pem -out key.pem
const fs = require ( 'fs' ) ;
const key = fs . readFileSync ( './key.pem' ) ;
const cert = fs . readFileSync ( './cert.pem' ) ;
const express = require ( 'express' )
const https = require ( 'https' ) ;
const app = express ( )
const server = https . createServer ( { key : key , cert : cert } , app ) ;
server . listen ( 8080 , ( ) => { console . log ( 'listening on 8080' ) } ) ;
HTTP
Express
CORS
Testing and Code Quality
.gitginore
Validator
Template Engine
Parser URL Encoded
Framework MVC
Authentication
Dates & Times
EMAIL SMTP
Slug
.env
Assets Compression
Security HTTP Headers
UUID
Query String
JSON-SERVER
Logging
FAKE DATA
Production
$ sudo npm install -g nodemon typescript ts-node
$ npm install --save-dev @types/express @types/mustache-express @types/node copyfiles
$ tsc --init
$ tsc -w (ficar monitorando typescript)
package.json
"scripts":
"start": "tsc ; nodemon ./dist/app",
tsconfig.json
"outDir": "./dist",
"rootDir": "./src",
"module": "commonjs",
"moduleResolution": "node"
nodemon.json
{
"restartable" : " rs" ,
"ignore" : [
" .git" ,
" dist" ,
" node_modules/**/node_modules"
],
"verbose" : true ,
"events" : {
"restart" : " osascript -e 'display notification \" App restarted due to:\n '$FILENAME'\" with title \" nodemon\" '"
},
"env" : {
"NODE_ENV" : " development"
},
"ext" : " ts,json"
}
$ npm install bcrypt
../helpers/Bcrypt.js
const bcrypt = require ( 'bcrypt' ) ;
const Bcrypt = {
cryptPassword : ( password ) =>
bcrypt . genSalt ( 12 )
. then ( ( salt => bcrypt . hash ( password , salt ) ) )
. then ( hash => hash ) ,
comparePassword : ( password , hashPassword ) =>
bcrypt . compare ( password , hashPassword )
. then ( resp => resp )
} ;
module . exports = Bcrypt ;
const Bcrypt = require ( '../helpers/Bcrypt' )
const password = 'userpassword' ;
// return hash
const userPasswordHash = await Bcrypt . cryptPassword ( password ) ;
userPasswordHash = '$2y$12$skd4.pWo.BU6/QpMIWhAK..XSVfpWWx7srqIrdmO0nHmknwOCureS'
// return true or false
const userPasswordIsValid = await Bcrypt . comparePassword ( password , userPasswordHash )
Force HTTP to HTTPS in Production
const app = express ( ) ;
if ( process . env . NODE_ENV === 'production' ) {
app . use ( ( req , res , next ) => {
if ( req . header ( 'x-forwarded-proto' ) !== 'https' ) {
res . redirect ( `https://${ req . header ( 'host' ) } ${ req . url } ` )
} else {
next ( ) ;
}
} ) ;
}
DEFAULT PORT: 27017
Packages/Modules
As A Service
GUI Software:
DEFAULT PORT: 3306
Tutorial
ORM
Packages
As A Service
Heroku
Fast Setup MongoDB + MongoClient
sudo docker run \
--name mongodb \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=alex \
-e MONGO_INITDB_ROOT_PASSWORD=mypassword \
-d \
mongo:4
sudo docker run \
--name mongoclient \
-p 3000:3000 \
--link mongodb:mongodb \
-d \
mongoclient/mongoclient
sudo docker exec -it mongodb \
mongo --host localhost -u admin -p mypassword
--authenticationDatabase admin \
--eval "db.getSiblingDB('database_test').createUser(
{user: 'alex', pwd: 'mypassword',
roles: [{role: 'readWrite', db: 'database_test'}]}
)"
GitHub Workflows/Actions
DNS
SSL/HTTPS VPS
Heroku
AWS
DigitalOcean
function sum ( x :number , y :number ) :number {
return x + y ;
}
module . exports . sum = sum ;
const Math = require ( './Math' ) ;
console . log ( `SUM: ${ Math . sum ( n1 , n2 ) } ` ) ;
function sum ( x :number , y :number ) :number {
return x + y ;
}
export default {
sum :sum , // sum
} ;
import * as Math from './Math' ;
console . log ( `SUM: ${ Math . sum ( 2 , 3 ) } ` ) ; // SUM: 5
export function sum ( x :number , y :number ) :number {
return x + y ;
}
import { sum } from './Math' ;
console . log ( `SUM: ${ sum ( 2 , 3 ) } ` ) ; // SUM: 5
JSON SERVER FAST REST API
$ sudo npm install -g json-server
Change PORT
json-server --watch db.json --port 3004
create db.json
{
"products" : [
{
"id" : 1 ,
"name" : " Sushi" ,
"description" : " A melhor comida que existe." ,
"price" : 8.5 ,
"category_id" : 1
},
{
"id" : 2 ,
"name" : " Batata Frita" ,
"description" : " Só o Cristiano Ronaldo não gosta." ,
"price" : 10.5 ,
"category_id" : 1
},
{
"id" : 3 ,
"name" : " X-Tudo" ,
"description" : " Melhor lanche que existe." ,
"price" : 12.5 ,
"category_id" : 1
},
{
"id" : 4 ,
"name" : " Tubaina" ,
"description" : " Os clássicos a gente nunca esquece." ,
"price" : 14.5 ,
"category_id" : 2
},
{
"id" : 5 ,
"name" : " Koka Kola" ,
"description" : " Refrigerante que faz mal." ,
"price" : 5.5 ,
"category_id" : 2
},
{
"id" : 6 ,
"name" : " Dollynho" ,
"description" : " Seu amiguinho, vamos brincar?" ,
"price" : 7.5 ,
"category_id" : 2
}
],
"categories" : [
{
"id" : 1 ,
"name" : " Comida"
},
{
"id" : 2 ,
"name" : " Refrigerantes"
}
]
}
$ json-server --watch db.json
>
Request
URL
Details
headers: { 'Content-Type': 'application/json' }
GET
http://localhost:3000/products
Return all products
GET
http://localhost:3000/products/1
Return product by ID
POST
http://localhost:3000/products
Create new product
{
"nome": "Bolo de Cenoura com cobertura de chocolate",
"descricao": "DELÍCIA",
"preco": 9.5,
"categoria_id": 1
}
PUT
http://localhost:3000/products/1
Update all product data by ID
{
"name": "Sushi edited",
"description": "description edited",
"preco": 10.5,
"category_id": 1
}
PATCH
http://localhost:3000/products/1 Update some product data by ID
{
"name": "New Sushi Name"
}
DELETE
http://localhost:3000/products/1
Delete a product by ID
GET
http://localhost:3000/products?name=Sushi
Filter products by name
GET
http://localhost:3000/products/?_page=1&_limit=2
Get products by Pagination
GET
http://localhost:3000/products/?_sort=nome&_order=desc
Get products order by
const fetch = require ( 'node-fetch' ) ;
const API_URL = 'http://localhost:3000' ;
const ENDPOINT = 'products' ;
// --------- GET
fetch ( `${ API_URL } /${ ENDPOINT } ` , {
"method" : "GET"
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// --------- POST
fetch ( `${ API_URL } /${ ENDPOINT } ` , {
method : 'POST' ,
body : JSON . stringify ( {
"name" : "New item adicionado com NODEJS" ,
"description" : "npm init e tals" ,
"price" : 19.90 ,
"category_id" : 1
} ) ,
headers : { 'Content-Type' : 'application/json' } ,
} )
. then ( res => res . json ( ) )
. then ( json => console . log ( json ) ) ;
// --------- PUT
const product_id_to_put = 8 ;
fetch ( `${ API_URL } /${ ENDPOINT } /${ product_id_to_put } ` , {
method : 'PUT' ,
body : JSON . stringify ( {
"name" : "PRODUTO 8 ATUALIZADO" ,
"description" : "description atualized" ,
"price" : 59.90 ,
"category_id" : 2
} ) ,
headers : { 'Content-Type' : 'application/json' } ,
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// --------- PATCH
const product_id_to_patch = 12 ;
fetch ( `${ API_URL } /${ ENDPOINT } /${ product_id_to_patch } ` , {
method : 'PATCH' ,
body : JSON . stringify ( {
"name" : "Item 12 nome atualizado" ,
"price" : 39.90 ,
} ) ,
headers : { 'Content-Type' : 'application/json' } ,
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// --------- DELETE
const product_id_to_delete = 3 ;
fetch ( `${ API_URL } /${ ENDPOINT } /${ product_id_to_delete } ` , {
method : 'DELETE'
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// --------- FILTER BY NAME
const filterName = 'Sushi' ;
fetch ( `${ API_URL } /${ ENDPOINT } ?name=${ filterName } ` , {
"method" : "GET"
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// ---------- ORDER BY
const ORDER = 'DESC' ;
const SORT = 'preco' ;
fetch ( `${ API_URL } /${ ENDPOINT } /?_sort=${ SORT } &_order=${ ORDER } ` , {
"method" : "GET"
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;
// ----------- PAGINATION
let page = 3 ;
let limit = 4 ;
fetch ( `${ API_URL } /${ ENDPOINT } /?_page=${ page } &_limit=${ limit } ` , {
"method" : "GET"
} )
. then ( response => response . json ( ) )
. then ( json => console . log ( json ) )
. catch ( err => console . error ( err ) ) ;