Lecture 13 - Backend Development - George Mason University

Transcription

Backend DevelopmentSWE 432, Fall 2016Design and Implementation of Software for the Web

Show & TellSparklines in presidential-polls-forecast.htmlLaToza/BellGMU SWE 432 Fall 20162

Today Why do we need backend programming?How can/should we structure those backends?Node.JSFor further reading:https://nodejs.org (Docs Examples)https://www.npmjs.com (Docs etupLaToza/BellGMU SWE 432 Fall 20163

Why we need backends Security: SOME part of our code needs to be “trusted” Performance: Avoid duplicating computation (do it once andcache) Do heavy computation on more powerful machines Do data-intensive computation “nearer” to the dataCompatibility: LaToza/BellValidation, security, etc. that we don’t want to allowusers to bypassCan bring some dynamic behavior without requiringmuch JS supportGMU SWE 432 Fall 20164

Dynamic Web AppsahWseuehtttnircaretthiswWeb “Front End”ReactSome “Back End”FirebaseLaToza/BellPresentationSomeother APIGMU SWE 432 Fall 2016Data storageSome other logic5

Where do we put the logic?aWheuset thterniraithwctsWeb “Front End”HTMLc tsatWhthentfr oPresentationReactCSSJavaScriptSome logicthwiatern“BackiEnd”denFirebaseData storageSome otherAPISome other logicFrontendBackendProsVery responsive (low latency)ProsEasy to refactor between multipleclientsLogic is hidden from users (good forConssecurity, compatibility, and intensiveSecuritycomputation)PerformanceConsUnable to share between front-ends Interactions require a round-trip toserverLaToza/BellGMU SWE 432 Fall 20166

Why Trust Matters Example: Transaction appfunction updateBalance(user, amountToAdd){user.balance user.balance lance").set(user.balance);} LaToza/BellWhat’s wrong?How do you fix that?GMU SWE 432 Fall 20167

Dynamic Web AppsWeb “Front End”PresentationReactSome logicHTMLCSSJavaScript“Back End”FirebaseLaToza/BellSomeother APIGMU SWE 432 Fall 2016Data storageSome other logic8

Dynamic Web AppsWeb “Front End”PresentationReactSome logicHTMLCSSJavaScript“Back End”FirebaseLaToza/BellSomeother APIGMU SWE 432 Fall 2016Our ownbackendData storageSome other logic9

What does our backend look like?Our own backendWeb “Front End”AJAXConnection toFrontendLogicPersistent DataLaToza/BellGMU SWE 432 Fall 201610

The “good” old days of backendsHTTP RequestGET /myApplicationEndpoint HTTP/1.1Host: cs.gmu.eduAccept: text/htmlweb serverRuns a programGive me /myApplicationEndpointDoes whatever it wantsWeb ServerApplicationHere’s some text to send backMyApplicationBackendHTTP ResponseHTTP/1.1 200 OKContent-Type: text/html; charset UTF-8 html head .LaToza/BellGMU SWE 432 Fall 201611

What’s wrong with thispicture?

History of Backend Development LaToza/BellIn the beginning, you wrote whatever you wantedusing whatever language you wanted and whateverframework you wantedThen PHP and ASP Languages “designed” for writing backends Encouraged spaghetti code A lot of the web was built on thisA whole lot of other languages were also springingup in the 90’s Ruby, Python, JSPGMU SWE 432 Fall 201613

Backend SpaghettiLaToza/BellGMU SWE 432 Fall 201614

De-SpaghettificationOur own backendConnection toFrontendLogicPersistent DataViewControllerModelLecture 10LaToza/BellGMU SWE 432 Fall 201615

MVC & Backend Servers LaToza/BellThere are a ton of backend frameworks that supportMVC SailsJS, Ruby on Rails, PHP Symfony, PythonDjango, ASP.NET, EJB Old days: View was server-generated HTMLNew days: View is an APIToday we’ll talk about Node.JS backenddevelopmentWe will not talk about making MVC backends andwill not require you to do soGMU SWE 432 Fall 201616

Node.JS LaToza/BellWe’re going to write backends with Node.JSWhy use Node? Easy to get into after learning JS (it’s JS) Event based: really efficient for sending lots ofquick updates to lots of clientsWhy not use Node? Bad for CPU heavy stuff It’s relatively immatureGMU SWE 432 Fall 201617

Node.JS Node.JS is a runtime that lets you run JS outside of abrowserNode.JS has a very large ecosystem of packagesExample: express (web server), nodemon(automatically restarts your server when it changes)Must be downloaded and installedhttps://nodejs.org/en/ LaToza/BellWe recommend v4.5.0 LTS (LTS - Long TermSupport, designed to be super stable)GMU SWE 432 Fall 201618

More on Modules How have we been using libraries so far? script src "https://fb.me/react-15.0.0.js" /script script src “https://fb.me/react-dom-15.0.0.js" /script script src /5.8.34/browser.min.js" /script What’s wrong with this? No standard format to say: What’s the name of the module?What’s the version of the module? Where do I find it? LaToza/BellIdeally: Just say “Give me React 15 and everything I need tomake it work!”This is slowly being fixed for ES6 and on but Node has agreat (non-standardized) approach we can use for backenddevelopmentGMU SWE 432 Fall 201619

A better way for modules Modules that magically appear Describe what your modules areCreate a central repository of those modulesMake a utility that can automatically find andinclude those modulesLaToza/BellAssumes dependencies magically existYour appDependenciesConfigurationDeclares what modules you needPackageManagerProvides the modules to your appGMU SWE 432 Fall 201620

NPM: Not an acronym, but the NodePackage Manager LaToza/BellBring order to our modules anddependenciesDeclarative approach: “My app is called helloworld” “It is version 1” You can run it by saying “nodeindex.js” “I need express, the mostrecent version is fine”Config is stored in json specifically package.jsonGMU SWE 432 Fall 2016Generated by npm commands:{"name": "helloworld","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no testspecified\" && exit 1"},"author": "","license": "ISC","dependencies": {"express": " 4.14.0"}}21

Using NPM Your “project” is a directory which contains a special file,package.json Everything that is going to be in your project goes in this directory Step 1: Create NPM projectnpm init Step 2: Declare dependenciesnpm install packagename --save Step 3: Use modules in your appvar myPkg require(“packagename”) Do NOT include node modules in your git repo! Instead, just donode install LaToza/BellThis will download and install the modules on your machinegiven the existing config!GMU SWE 432 Fall 201622

Demo: Hello World Server1: Make a directory, myapp2: Enter that directory, type npm init (accept all defaults)3: Type npm install express --save4: Create text file app.js:var express require('express');var app express();var port process.env.port 3000;app.get('/', function (req, res) {res.send('Hello World!');});Creates a configuration filefor your projectTells NPM that you want to useexpress, and to save that in yourproject configapp.listen(port, function () {console.log('Example app listening on port' port);});5: Type node app.js6: Point your browser to http://localhost:3000LaToza/BellRuns your appGMU SWE 432 Fall 201623

Demo: Hello World Servervarexpress require(‘express');1: Makea directory,myappImport the module express2: Enter that directory, type npm init (accept all defaults)var app express();3: Typenpma installexpress--saveCreatenew instanceof express4: Create text file app.js:var port process.env.port 3000;Decide what port we want express to listen onCreates a configuration filefor your projectTells NPM that you want to useexpress, and to save that in yourproject configapp.get('/', function (req, res) {res.send('Hello World!');});Create a callback for express to call when we have a “get” request to “/“. Thatcallback has access to the request (req) and response (res).app.listen(port, function () {console.log('Example app listening on port' port);});5: Type node app.jsTell our new instance of express to listen on port,andprintto the console once itRunsyourapp6: Point your browser to http://localhost:3000starts successfullyLaToza/BellGMU SWE 432 Fall 201624

Express Basic setup: For get:app.get("/somePath", function(req, res){//Read stuff from req, then call res.send(myResponse)}); For post:app.post("/somePath", function(req, res){//Read stuff from req, then call res.send(myResponse)}); Serving static s'));Make sure to declare this *last*Additional helpful module - bodyParser (for readingPOST data) LaToza/BellGMU SWE 432 Fall 201625

Putting it together:Firebase Node

Moving Firebase into Node General rule: If you set your database to be writeable byeveryone then make sure NOBODY has yourprivate keyIn our security lecture we’ll talk about having some data writable throughthe web app directly and some only through node. For now, we’ll talkabout the simplest case: Only allow writes through our node backend.LaToza/BellGMU SWE 432 Fall 201627

Firebase Node Step 1: Create a special access key for our Node appto use to access our database This key will distinguish our node app from the web app Now you can keep publishing your API key, but have aprivate key that you never publish publicly te a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google projectassociated with your app, click Import Google Project. Otherwise, click Create New Project.234LaToza/BellClick settings and select Permissions.Select Service accounts from the menu on the left.Click Create service account.a Enter a name for your service account. You can optionally customize the ID from the one automatically generated fromthe name.b Choose Project Editor from the Role dropdown.c Select Furnish a new private key and leave the Key type as JSON.d Leave Enable Google Apps Domain-wide Delegation unselected.e Click Create.GMU SWE 432 Fall 201628

Firebase Node LaToza/BellStep 2: Configure our database to allow writes fromONLY clients that have authenticated with a privatekeyDatabase - Rules - Set .write to be “auth ! null”GMU SWE 432 Fall 201629

Firebase Node Step 3: Declare our dependency on firebase In our project directory, run:npm install firebase --save In our app, write: LaToza/Bellvar firebase require("firebase");Step 4: Copy our downloaded private key (step 1)to our directory and configure Firebase to connectwith itGMU SWE 432 Fall 201630

Demo: Firebase NodeJS

What’s to come? LaToza/BellHow do we create structured APIs?How do we maintain some state between ourbackend and frontend?Privacy & SecurityArchitecting many services togetherDeploying our backend servicesGMU SWE 432 Fall 201632

Node.JS We’re going to write backends with Node.JS Why use Node? Easy to get into after learning JS (it’s JS) Event based: really efficient for sending lots of quick updates to lots of clients Why not use Node