MrLiar 2015-11-09
NodeJSRESTfulServicewithGulpandExpress
HowtomakeExpressJSandServicesLayerworkingtogether?
Hereismyapp.js
/*jslintnode:true*/
'usestrict';
varexpress=require('express');
varbodyParser=require('body-parser');
varrouter=require('./route');
varapp=express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/',router);
app.set('port',process.env.PORT||3000);
app.listen(app.get('port'));
console.log('Runningserveronport'+app.get('port')+'.');
Hereistheroute.jswhichismyrouter,butalsoIconstructtheserviceslayerhereaswell.
/*jslintnode:true*/
'usestrict';
varexpress=require('express');
varconfig=require('./lib/config');
varlog4js=require('log4js');
varHashMap=require('hashmap').HashMap;
varemailscan=require('./lib/emailservice');
varaccount_controller=require('./controller/account.controller.js');
varjob_controller=require('./controller/job.controller.js');
varattachment_controller=require('./controller/attachment.controller.js');
//holdalltheservices
varservices=newHashMap();
//setupconfig
config.load(__dirname+'/config','test-conf');
services.set('config',config);
//setuplogger
log4js.configure(__dirname+'/config/log/'+config.data.logConfigFileName,config.data.log4js);
varlogger=log4js.getLogger('root');
services.set('logger',logger);
//setupemailscan
emailservice.services=services;
emailservice.init(services);
services.set('emailscan',emailscan);
//setupcontrollers
account_controller.init(services);
job_controller.init(services);
attachment_controller.init(services);
//routingconfiguration
varrouter=express.Router();
router.get('/accounts/:email',account_controller.getAccountByEmail);
router.post('/jobs/scan',job_controller.scanJobs);
router.get('/jobs/:accountId/:messageId',job_controller.getJob);
module.exports=router;
Hereisoneexampleofthecontroller,whichisaccount.controller.js
/*jslintnode:true*/
'usestrict';
varHashMap=require('hashmap').HashMap;
varservices=null;
module.exports={
getAccountByEmail:function(req,res){
//services
varemailscan=services.get('emailservice');
varlogger=services.get('logger');
//params
varemail=req.params.email;
emailscan.fetchAccountInfoByEmail(email,function(err,account){
logger.debug("accountinfo="+account.id);
res.json(account);
});
},
init:function(myservices){
services=myservices;
}
};
WarningInfo:
body-parserdeprecatedbodyParser:useindividualjson/urlencodedmiddlewaresapp.js:8:9
body-parserdeprecatedundefinedextended:provideextendedoptionnode_modules/body-parser/index.js:105:29
Solution:
Changethebodyparserpartasfollow:
varapp=express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
References:
should.jsprovidethetestassertion
http://unitjs.com/guide/should-js.html
underscoreenhancetheJSoperation
http://underscorejs.org/#filter
onlineJSONeditortovalidatetheresponse
http://www.jsoneditoronline.org/
olderblogaboutRESTful
https://github.com/luohuazju/easy/tree/master/easynodejs/buglist