Giter VIP home page Giter VIP logo

learning-nodejs's Introduction

References

Install Ubuntu

Event Loop

Others

Resources

Commands

  • $ 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
      • -D = --save-dev

Latest Stable Version

  • $ 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') });

Modules/Packages

FREE APIs to Play

TypeScrypt

  • $ 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"
}

Using Bcrypt Example

  • $ 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;
  • using 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();
    }
  });
}

Services

MongoDB

MySQL

Docker

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'}]}
   )"

Deploy

Import/Export Modules

Older module.exports

  • Math.ts
function sum(x:number, y:number):number {
 return x+y;
}
module.exports.sum = sum;
  • index.ts
const Math = require('./Math');
console.log(`SUM: ${Math.sum(n1,n2)}`);

Modern Object

  • Math.ts
function sum(x:number, y:number):number {
 return x+y;
}
export default {
	sum:sum, // sum
};
  • index.ts
import * as Math from './Math';
console.log(`SUM: ${Math.sum(2,3)}`); // SUM: 5

Modern Functions

  • Math.ts
export function sum(x:number, y:number):number {
 return x+y;
}
  • index.ts
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/1Update 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

Exampe with Node-Fetch

  • $ npm install node-fetch
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));

learning-nodejs's People

Contributors

alexgalhardo avatar dependabot[bot] avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.