Frontend Training
Who am I?
❏ Frontend architect at ilegra
❏ Graduated in Analysis and System
Development at FATEC Senai
❏ Started in 2012 on IT world
❏ Experience with Arch Front (Angular,
React, React Native, Vue, NodeJS,
Micro-fronts, SSR, BFF, GraphQL, PWA and
others)
@adrianlemess
Schedule for today
❏ Microfrontend (Demo)
❏ SSR (Exercise)
❏ Angular 8 (Exercise)
❏ Workers (Exercise)
❏ NodeJS (Exercise)
❏ BFF and GraphQL (Exercise)
❏ Puppeteer (Demo)
❏ Wasm (Demo)
Exercise Repo
❏ Fork the repository
https://github.com/adrianlemess/frontend-training
❏ Clone your fork repository
❏ In the terminal inside the root folder, type
❏ npm run bootstrap
Microfrontend
Frontend Monolith
Microfrontend
Choose what we need...
❏ How do applications relate to each other?
❏ Code isolation and Separation of Concern (SOC)
❏ Separated deploy and team ownership
❏ Cross-browser
❏ Performance
❏ Agnostic Technology
Options today
❏ Single SPA - "meta-framework" to combine multiple frameworks into
one app.
❏ Multiple SPAs on different URLs sharing code via NPM
❏ Micro-apps isolation with Iframe and communication via Post-message
❏ Web components
❏ Custom elements
❏ Open components
❏ Mosaic
❏ Vanilla script
Cases at
ilegra
Legado
1 - Single SPA + Iframe
❏ AngularJS Migration to React
❏ Using CanopyTax/Single-SPA micro-front framework and
Iframe
App 1
/app1
App 2
/app2
Iframe
/**
DOM DOM
2 - Homemade solution
Router
Homepage
Templates
/header
/menu
/app1
Header
Menu
Login
App1
App2
App3
2 - Homemade solution
Header (React)
Menu
(React)
App loading dynamically
3 - Mosaic with adaptations
3 - Our Solution with Microfronts
Fragment-loader
Fragment A Fragment B Fragment C
Custom
Router
Demo
https://github.com/adrianlemess/poc-microfrontend
SSR
User Journey
It's happening? It's useful? is interactive
Navigation
Starts!
(Time to
First Byte)
First Painting
Navigation
has started
(First
contentful
paint)
First
Meaningful
paint
(Primary
content has
loaded)
Visible
content
has loaded Time to
interactive
(events attached)
Fully loaded
First Loading - Numbers
❏ Google metrics through the Lighthouse tool indicate that the
ideal load time ranges from 1.5s to 3s.
❏ Amazon found that they could lose 1.6 Billion revenue on sale if
their page takes 1s longer to load.
❏ Walmart in turn found that every 100ms of initial load
optimization impacts 1% more revenue.
❏ Pinterest which reduced the initial load from 23s to 5.6s
resulting in a 43% increase in sales and 753% new user signups.
First Loading Nucleus Staff
❏ More than 10s were taken to load the entire app after login
How to Improve?
❏ Lazy Loading - Loading only what is necessary
❏ Assets and CDN
❏ Above the first
❏ Async loading (JS, CSS, Assets)
❏ SSR
What is SSR?
❏ Pré-Process the first page on the server side
❏ Deliver the first page already rendered - fast interaction
❏ Improve load speed
❏ SEO Improvements (Search Engine Object)
How to measure web
performance?
Results
https://github.com/adrianlemess/server-side-rendering
Vue CSR
Vue SSR
React CSR
React SSR
Angular CSR
Angular SSR
Angular 8
What is?
❏ Angular is a platform and framework for building applications
using HTML, CSS, and TypeScript.
❏ Open source maintained by Google
❏ Angular works on the SPA (Single Page Applications) model
❏ Deliver a version of the application to the browser with its
templates
❏ Traffic only JSON and no more HTML templates between server
and client
❏ Use TypeScript
Angular Versions
How to Install
❏ Install Angular and TypeScript
npm install -g typescript @angular/cli
❏ Documentation in: https://angular.io/guide/quickstart
Angular CLI commands
❏ Creating an app
ng new name_app —prefix test-prefix
❏ Start an app
ng serve --open
❏ Creating an component
ng generate component name_component
❏ Creating an module
ng generate module name_module
Angular CLI commands
❏ Creating an Service
ng generate service name_service
❏ Building an app for an environment
ng build --prod
Angular CLI commands
❏ Creating an web worker
ng generate web-worker name_worker
❏ Transform an app in PWA
ng add @angular/pwa --project *project-name*
❏ Transform an app in SSR
ng add @nguniversal/express-engine --clientProject
name_project
Concepts
❏ TSlint / Eslint - code analyzer based on a rule set
❏ Binding - bind a variable to the DOM
❏ Guard - Route Access Protection
❏ Interceptor - intercept and modify each request in a global way
❏ Lazy Loading - Slowly load modules as needed
❏ Pipes and masks - ways to display certain formatted data on
screen or in input
Concepts
❏ Directive - attributes or tags in html we added
❏ Validators - Custom form input validations
❏ Observables - how to work with reactivity in Angular
❏ rxjs / ReactiveX - library that implements observables
❏ ngrx / Redux - Lib that implements flux model
❏ zones - equivalent to react Vdom and vuejs, famous
$scope.apply () from angularJS
Components
Code Snippets
❏ https://gist.github.com/adrianlemess/0193b63bede199c0b6c6dac41535b645
TypeScript sandbox
❏ Playground to practice TypeScript
❏ https://github.com/adrianlemess/ts-sandbox
Workers
Quiz
JavaScript is ________________
a) Asynchronous
b) Single Thread
c) Both
d) Confused
Event loop
Single Thread
“Every line of front end JS you've ever written has
(momentarily) stopped your page from working”.
Nor Churchill - Neither Mark Twain
60 frames / second
❏ The users expected pages more simple and interactive
❏ interactions must be fluid
❏ The current devices refresh the view 60 times per second
❏ 1 second == 1000ms
60 frames == x
❏ Each frame has only 16ms to execute
❏ We should worry about what execute and not block the main
thread
Workers
❏ A worker is an object created using a
constructor that runs a named JavaScript file
in the background.
❏ Has its own global execution context, self !==
window
❏ Communicate to the main thread via the
postMessage API
❏ Web Worker (parallelism) x Service Worker
(offline) x Worklets (Browser render journey)
Web
Workers
Web Workers
❏ The W3C published a first draft of the web
workers standard in 2009
❏ Web workers is an asynchronous system, or
protocol, for web pages to execute tasks in
the background, independently from the main
thread and website UI
❏ Best suited to execute long-running or
demand computation tasks
❏ Helps to free main thread to user interactions
❏ Angular 8 has built-in support
Main Thread
Web Worker
PostMessage
❏ Using a web worker:
const myWorker = new Worker('worker.js');
❏ Sending a message to worker
myWorker.postMessage('Hello!');
❏ Receiving result from worker
myWorker.onmessage = function(e) {
console.log(e.data);
}
main.js
❏ Receiving message from main.js
self.onmessage = function(e) {
console.log(e.data);
// Send message to main file
self.postMessage(workerResult);
}
worker.js
❏ Navigator object (browser infos)
❏ Location object (Read Only)
❏ XMLHttpRequest (Service worker uses Fetch)
❏ setTimeout()/clearTimeout() and setInterval()/clearInterval()
❏ The application cache
❏ Parsing data
❏ Virtual DOM
❏ File Reader, blob, ArrayBuffer
❏ importScripts() method to import other scripts
❏ Spawning other workers
❏ Not available DOM and Window objects
What we can do
❏ It’s not possible to specify if a web worker should run on a specific
core
❏ Web workers on a single core will not run in parallel but will not block
the main UI thread
❏ On a multicore CPU Web Workers can truly run in parallel if the SO
decides to
Web Workers and Cores
Service
Workers
What is service worker?
❏ Service worker is a programmable proxy,
allowing you to control how the requests
from your page is handled
❏ Runs in background
❏ Enable cache (requests, image, etc)
❏ Enable push notification
❏ Background sync
What is service worker?
Demo
https://github.com/adrianlemess/poc-webworker-angular8
NodeJS
What is?
❏ Created by Ryan Dahl and released in 2009 at JSConf.EU
❏ Developed and maintained by Joyent, GitHub and community
❏ Licença MIT
❏ Baseado na Engine Google V8
❏ Last release: v12.13.1
❏ Javascript Development Platform for distributed applications
❏ Ideal for scenarios with many simultaneous connections and low
data processing
NodeJS
libuv V8 Js, C++
Google’s JavaScript engine
Event looping
Npm
❏ Dependency Manager
❏ Contains Project Information
❏ Generates package.json file with at least:
❏ Name
❏ Version
❏ Dependencies
❏ License
❏ Point main file
Npm commands
❏ Starting npm project
npm init
❏ Install dependencies
npm install <module name> (--save, -g)
❏ Run a file
node arquivo.js
❏ Execute a global package without install globally
npx package_command
Package.json scripts
"scripts": {
"build": "tsc",
"dev": "nodemon index.ts",
"start": "node ./dist/index.js",
"prod": "npm run build && npm run start:prod",
"test": "jest"
}
❏ Execute npm run dev, npm start, npm run prod ...
GraphQL & BFF
SOA
Interoperability
Business Value
Reuse by design
Incremental
Microservices - the Holy Graal
Isolated deploy
Horizontal Scalability
Time to Market
Agnostic technologyIsolated teams
Multi UIs
❏ How to provide different user experience
to different type of UIs?
❏ Different needs
❏ Difficult to keep cohesive domains
Business Oriented
❏ Contracts shouldn't be related with specifs UI
Security
❏ Exposes microservices to attackers
❏ Decrease the attack surface
Venn Diagram
Frontend Backend?
BFF - Best Friend Forever
Backend for Frontend
BFF Architectural Pattern
BFF Architectural Pattern
❏ Intermediate service
❏ Every frontend has it owns backend
❏ Tied coupled with a specific user experience
❏ Make easier to define and adapt API services as the UI required
Frontend BackendBFF
Characteristics
Data
Aggregation
Adaptation
Business rules
stay on services
Different clients == different
needs
❏ First Painting
❏ Server Side
Rendering
❏ Search Engine
Optimization
❏ Request frequency
❏ Network payload size
❏ CPU, Memory and
Battery Usage
How can we develop?
❏ Developed and maintained by frontend team
Java/Kotlin
Swift
NodeJS
Advantages
Deliver unique experience
https://medium.com/tech-tajawal/backend-for-frontend-using-graphql-under-microservices-5b63bbfcd7d9
Network Data
❏ Cache data
❏ Minimize the amount of data trafficked with the clientes
Frontend BackendBFF
Parallelism development
Disadvantages
Single point of failure
❏ It should be resilient by design with proper implementation of
circuit breakers, timeouts, retry etc
❏ Should be properly tested
❏ Required High Availability
One more component...
Manually data aggregation
❏ We have to program the data aggregation
GraphQL
What is?
“GraphQL is a query language for APIs and a runtime for fulfilling
those queries with your existing data.” https://graphql.org/
Who is using it
GraphQL
❏ Created by facebook team in 2012 and
became open source in 2015
❏ Query only the data we need
❏ Good fit for data aggregation
❏ Modified resources using mutations
❏ Resources are defined by schemas
Schema
type Company {
id: Int
name: String
description: String
users: [User]
}
type User {
id: Int
firstName: String
age: Int
company: Company
}
Graph
Nodes
Edge/resolvers
How is used
Gateway
Services
Problems about GraphQL
❏ REST can do much of what GraphQL does
❏ GraphQL will make some tasks more complex
❏ It’s easier to use a web cache with REST (HTTP) than with
GraphQL
❏ You could have performance issues with GraphQL queries
❏ The way GraphQL schemas work could be a problem to
multiple types of UI
❏ Managing complexity
BFF x GraphQL
❏ Specific Users
❏ Building solutions
❏ Very low data usage
❏ Agility
❏ Full Stack team
❏ General users
❏ Projecting
capabilities
❏ Low data usage
❏ Stability
Maybe Both?
BFF and GraphQL
Service A
Service B
Service C
BFF
BFF
Frontend Web
Frontend Mobile
Our perspective
❏ Good fit for on demand architecture
❏ Each service created may be available on GraphQL to
aggregation
❏ Don’t lose latency to simple requests
❏ Aggregation when we need aggregation
Our perspective
❏ Orphan logic stay on BFF
❏ Flexibility
❏ Services oriented only by business
❏ Services not exposed
❏ Attending multiple types of client
What is
“ Puppeteer is a Node
library which provides a
high-level API to control
Chrome or Chromium over
the DevTools Protocol.
Puppeteer runs headless by
default”
Features
❏ Screenshots
❏ PDF prints
❏ Pre-render content and crawl SPA to SEO engines
❏ Automate form submission, UI testing, keyboard input, etc.
❏ Create an up-to-date, automated testing environment.
❏ Capture a timeline trace of your site to help diagnose
performance issues.
❏ Test Chrome Extensions.
Install
# Chromium + puppeteer
npm i puppeteer
# Puppeteer without Chromium
npm i puppeteer-core
Snapshot
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 767, height: 1024 });
await page.goto('https://getbootstrap.com/');
await page.screenshot({ path: 'bootstrap.png',
fullPage: true });
browser.close();
})();
PDF
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://github.com/');
await page.pdf({ path: 'github.pdf', format:
'A4' });
browser.close();
})();
Automating Interactions
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.npmjs.com');
await page.focus('#site-search');
await page.type('react');
await page.click('#npm-search > button');
await page.waitForNavigation();
await page.screenshot({ path: 'npmjs.png' });
browser.close(); })();
Testing Devices
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iphone6 = devices['iPhone 6'];
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(iphone6);
await page.goto('https://www.facebook.com/');
await page.screenshot({ path: 'facebook.png' });
const host = await page.evaluate(() => location.host);
console.log(host); // www.facebook.com'
browser.close(); })();
Demo
https://github.com/adrianlemess/poc-puppeteer
Wasm
JavaScript
❏ Created by Brendan Eich in 1995
❏ Made in 10 days
❏ Primary Goal: DOM control and create dynamic web pages
❏ interpreted - runtime errors
❏ Concern with performance: 0
V8 - Google
❏ Ajax Emergence
❏ Code processed on browser and manipulate data via HTTP
❏ Dynamics apps (gmail. google maps e afins)
❏ Performance needs
❏ Google created in 2009 the Engine V8
❏ JIT - Just in Time Compilation - Code compilation - JavaScript
to Bytecode
How JIT/V8 Works?
❏ After JavaScript is loaded, it is transformed into a tree structure
called Abstract Syntax Tree or AST
❏ If a code snippet is interpreted many times it becomes warm. It
goes through the baseline compiler which, depending on the
OS / platform, generates a compiled version of the snippet with
some optimization, reducing interpretation time.
❏ If this warm code is executed many times it becomes hot and
the optimizer compiler kicks in, using a few things as a premise
❏ If one of these assumptions is broken, the deoptimization stage
begins.
❏ We also have a garbage collector to clear memory when
something is no longer used
How JIT/V8 Works?
JavaScript with V8
❏ Created by Brendan Eich in 1995
❏ Made in 10 days
❏ Primary Goal: DOM control and create dynamic web pages.
Deliver robust applications and run anywhere
❏ interpreted - runtime errors Compilado em tempo real
❏ Concern with performance: A LOT
Web Assembly -
The next
performance
Jump
“Web Assembly will change the way we
think of Web Apps”. Jay Phelps. Software
Engineer on Netflix.
Web Assembly what is?
❏ WebAssembly (WASM) is a binary-format Compiler Target (the
code that the compiler generates) that runs code such as C, C
++, and Rust in the browser with performance very close to that
of native code.
❏ Lets you run these codes from other languages next to
JavaScript - including sharing functionality.
WebAssembly stages
❏ Small bundle, decoding before JS parser, pre-compilation
optimizations and stream compilation
Abstract
❏ May be 10% to 800% faster than JS code - Depends on which
engine will run
❏ We can import WASM on NodeJS and browser
❏ Only runs 20% slower than native code.
❏ Sharing code between JavaScript and others languages - rust,
scala, C, C++, etc
❏ Accessing web APIs available on the environment (browser or
Node)
Future?
❏ Binaries Everywhere - code once run everywhere
❏ Using by games on web
❏ More and more languages compiling for WASM
❏ Garbage Collector
❏ Wasi
Exercises
All Links
❏ https://github.com/adrianlemess/frontend-training
❏ https://github.com/adrianlemess/poc-microfrontend
❏ https://github.com/adrianlemess/ts-sandbox
❏ https://github.com/adrianlemess/poc-puppeteer
❏ https://github.com/adrianlemess/poc-webworker-angular8
❏ https://github.com/adrianlemess/server-side-rendering
❏ https://gist.github.com/adrianlemess/0193b63bede199c0b6c6d
ac41535b645
Feedbacks?
Treinamento frontend

Treinamento frontend

  • 1.
  • 2.
    Who am I? ❏Frontend architect at ilegra ❏ Graduated in Analysis and System Development at FATEC Senai ❏ Started in 2012 on IT world ❏ Experience with Arch Front (Angular, React, React Native, Vue, NodeJS, Micro-fronts, SSR, BFF, GraphQL, PWA and others) @adrianlemess
  • 3.
    Schedule for today ❏Microfrontend (Demo) ❏ SSR (Exercise) ❏ Angular 8 (Exercise) ❏ Workers (Exercise) ❏ NodeJS (Exercise) ❏ BFF and GraphQL (Exercise) ❏ Puppeteer (Demo) ❏ Wasm (Demo)
  • 4.
    Exercise Repo ❏ Forkthe repository https://github.com/adrianlemess/frontend-training ❏ Clone your fork repository ❏ In the terminal inside the root folder, type ❏ npm run bootstrap
  • 5.
  • 6.
  • 7.
  • 8.
    Choose what weneed... ❏ How do applications relate to each other? ❏ Code isolation and Separation of Concern (SOC) ❏ Separated deploy and team ownership ❏ Cross-browser ❏ Performance ❏ Agnostic Technology
  • 9.
    Options today ❏ SingleSPA - "meta-framework" to combine multiple frameworks into one app. ❏ Multiple SPAs on different URLs sharing code via NPM ❏ Micro-apps isolation with Iframe and communication via Post-message ❏ Web components ❏ Custom elements ❏ Open components ❏ Mosaic ❏ Vanilla script
  • 10.
  • 11.
    Legado 1 - SingleSPA + Iframe ❏ AngularJS Migration to React ❏ Using CanopyTax/Single-SPA micro-front framework and Iframe App 1 /app1 App 2 /app2 Iframe /** DOM DOM
  • 12.
    2 - Homemadesolution Router Homepage Templates /header /menu /app1 Header Menu Login App1 App2 App3
  • 13.
    2 - Homemadesolution Header (React) Menu (React) App loading dynamically
  • 14.
    3 - Mosaicwith adaptations
  • 15.
    3 - OurSolution with Microfronts Fragment-loader Fragment A Fragment B Fragment C Custom Router
  • 16.
  • 17.
  • 18.
    User Journey It's happening?It's useful? is interactive Navigation Starts! (Time to First Byte) First Painting Navigation has started (First contentful paint) First Meaningful paint (Primary content has loaded) Visible content has loaded Time to interactive (events attached) Fully loaded
  • 19.
    First Loading -Numbers ❏ Google metrics through the Lighthouse tool indicate that the ideal load time ranges from 1.5s to 3s. ❏ Amazon found that they could lose 1.6 Billion revenue on sale if their page takes 1s longer to load. ❏ Walmart in turn found that every 100ms of initial load optimization impacts 1% more revenue. ❏ Pinterest which reduced the initial load from 23s to 5.6s resulting in a 43% increase in sales and 753% new user signups.
  • 20.
    First Loading NucleusStaff ❏ More than 10s were taken to load the entire app after login
  • 21.
    How to Improve? ❏Lazy Loading - Loading only what is necessary ❏ Assets and CDN ❏ Above the first ❏ Async loading (JS, CSS, Assets) ❏ SSR
  • 22.
    What is SSR? ❏Pré-Process the first page on the server side ❏ Deliver the first page already rendered - fast interaction ❏ Improve load speed ❏ SEO Improvements (Search Engine Object)
  • 25.
    How to measureweb performance?
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
    What is? ❏ Angularis a platform and framework for building applications using HTML, CSS, and TypeScript. ❏ Open source maintained by Google ❏ Angular works on the SPA (Single Page Applications) model ❏ Deliver a version of the application to the browser with its templates ❏ Traffic only JSON and no more HTML templates between server and client ❏ Use TypeScript
  • 35.
  • 36.
    How to Install ❏Install Angular and TypeScript npm install -g typescript @angular/cli ❏ Documentation in: https://angular.io/guide/quickstart
  • 37.
    Angular CLI commands ❏Creating an app ng new name_app —prefix test-prefix ❏ Start an app ng serve --open ❏ Creating an component ng generate component name_component ❏ Creating an module ng generate module name_module
  • 38.
    Angular CLI commands ❏Creating an Service ng generate service name_service ❏ Building an app for an environment ng build --prod
  • 39.
    Angular CLI commands ❏Creating an web worker ng generate web-worker name_worker ❏ Transform an app in PWA ng add @angular/pwa --project *project-name* ❏ Transform an app in SSR ng add @nguniversal/express-engine --clientProject name_project
  • 40.
    Concepts ❏ TSlint /Eslint - code analyzer based on a rule set ❏ Binding - bind a variable to the DOM ❏ Guard - Route Access Protection ❏ Interceptor - intercept and modify each request in a global way ❏ Lazy Loading - Slowly load modules as needed ❏ Pipes and masks - ways to display certain formatted data on screen or in input
  • 41.
    Concepts ❏ Directive -attributes or tags in html we added ❏ Validators - Custom form input validations ❏ Observables - how to work with reactivity in Angular ❏ rxjs / ReactiveX - library that implements observables ❏ ngrx / Redux - Lib that implements flux model ❏ zones - equivalent to react Vdom and vuejs, famous $scope.apply () from angularJS
  • 42.
  • 43.
  • 44.
    TypeScript sandbox ❏ Playgroundto practice TypeScript ❏ https://github.com/adrianlemess/ts-sandbox
  • 45.
  • 46.
  • 47.
    JavaScript is ________________ a)Asynchronous b) Single Thread c) Both d) Confused
  • 48.
  • 49.
    Single Thread “Every lineof front end JS you've ever written has (momentarily) stopped your page from working”. Nor Churchill - Neither Mark Twain
  • 50.
    60 frames /second ❏ The users expected pages more simple and interactive ❏ interactions must be fluid ❏ The current devices refresh the view 60 times per second ❏ 1 second == 1000ms 60 frames == x ❏ Each frame has only 16ms to execute ❏ We should worry about what execute and not block the main thread
  • 51.
    Workers ❏ A workeris an object created using a constructor that runs a named JavaScript file in the background. ❏ Has its own global execution context, self !== window ❏ Communicate to the main thread via the postMessage API ❏ Web Worker (parallelism) x Service Worker (offline) x Worklets (Browser render journey)
  • 52.
  • 53.
    Web Workers ❏ TheW3C published a first draft of the web workers standard in 2009 ❏ Web workers is an asynchronous system, or protocol, for web pages to execute tasks in the background, independently from the main thread and website UI ❏ Best suited to execute long-running or demand computation tasks ❏ Helps to free main thread to user interactions ❏ Angular 8 has built-in support Main Thread Web Worker PostMessage
  • 54.
    ❏ Using aweb worker: const myWorker = new Worker('worker.js'); ❏ Sending a message to worker myWorker.postMessage('Hello!'); ❏ Receiving result from worker myWorker.onmessage = function(e) { console.log(e.data); } main.js
  • 55.
    ❏ Receiving messagefrom main.js self.onmessage = function(e) { console.log(e.data); // Send message to main file self.postMessage(workerResult); } worker.js
  • 56.
    ❏ Navigator object(browser infos) ❏ Location object (Read Only) ❏ XMLHttpRequest (Service worker uses Fetch) ❏ setTimeout()/clearTimeout() and setInterval()/clearInterval() ❏ The application cache ❏ Parsing data ❏ Virtual DOM ❏ File Reader, blob, ArrayBuffer ❏ importScripts() method to import other scripts ❏ Spawning other workers ❏ Not available DOM and Window objects What we can do
  • 57.
    ❏ It’s notpossible to specify if a web worker should run on a specific core ❏ Web workers on a single core will not run in parallel but will not block the main UI thread ❏ On a multicore CPU Web Workers can truly run in parallel if the SO decides to Web Workers and Cores
  • 58.
  • 61.
    What is serviceworker? ❏ Service worker is a programmable proxy, allowing you to control how the requests from your page is handled ❏ Runs in background ❏ Enable cache (requests, image, etc) ❏ Enable push notification ❏ Background sync
  • 62.
  • 63.
  • 64.
  • 65.
    What is? ❏ Createdby Ryan Dahl and released in 2009 at JSConf.EU ❏ Developed and maintained by Joyent, GitHub and community ❏ Licença MIT ❏ Baseado na Engine Google V8 ❏ Last release: v12.13.1 ❏ Javascript Development Platform for distributed applications ❏ Ideal for scenarios with many simultaneous connections and low data processing
  • 66.
    NodeJS libuv V8 Js,C++ Google’s JavaScript engine
  • 67.
  • 68.
    Npm ❏ Dependency Manager ❏Contains Project Information ❏ Generates package.json file with at least: ❏ Name ❏ Version ❏ Dependencies ❏ License ❏ Point main file
  • 69.
    Npm commands ❏ Startingnpm project npm init ❏ Install dependencies npm install <module name> (--save, -g) ❏ Run a file node arquivo.js ❏ Execute a global package without install globally npx package_command
  • 70.
    Package.json scripts "scripts": { "build":"tsc", "dev": "nodemon index.ts", "start": "node ./dist/index.js", "prod": "npm run build && npm run start:prod", "test": "jest" } ❏ Execute npm run dev, npm start, npm run prod ...
  • 71.
  • 72.
  • 73.
    Microservices - theHoly Graal Isolated deploy Horizontal Scalability Time to Market Agnostic technologyIsolated teams
  • 74.
    Multi UIs ❏ Howto provide different user experience to different type of UIs? ❏ Different needs ❏ Difficult to keep cohesive domains
  • 75.
    Business Oriented ❏ Contractsshouldn't be related with specifs UI
  • 76.
    Security ❏ Exposes microservicesto attackers ❏ Decrease the attack surface
  • 77.
  • 78.
    BFF - BestFriend Forever Backend for Frontend
  • 79.
  • 80.
    BFF Architectural Pattern ❏Intermediate service ❏ Every frontend has it owns backend ❏ Tied coupled with a specific user experience ❏ Make easier to define and adapt API services as the UI required Frontend BackendBFF
  • 81.
  • 82.
    Different clients ==different needs ❏ First Painting ❏ Server Side Rendering ❏ Search Engine Optimization ❏ Request frequency ❏ Network payload size ❏ CPU, Memory and Battery Usage
  • 83.
    How can wedevelop? ❏ Developed and maintained by frontend team Java/Kotlin Swift NodeJS
  • 84.
  • 85.
  • 86.
    Network Data ❏ Cachedata ❏ Minimize the amount of data trafficked with the clientes Frontend BackendBFF
  • 87.
  • 88.
  • 89.
    Single point offailure ❏ It should be resilient by design with proper implementation of circuit breakers, timeouts, retry etc ❏ Should be properly tested ❏ Required High Availability
  • 90.
  • 91.
    Manually data aggregation ❏We have to program the data aggregation
  • 92.
  • 93.
    What is? “GraphQL isa query language for APIs and a runtime for fulfilling those queries with your existing data.” https://graphql.org/
  • 94.
  • 95.
    GraphQL ❏ Created byfacebook team in 2012 and became open source in 2015 ❏ Query only the data we need ❏ Good fit for data aggregation ❏ Modified resources using mutations ❏ Resources are defined by schemas
  • 96.
    Schema type Company { id:Int name: String description: String users: [User] } type User { id: Int firstName: String age: Int company: Company }
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
    Problems about GraphQL ❏REST can do much of what GraphQL does ❏ GraphQL will make some tasks more complex ❏ It’s easier to use a web cache with REST (HTTP) than with GraphQL ❏ You could have performance issues with GraphQL queries ❏ The way GraphQL schemas work could be a problem to multiple types of UI ❏ Managing complexity
  • 102.
    BFF x GraphQL ❏Specific Users ❏ Building solutions ❏ Very low data usage ❏ Agility ❏ Full Stack team ❏ General users ❏ Projecting capabilities ❏ Low data usage ❏ Stability
  • 103.
  • 104.
    BFF and GraphQL ServiceA Service B Service C BFF BFF Frontend Web Frontend Mobile
  • 105.
    Our perspective ❏ Goodfit for on demand architecture ❏ Each service created may be available on GraphQL to aggregation ❏ Don’t lose latency to simple requests ❏ Aggregation when we need aggregation
  • 106.
    Our perspective ❏ Orphanlogic stay on BFF ❏ Flexibility ❏ Services oriented only by business ❏ Services not exposed ❏ Attending multiple types of client
  • 108.
    What is “ Puppeteeris a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default”
  • 110.
    Features ❏ Screenshots ❏ PDFprints ❏ Pre-render content and crawl SPA to SEO engines ❏ Automate form submission, UI testing, keyboard input, etc. ❏ Create an up-to-date, automated testing environment. ❏ Capture a timeline trace of your site to help diagnose performance issues. ❏ Test Chrome Extensions.
  • 111.
    Install # Chromium +puppeteer npm i puppeteer # Puppeteer without Chromium npm i puppeteer-core
  • 112.
    Snapshot const puppeteer =require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setViewport({ width: 767, height: 1024 }); await page.goto('https://getbootstrap.com/'); await page.screenshot({ path: 'bootstrap.png', fullPage: true }); browser.close(); })();
  • 113.
    PDF const puppeteer =require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://github.com/'); await page.pdf({ path: 'github.pdf', format: 'A4' }); browser.close(); })();
  • 114.
    Automating Interactions const puppeteer= require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.npmjs.com'); await page.focus('#site-search'); await page.type('react'); await page.click('#npm-search > button'); await page.waitForNavigation(); await page.screenshot({ path: 'npmjs.png' }); browser.close(); })();
  • 115.
    Testing Devices const puppeteer= require('puppeteer'); const devices = require('puppeteer/DeviceDescriptors'); const iphone6 = devices['iPhone 6']; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.emulate(iphone6); await page.goto('https://www.facebook.com/'); await page.screenshot({ path: 'facebook.png' }); const host = await page.evaluate(() => location.host); console.log(host); // www.facebook.com' browser.close(); })();
  • 116.
  • 117.
  • 118.
    JavaScript ❏ Created byBrendan Eich in 1995 ❏ Made in 10 days ❏ Primary Goal: DOM control and create dynamic web pages ❏ interpreted - runtime errors ❏ Concern with performance: 0
  • 119.
    V8 - Google ❏Ajax Emergence ❏ Code processed on browser and manipulate data via HTTP ❏ Dynamics apps (gmail. google maps e afins) ❏ Performance needs ❏ Google created in 2009 the Engine V8 ❏ JIT - Just in Time Compilation - Code compilation - JavaScript to Bytecode
  • 120.
    How JIT/V8 Works? ❏After JavaScript is loaded, it is transformed into a tree structure called Abstract Syntax Tree or AST ❏ If a code snippet is interpreted many times it becomes warm. It goes through the baseline compiler which, depending on the OS / platform, generates a compiled version of the snippet with some optimization, reducing interpretation time. ❏ If this warm code is executed many times it becomes hot and the optimizer compiler kicks in, using a few things as a premise ❏ If one of these assumptions is broken, the deoptimization stage begins. ❏ We also have a garbage collector to clear memory when something is no longer used
  • 121.
  • 122.
    JavaScript with V8 ❏Created by Brendan Eich in 1995 ❏ Made in 10 days ❏ Primary Goal: DOM control and create dynamic web pages. Deliver robust applications and run anywhere ❏ interpreted - runtime errors Compilado em tempo real ❏ Concern with performance: A LOT
  • 123.
    Web Assembly - Thenext performance Jump
  • 124.
    “Web Assembly willchange the way we think of Web Apps”. Jay Phelps. Software Engineer on Netflix.
  • 125.
    Web Assembly whatis? ❏ WebAssembly (WASM) is a binary-format Compiler Target (the code that the compiler generates) that runs code such as C, C ++, and Rust in the browser with performance very close to that of native code. ❏ Lets you run these codes from other languages next to JavaScript - including sharing functionality.
  • 126.
    WebAssembly stages ❏ Smallbundle, decoding before JS parser, pre-compilation optimizations and stream compilation
  • 127.
    Abstract ❏ May be10% to 800% faster than JS code - Depends on which engine will run ❏ We can import WASM on NodeJS and browser ❏ Only runs 20% slower than native code. ❏ Sharing code between JavaScript and others languages - rust, scala, C, C++, etc ❏ Accessing web APIs available on the environment (browser or Node)
  • 128.
    Future? ❏ Binaries Everywhere- code once run everywhere ❏ Using by games on web ❏ More and more languages compiling for WASM ❏ Garbage Collector ❏ Wasi
  • 129.
  • 130.
    All Links ❏ https://github.com/adrianlemess/frontend-training ❏https://github.com/adrianlemess/poc-microfrontend ❏ https://github.com/adrianlemess/ts-sandbox ❏ https://github.com/adrianlemess/poc-puppeteer ❏ https://github.com/adrianlemess/poc-webworker-angular8 ❏ https://github.com/adrianlemess/server-side-rendering ❏ https://gist.github.com/adrianlemess/0193b63bede199c0b6c6d ac41535b645
  • 131.