servidor api rest con node.js
DESCRIPTION
Creando un servidor con una API RESTful con nodejs, expressjs and mongoosejs.TRANSCRIPT
SERVIDORAPIRESTCONNODE.JS
ADOLFOSANZDEDIEGOOCTUBRE2013
1ACERCADE
1.1ELGULElGULeselGrupodeUsuariosdeLinuxdelaUC3M.Grupodepersonasconinquietudesentornoalainformática.ConlaideacomúndelautilizaciónypromocióndelSoftwareLibre.Quedamosdevezencuandoyorganizamosactividadessobretodoesto.Elpuntodeunióneslalistadecorreoqueestáabiertaatodoelmundo.
1.2¿DÓNDEENCONTRARNOS?Twitter:Lista:Ftp:Web:Podcast:Blog:Linkedin:
http://twitter.com/[email protected]
ftp://ftp.gul.uc3m.eshttp://www.gul.uc3m.es
http://holamundo.gul.es/http://planeta.gul.uc3m.es/
http://www.linkedin.com/groups?gid=3451836
1.3ADOLFOSANZDEDIEGOAntiguoprogramadorwebJEEHoyendía:ProfesordeFPdeinformática:Hardware,SistemasOperativosRedes,Programación
FormadorFreelance:Java,AndroidJavaScript,jQueryJSF,Spring,HibernateGroovy&Grails
Megustaprogramar
1.4HACKALOVER
ParalosamantesdeloshackathonesMeetup:
Twitter:Blog:LinkedIn:
YouTube:
http://www.meetup.com/Hackathon-Lovers/
http://twitter.com/HackathonLovershttp://hackathonlovers.tumblr.com/
http://www.linkedin.com/groups/Hackathon-Lovers-6510465
http://www.youtube.com/channel/UCRwSe7jK-y62BMvIiNBV1qw
1.5TWEETSSENTIMENT
Esunanalizadordetweetsqueextraeinformaciónsemánticaparaconocersielsentimientogeneraldelostweetsdeundeterminadotemaespositivoonegativo.Web:Twitter:
http://tweetssentiment.com/http://twitter.com/TweetsSentiment
1.6¿DONDEENCONTRARME?Minick:asanzdiegoAboutMe:GitHub:Twitter:Blog:LinkedIn:Google+:
http://about.me/asanzdiegohttp://github.com/asanzdiegohttp://twitter.com/asanzdiego
http://asanzdiego.blogspot.com.eshttp://www.linkedin.com/in/asanzdiego
http://plus.google.com/+AdolfoSanzDeDiego
1.7CRÉDITOSAgradecimientosaCarlosAzustre( )CómocrearunaAPIRESTusandoNode.JS
Estastransparenciasestánhechascon:
http://twitter.com/carlosazaustre
http://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
https://github.com/asanzdiego/markdownslides
1.8LICENCIAEstastransparenciasestánbajounalicencia:
Elcódigodelosprogramasestánbajounalicencia:
CreativeCommonsReconocimiento-CompartirIgual3.0
GPL3.0
1.9FUENTESTransparencias:
Código:
SlideShareDeckSlidesRevealSlidesPlainHTML
https://github.com/asanzdiego/curso-api-restful-nodejs-server-2013/tree/master/src
2APIS¿PARAQUÉ?
2.1APLICACIÓNESTÁNDAR
2.2INTRODUCIMOSAPI
2.3SEPARACIÓNROLES
2.4¿YAHORAQUÉ?
2.5SERVICIOSEXTERNOS
2.6APPSCLIENTES
2.7APPSDESERVICIOS
2.8APPSMIXTAS
2.9PLATAFORMA
2.10¿QUIENEXPONEAPIS?
2.11¿QUIENEXPONEAPIS?
2.12¿QUIENEXPONEAPIS?
2.13EXPONLASTÚ
2.14EXPONLASTÚ
2.15EXPONLASTÚ
3APISRESTFUL
3.1¿QUÉESREST?REST(RepresentationalStateTransfer)esunatécnicadearquitecturadesoftwareparasistemashipermediadistribuidoscomolaWorldWideWeb.EnRESTunaURL(UniformResourceLocator)representaunrecurso.SepuedeaccederalrecursoomodificarlomediantelosmétodosdelprotocoloHTTP:
GET,POST,PUT,DELETE
3.2EJEMPLOAPIhttp://myhost.com/talkGET>Devuelvetodaslascharlas.POST>Crearunanuevacharla.
http://myhost.com/talk/123GET>Devuelvelacharlaconid=123PUT>Actualizalacharlaconid=123DELETE>Borralacharlaconid=123
3.3MANEJODEERRORESSepuedenutilizarloserroresdelprotocoloHTTP:200Successful201Created202Accepted301MovedPermanently400BadRequest401Unauthorised402PaymentRequired403Forbidden404NotFound405MethodNotAllowed500InternalServerError501NotImplemented
3.4¿PORQUÉREST?Esmássencillo(tantolaAPIcomolaimplementación).Esmásrápido(peticionesmáslijerasquesepuedencachear).Esmultiformato(HTML,XML,JSON,etc.).SecomplementamuybienconAJAX.
3.5RESTVSRESTFULRESTserefiereauntipodearquitecturadesoftwareSeutilizacomonombreSeutilizacomoporejemplo:success=éxito.
SiunserviciowebesRESTfulindicaqueimplementadichaarquitectura.SeutilizacomoadjetivoSeutilizacomoporejemplo:successful=éxitoso).
3.6RESTVSRESTFULAveceselfulseconfundeconfull=completo.YserefierealosservicioswebRESTfull
YserefierealosservicioswebREST(sinelfull)
AquellosqueimplementanunaAPIcontodoslosmétodosdelprotócoloHTTP.
AquellosqueNOimplementanunaAPIcontodoslosmétodosdelprotócoloHTTP.
4NODE.JS
4.1INTRODUCCIÓN
Node.jspermiteprogramarenJavascriptdelladodelservidor.PensadoparaunmanejodeE/Sorientadaaeventos.
4.2EJECUCIÓNEjecuciónconcurrenteMuchostareas
PeroNOparaleloUnaúnicahebra
4.3¿DÓNDEUSARLO?CuandohaymuchaE/SyportantomuchaCPUinactivaportarea.
YhaymuchosclientesquecompensanesainactividaddelaCPU.
Pensadoparalacreacióndeprogramasderedaltamenteescalables.
4.4OTROSCONCEPTOSnpm :eselgestordepaquetesdeNode.js.
expressjs :esunalibreríaparaNode.jsdedesarrolloweb.
mongoosejs :esunalibreríaparaNode.jsdemodeladodeobjetosdeMongoDB
http://npmjs.org/
http://expressjs.com/
http://mongoosejs.com/
http://www.mongodb.org/
4.5PRIMEROPASOSInstalarNode.js
InstalarMongoDBhttp://nodejs.org/download/
http://docs.mongodb.org/manual/installation/
4.6ABURRIDO
5CÓDIGO
5.1APLAUSOS
5.2PACKAGE.JSONDefinelasdependenciasdenuestroproyecto.
{"name":"api-restful-nodejs-server","version":"0.0.1","dependencies":{"express":"3.x","mongoose":"3.6.20"}}
5.3NPMINSTALLEstecomandoinstalaráenlacarpetanode_moduleslasdependenciasdenuestroproyecto.
npminstall
5.4APP.JSEselficheroprincipal.Elnombreeslodemenos.Avecestambiénselesuelellamarserver.jsParaejecutarunaaplicacióndeNode.js:
nodeapp.js
5.5APP.JS//modulosrequeridosvarhttp,express,mongoose,app,server...
//configuramosappapp.configure(function(){//config...});
//importamoslasrutasvarroutes=require('./routes/talkRoute')(app);
//conectamosconlabasededatosmongoose.connect('mongodb://localhost/gul',function(err,res){//console.log('ConnectedtoGULMongoDBDatabase');});
//arrancamoselservidorserver.listen(3000,function(){//console.log("Serverrunningonhttp://localhost:3000");});
5.6DIRECTORIOSPuedesusarlaestructuradedirectoriosquequieras.Yoheusadoesta:models:routes:services:
5.7MODELSDirectorioconlosmodelosquesevanaguardarenbasededatos.Yocreounficherojsparacadacolección.
5.8MODELS/TALKMODEL.JS//modulosrequeridosvarmongoose=require('mongoose');varSchema=mongoose.Schema;
//definimoselmodelo'talk'consusrestricciones//tambiénpodemosdefinirrelacionesconotrosmodelos//aquínosehahechoporsimplificarvartalkSchema=newSchema({talkName:{type:String,required:true},talkDate:{type:Date,required:true},talkSpeaker:{type:String,required:true},talkSpeakerMail:{type:String,required:true,match:/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/},talkPoints:{type:Number,required:true,default:0}});
//exportamoselmodelomodule.exports=mongoose.model('Talk',talkSchema);
5.9ROUTESDirectorioconlosmapeosdelasrutasdelaAPIRESTful.Aquísólogestionola'request'yel'response'.Transformola'request'enunobjeto'options'yselepasoaunservicio.Loquedevuelvaelserviciolometoenel'response'.Yocreounficherojsparacadacolección.
5.10ROUTES/TALKROUTE.JSmodule.exports=function(app){
varTalkService=require('../services/talkService.js');
varfindTalks=function(req,res){TalkService.findAllTalks({...});};varfindTalk=function(req,res){vartalkId=req.params.talkId;TalkService.findTalkById({...});};varaddTalk=function(req,res){...};varupdateTalk=function(req,res){...};vardeleteTalk=function(req,res){...};
//mapeamosmétodoyURLaunafunciónapp.get('/talk',findTalks);app.get('/talk/:talkId',findTalk);app.post('/talk',addTalk);app.put('/talk/:talkId',updateTalk);app.delete('/talk/:talkId',deleteTalk);}
5.11SERVICESAquíestánlosserviciosqueaccedenabasededatos.Aquínohaynirequestniresponse.Lasfuncionesrecibenunobjeto'options'conloquenecesita.Normalmentedebengestionaralmenosun'onSuccess'yun'onError'.Hayfuncionesqueademásgestionanun'onNotFound'.Unserviciopuedellamaraotrosservicios.Yocreounficherojsparacadacolección.
5.12SERVICES/TALKSERVICE.JS//importamoselmodelovarTalk=require('../models/talkModel.js');
varfindAllTalks=function(options){Talk.find(function(error,talks){...});};varfindTalkById=function(options){Talk.findById(options.talkId,function(error,talk){...});};varsaveTalk=function(options){...};varfindTalkByIdAndUpdate=function(options){...};varfindTalkByIdAndRemove=function(options){...});
//exportamoslosserviciosexports.findAllTalks=findAllTalks;exports.findTalkById=findTalkById;exports.saveTalk=saveTalk;exports.findTalkByIdAndUpdate=findTalkByIdAndUpdate;exports.findTalkByIdAndRemove=findTalkByIdAndRemove;
6DEMO
7¿ALGUNAPREGUNTA?