making restful web services the easy way with node · pdf filetitle: making restful web...
TRANSCRIPT
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
MakingRESTfulWebServicestheEasyWaywithNode.js
DanMcGhanOracleDeveloperAdvocateOctober3,2017
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
🎉💃🍻😃👍🕺🎉
Confidential– OracleInternal/Restricted/HighlyRestricted 3
Getexcitedfor…
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
🎉💃🍻😃👍🕺🎉JavaScriptin theDatabase!!!
Confidential– OracleInternal/Restricted/HighlyRestricted 4
Getexcitedfor…
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
JavaScriptintheDatabase!!!• NewMulti-LanguageEnginefromOracleLabs• NowavailableforpreviewonOTN– ViaaVirtualBoxVM
• GototheirtalkWednesdayat5:30pm– CON6744:AcceleratingYourDatabaseApplicationsSimplywithGraal–MarriottMarquis(YerbaBuenaLevel)– Salon13– Ignorethedescriptioninthesessionbuilder
5
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
SafeHarborStatementThefollowingisintendedtooutlineourgeneralproductdirection.Itisintendedforinformationpurposesonly,andmaynotbeincorporatedintoanycontract.Itisnotacommitmenttodeliveranymaterial,code,orfunctionality,andshouldnotberelieduponinmakingpurchasingdecisions.Thedevelopment,release,andtimingofanyfeaturesorfunctionalitydescribedforOracle’sproductsremainsatthesolediscretionofOracle.
6
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Aboutme• DanMcGhan–OracleDeveloperAdvocate– FocusonJavaScriptandOracleDatabase
• ContactInfo– [email protected]–@dmcghan– jsao.io
7
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Agenda
RoughintrotoAPIsandNode.js
ManualAPIcreation
APIcreationwithSails.js
APIcreationwithORDS
1
2
3
8
4
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Agenda
RoughintrotoAPIsandNode.js
ManualAPIcreation
APIcreationwithSails.js
APIcreationwithORDS
1
2
3
9
4
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
What’sREST?• REpresentation StateTransfer– Architecturalstylefordistributedhypermediasystems–OriginallydefinedinRoyFielding’sdoctoraldissertation
• Definessixconstraints
–Mostimplementationsdon’tcomply100%
10
UniformInterface Stateless Cacheable
Client-server LayeredSystem Codeondemand
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Clientcommunicatesintentvia• URLpathsbasedonnouns,notverbs
• HTTPmethods
11
Type Example
Collection http://server.com/api/employees
Resource http://server.com/api/employees/101
Method CRUD/DatabaseAction
POST Create/INSERT
GET Read/SELECT
PUT Update/UPDATE
DELETE Delete/DELETE
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
WhatisNode.js?• Server-sideJavaScriptruntime–Onelanguage,front-endandback-end
• JavaScriptruntimebuiltonChrome’sV8JavaScriptengine– ThoughV8isbeingdecoupledtoallowforotherJavaScriptengines
• Packageecosystem(NPM)isworld’slargestrepoofopen-sourcelibraries• Lightweightandefficient:event-driven,non-blockingI/Omodel
12
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 13
Node.js architecture
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Rollyourownoruseaframework?
14
Rollyourown• Morecode
• Moreflexibility
• Lowershort-termlearningcurve
• Lowerlong-termproductivity
Framework• Lesscode
• Lessflexibility
• Highershort-termlearningcurve
• Higherlong-termproductivity
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Whatfeaturesdoyouneedtosupport?• Pagination,sorting,&filtering• Authentication&authorization• Caching/ETag• Doc/Swagger• Real-timepush/WebSockets• Throttling• Multiplerepresentations(JSON,XML,CSV)• CORS
15
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 16
BasicingredientsforaRESTAPI
Client Middle-tier Database
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 17
BasicingredientsforaRESTAPI
Client Middle-tier Database
WebServer
acceptHTTPrequests,sendHTTPresponses
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 18
BasicingredientsforaRESTAPI
Client Middle-tier Database
WebServer
RoutingLogic
identifyintent,routerequesttocorrectcontrollerlogic
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 19
BasicingredientsforaRESTAPI
Client Middle-tier Database
WebServer
RoutingLogic
ControllerLogic
extractdata,applybusiness&databaselogic,generateresponse
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 20
BasicingredientsforaRESTAPI
Client Middle-tier Database
WebServer
RoutingLogic
ControllerLogic
DatabaseLogic
applybusinesslogic,updatepersistedstate
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.| 21
Howshouldthisbedone?Youdecide!
Client Middle-tier Database
WebServer
RoutingLogic
ControllerLogic
DatabaseLogic
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Agenda
RoughintrotoAPIs andNode.js
ManualAPIcreation
APIcreationwithSails.js
APIcreationwithORDS
1
2
3
22
4
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Webserveroptions• Express– Highlypopular,generalpurposewebserver
• Restify–WebserverfocusedonAPIs,addsDTrace support
• Kracken– fromPayPal,layeroverExpress,addsstructureandconvention
• Hapi– fromWalmart,alternativetoExpress– Includesmodulesforvalidation,CORS,sessions,caching,logging,etc.
23
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Databaselogicoptions• Drivers– Lowlevel,butextremelyflexible–Mayrequirespecificdatabaseknowledge
• ORMs– Higherlevel,canbemoreproductive– Attempttoabstractawaythedatabase
24
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
node-oracledbclassoverview
25
Baseclass• Getconnectionsorcreatepools• Setconfigurationparameters
ConnectionPooling• Dramaticallyincreasesperformance• Built-inpoolcacheforconvenience
SQLandPL/SQLExecution• Transactionsupportw/datatypeconversion• BindusingJavaScriptobjectsorarrays
Read-consistent,pageable cursor• Usedforlargeresultsets• RecursivecallbacksorNode.jsstreams
Largeobjectsupport• CanfetchsmallerLOBsasstring/buffer• StreamlargeLOBswiththisclass
Oracledb
Pool
Connection
ResultSet
Lob
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
26
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
27
Name,description,dependencies,scripts
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
28
Name,description,dependencies,scripts
Mainfile,startstheapplication
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
29
Name,description,dependencies,scripts
Mainfile,startstheapplication
Genericdirectoryforreusablelogic
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
30
Name,description,dependencies,scripts
Mainfile,startstheapplication
Genericdirectoryforreusablelogic
Directoryforcontrollerlogic
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
31
Name,description,dependencies,scripts
Mainfile,startstheapplication
Genericdirectoryforreusablelogic
Directoryfordatabaselogic
Directoryforcontrollerlogic
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Abasicdirectorystructure
32
Name,description,dependencies,scripts
Mainfile,startstheapplication
Genericdirectoryforreusablelogic
Directoryfordatabaselogic
Directoryforcontrollerlogic
Directoryforapplicationconfiguration
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ManualAPIDemo
33
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ManualAPIreview• HavetomanuallyimplementCRUDfunctionality– Notsobadifyou’recomfortablewithSQL(couldevenbescripted)– Couldbeadvantageousforcomplextasks(multipletables,transactions,etc.)
• GETrequestscanbetough– Paginationnotsobad,butapaintorepeat– NogenericsolutionforconvertingJSobjectstowhereclauses– NogenericsolutionforconvertingJSobjectstoorderbyclauses
34
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Agenda
RoughintrotoAPIs andNode.js
ManualAPIcreation
APIcreationwithSails.js
APIcreationwithORDS
1
2
3
35
4
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
MVCandAPIFrameworks• Frameworksofferall-in-onesolutions– Includewebservers– Generaterouting,controller,andmodellogic–Manyotherfeatures,varybytheframework
• Favorconventionoverconfiguration
36
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Sails.js andLoopback• Sails– AnMVCframeworkforNode.js• UsesWaterlineORMfordatabasemodeling
– Favoritefeatures• Blueprints:easilyprototypeAPIs• WebSocket integration
• Loopback– AnAPIframeworkforNode.js• UsesacustomORMfordatabasemodeling
– Favoritefeature• DiscoveryAPIsforOracleandothers
37
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
GettingstartedwithSails.js• Installation– npm install sails -g
• Createanapplication– sails new my-project
• Startuptheapplication– cd my-project– sails lift
• AddingtheOracleadapterforWaterline– npm install sails-oracle-db --save
38
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
SailsAPIDemo
39
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
SailsAPIreview• Sailsbringsout-of-the-boxconventiontoeachproject• Initiallearningcurvecanbealittlesteep– Butsubsequentusegetsbetter
• BlueprintscanhelpwithAPIprototyping
40
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
UsecautionwithORMs• Someenforcecasesensitivity
– Apainwhenyouwanttorunad-hocqueries
• Somedon’tusebindvariables– Forcesfrequenthardparses– Loopbackwins
• Somedon’tsupporttransactions
41
selectcolumnfromuser
select"column"from"user"becomes
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Agenda
RoughintrotoAPIs andNode.js
ManualAPIcreation
APIcreationwithSails.js
APIcreationwithORDS
1
2
3
42
4
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
IntroducingOracleRESTDataServices(ORDS)• Providesdataaccessconsistentwithmodernapp-dev frameworks–Mid-tierapplication– CanmapRESTfulrequeststoSQL– CanreturnresultsinJSONformat• JavaScriptfriendly
• Services– HTTP(s)relationaldataaccess–OracleJSONcollectionbasedschemalessaccess–OracleNoSQL accessoverHTTP–OracleAPEXmid-tier,webtoolkitapps,mod_plsql replacement
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ORDSreleasehistory
Version Date Description
1.0 2010 FirstreleaseasOracleAPEXListenerwithwith supportforOWAtoolkitusedbyAPEX
1.1 2011 First releasewithRESTsupportforJSON,Microdata,CSV,Pagination.AlsoaddedFOP
2.0 2012 OAuth2support,IntegratedwithAPEX, MultiDatabase,SQLDeveloperintegration
2.0.5 2013 AddedPDBsupport
2.0.6 2014 RenamedtoOracle RESTDataServicestoemphasizeRESTcommitment
2.0.8 2014 AddedRESTFiltering
3.0 2016 RESTAutoTable,NoSQL,DB12 JSON,BulkloadingoverREST
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ServingJSONresultsfromrelationaldata
OracleDatabase
URI
HTTP(S)client
OracleRESTDataServices
MapandBind SQL
Transform SQLResultSetTransformtoJSONJSON
• Datastoredinstandardrelationaltablesandcolumns• ORDSdeveloperdefinesURI=>SQLmapping• AppdevelopercallsnamedURIoverHTTP(S)–WorksforJavaScript(Node.js),Java,Python,PHP,Ruby,etc.
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ORDSAPIDemo
46
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
ORDSreview• ORDScangreatlysimplifyAPIcreationonOracleDatabase– AutoREST fortables– Built-insupport forpagination,filtering,even“asof”
• HasabuiltinOAuthServer• CanuseORDSincombinationwithNode.js– HideORDSbehindafirewall– ProxyselectrequestsfromNode.js toORDS(useauthenticationforNode.js server)– Lookatnode4ords foranexample
47
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
Summary• There’snoperfectsolutionforcreatingRESTAPIswithNode.js• ManualAPIimplementationsprovidethemostcontrol– Butalsorequirethemostknowledgeandcode– I’dliketoseealayer overthedriverforwhere,order,limit,andoffset
• ORMsprovideabstractionsfordatabases– Butmaynotusethedatabase“correctly”
• APIframeworksprovideconvention– Butonlymakesenseifyouagreewiththoseconventions
48
Copyright©2017, Oracleand/oritsaffiliates.Allrightsreserved.|
• Express
• Restify
• Hapi
• Kracken
• Driver• node-oracledb
– Query/SchemaBuilder• Knex
– ORMs• Sequelize
• Bookshelf
• Waterline
49
• Sails
• Loopback
• ORDS
Nextsteps:learnandcode!WebServers DriversandORMs Frameworks