Skip to content

Instantly share code, notes, and snippets.

@vre2h
Last active February 20, 2020 12:29
Show Gist options
  • Save vre2h/6e320f25f1373964c8a034ec26373434 to your computer and use it in GitHub Desktop.
Save vre2h/6e320f25f1373964c8a034ec26373434 to your computer and use it in GitHub Desktop.
Node.js course

Topic: Node.js as a web server

held by Shahen Hovhannisyan

Node Server

Definitions of server, port, protocol.

Every request has method, status, headers, cookies and body.

  • Methods

    • GET
    • POST
    • PUT
    • DELETE
    • OPTION, etc
  • Headers - metadata

  • Body - info that we're sending to backend (POST, PUT)

  • Cookies - information that backend sends to keep in browser to use it in the future as part of header for validation. On the browser side there's an api that sends cookie automaticaly to backend so you don't need to do it manually from frontend. It's safer than using localstorage but in mobile it's a headache (as everything else in mobile).

Express

node index.js --inspect - allows us to debug node in browser

Request (from HTTP2) and Response are streams and if you're using express there's a way to get response as chunk.

REST API

  • GET, POST, PUT, DELETE
  • How to create urls
    • /posts/:postId/comments/:commentId
    • Query params - we can get them from req.query.
      • /posts?last-20-10-2019&index=10

Middleware

Before response came to handler there're a lot of function that can affect on it. These functions are middlewares.

  • There's a way to create middleware - app.use and it has 3rd argument - next. If we call it without args, then it goes to another middlewares. In case if we pass object - it causes the error which we can handle by app.on('error', cb).

  • We can send headers by calling res.header('X_COMP_MAN', 'MAC').

  • Example

app.use([route], (req, res, next) => {
 console.log('THIS IS MIDDLEWARE');
 next();
});

Example's of REST queries

  1. GET /users
app.get('/users', (req, res) => {
 res.json(users);
})
  1. GET /users/:id
  2. POST /users We also need middleware for parsing body.
app.use(express.json())

Then request:

app.post('/users', (req, res) => {
 const newUser = req.body;
 users.push(newUser);
 res.json(newUser);
 res.end();
})
  1. DELETE /users/:id

Statuses

  • 100 - protocol switching
  • 200-400 - OK
  • 400+ - Not OK

Cookies

npm i cookie-parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/users', (req, res) => {
 console.log(res.cookies);
})

Cookies has key, value, ExpirationDate, secure, HTTPOnly, domain, path, etc

How to set cookies? Let's do it on user creation.

const users = [];
app.post('/users', (req, res) => {
 const newUser = req.body;
 users.push(newUser);
 
 res.cookie('uid', newUser.id, {httpOnly: true, secure: false, expires: new Date('10-10-2099')});
 res.json(newUser);
 res.end();
});
 
app.get('/users', (req, res) => {
 res.cookie('uid', 1, {httpOnly: true, secure: false, expires: new Date('10-10-2099')}).end();
});

// better to do this process in middleware
app.get('/me', (req, res) => {
 const {uid} = req.cookies;
 const user = users.find(u => u.id === +uid)
 
 if (!user) {
  res.status(404).end()
  return 
 }
 
 res.json(user);
});

If you want to delete cookie, you need to change it's expires key to past date.

res.cookie('uid', 0, {
 expires: new Date('10-10-1990')
});

Session

User signup --> Backend generates uuid --> Stores in object {[key: string]: {email, id, username} } (key is a uuid) --> sends uuid to frontend -->

User request with uuid --> Backend checks if there's a object with this uuid

Note,

  1. Frontend gets only uuid.
  2. We keep this uuid's in mongo or redis.

Topic: Express.js

held by Gevorg Topikyan

Main source: Express.js docs

Patterns

Recommended Literature:

  • "Gang of four"

Mentioned Topics:

  • Chain of responsibility pattern

Middlewares

Express handlers are middlewares which use chain of responsibility pattern.

function (req, res, next)
  • next - passes flow to another middleware. It can be called with 'route' argument to pass to another route instead of middleware.

Error handler middleware

app.use(err, req, res, next)

Note, we need to specify all args for express to help it understand that it's an error handling middleware.

Third-party Middlewares

  • body-parser - to parse response body
  • morgan - for logging

Mini applications

const router = express.Router();
app.use('/', router);

We can use this feature of express to create a lot of mini independent reusable applications and connect them to route (e.g. user handler to user, posts handler to post).

Other express handler arguments

  • Request
  • Response

Express methods

  • Download - to get file and stream response by sending using chunks.

Task,

  • to make download process on server slower (CPU safe way)

Another Packages

  • We use dotenv to insert variables to process.env.
  • We can use winston as logger. It has some advantages over morgan. For example, morgan can log only requests, winston on the other side can work with everything. Also, winston has tons of integrations (e.g. with mongodb)
  • We use errorhandler - package for handling errors

Protocols

held by Shahen Hovhannisyan

Protocol - set of communication rules for two entities communication (e.g. client / server).

Networking

  • DNS

Protocols

Every protocol has a multiple layers.

  • HTTP(S) - Hyper Text Transfer Protocol - Application Layer Protocol
    • We've client and server and they setup communication using handshake request
    • HTTP uses TCP/IP
    • Before HTTP/1.0 every request (e.g styles, scripts) had it's own handshake request. After HTTP/1.0 we can setup "keep-alive" method to keep request alive.
    • HTTP/2.0 forces to use HTTPS and can get all files that it might need in future.
    • HTTP/3.0 gonna use UDP
    • HTTPS only have SSL, SSL makes sure domain that opened belongs to ip
  • TCP / IP - Transport Layer Protocols
    • It's a socket that opens so client-server can communicate
    • TCP/IP says that data will be there and in the correct order
  • UDP - User Datagram Protocol - Transport Layer Protocols
  • RTC - Realtime Communication
  • SSH - Secure Shell
  • FTP - File Transfer Protocol
  • DRP - Remote Desktop Protocol

TCP/IP

  • We've net package which allows to create tcp server

server.js

const net = require('net');
const server = net.createServer();

server.on('listening', () => {
  console.log('tcp server listening');
});
  
server.on('connection', socket => {
  console.log(socket.localAddress);
  
    // data is a Buffer
    server.on('data', (data) => {
      console.log(data.toString());
      
      socket.write('ping');
    });
    
  // destroys socket
  socket.destroy();
});

server.listen(1234);

client.js

const socket = net.Socket()

socket.connect({
  host: '127.0.0.1',
  port: 1234
})

socket.on('data', (data) => {
  console.log(data);
  socket.write('pong');
});
  • To check use telnet cli command

UPD

It may not send your request/response or in wrong order.

server.js

const dgram = require('dgram');

const socket = dgram.createSocket()

socket.on('message', (msg, info) => {
  console.log(msg.toString())
})

socket.on('listening', () => {
  console.log('listening');
});

socket.on('connect', () => {
  console.log('connected')
});

socket.bind(3000)
  • It has not response, only requests
  • To send udp request from cli
echo 'hi' | nc -w1 -u 127.0.0.1 3000

client.js

const socket = new dgram.createSocket('udp4');

socket.bind(1234, () => {
  socket.send('hello DGRAM', 3000, '0.0.0.0), (err, bytes) => {
    conosle.log(err, bytes);
  }):
});

Web Socket

TCP vs Web Socket

  • WS works without handshake

Usage

  • Chats
  • Games

Node.js

  • Use Websockets using websocket package
  • Server (see docs as example)
  • Browser
    const ws = new WebSocket('ws://localhost:3000')
    

Socket.io

  • See docs
  • On client it already has package on http://localhost:3000/socket.io/socket.io.js

Caching

  • Memoization
  • Redis

Databases

  • SQL
  • NoSQL
  • Graph

Project Structure

Principles

  • Scalability
  • High load proof
  • Bulletproof
  • Fault-tolerant

Patterns

  • MVC
  • MVVM
  • MVP
  • BloC
  • Solid

Packages

  • mlap
  • mongo atlas

Backend apps layering

  • Controller -> Service -> Data Layer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment