AiNoTame

Dio è nella pioggia.
posts - 17, comments - 127, trackbacks - 0

Webapi-like controllers in NodeJS+ExpressJS

Lavorando su un progetto ~MEAN (MongoDB + ExpressJS + AngularJS + nodeJS) mi sono chiesto: “perchè non creare un modulo di registrazione custom dei controller simile a quella delle webapi di asp.net”? da qui è nato il seguente modulo:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var path = require('path');
var fs = require('fs');
var config = require('./config');
var _ = require('lodash');

var getControllersInServerFolder = function (serverFolder) {
    if (_.isEmpty(serverFolder)) {
        serverFolder = config.settings.controllersFolder;
    }

    var controllers = [];

    var fileSystemObjects = fs.readdirSync(serverFolder); //read folder content
    if (_.isArray(fileSystemObjects)) {
        _.forEach(fileSystemObjects, function (fso) {
            var fsoFullPath = path.join(serverFolder, fso);
            var fsoStat = fs.statSync(fsoFullPath);
            if (fsoStat.isFile() && fso.endsWith('controller.js')) {
                controllers.push(require(path.relative(__dirname, fsoFullPath)));
            } else if (fsoStat.isDirectory()) {
                _.union(controllers, getControllersInServerFolder(fsoFullPath));
            }
        });
    }

    return controllers;
};

exports.getControllers = getControllersInServerFolder;

Quindi nello startup del server nodejs:

1
2
3
_.forEach(require('controllers-manager')..getControllers(), function(controller) {
	server.use(controller.path, controller.router); // register route into expressjs
});

Ora i controller sono tutti quei files definiti nella cartella config.settings.controllersFolder (o sottocartelle) che terminano con ‘controller.js’ e hanno tutti la seguente struttura:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var express = require('express');
var router = express.Router();

//apply before any actions (check authorizations...)
router.use(function(req, res, next) {
	next(); //go to next 
});

router.get('/message', function(req, res, next) {
	res.send({'Hello world'});
});

exports.path = '/api/sample';
exports.router = router;

Facile, semplice e veloce.

Print | posted on Sunday, October 12, 2014 3:49 PM | Filed Under [ Javascript Nodejs ]

Feedback

Gravatar

# erectile curve

erectile pills without a doctor prescription
erectile pills over the counter
online doctor erectile dysfunction
best drugs for ed
erectile destroyer http://eddrugsgeneric.com/
6/8/2018 2:19 AM | buy erectile
Gravatar

# erectile function healthy dads healthy kids

erectile method
best erectile dysfunction pills
erectile medication where to purchase
best drugs for ed
erectile rehabilitation therapy http://eddrugsgeneric.com/
6/8/2018 4:21 AM | erectile pills
Gravatar

# generic low dose cialis buy.ci.al.is.o.nl.i.ne.

generic cialis super active reviewcialis 5 mg prezzo genericocialis generic soft tabcialis huiduitslagcialis in uk kaufenorder cialis no prescriptioncialis 20 mg costcialis met hoge bloeddrukcialis 5 mg beipackzettelconstructeur automobile presse sp cialis ecould cialis help men achieve orgasmcialis 20 mg durataviagra cialis preciovergleich viagra mit cialisviagra cialis parduoducialis effect on womendo viagra and cialis work the same way
cialis therapie Generic for cialis
cialis cost Cialis 5 mg
cialis australian price http://babecolate.com/
cialis achat internetcialis usage for recreational sexbuy cialis whereviagra levitra cialis stuffy nosealternate between viagra and cialiscompare cost viagra levitra cialishow many people use cialisgeneric cialis with dapoxetinewlagreen price for cialisgeneric cialis from india byingeffet cialis dureecialis heatcialis in belgie kopencialis pillwhich pill works better viagra or cialisfast cialis onlinetype web cialischeap cialis soft
6/9/2018 5:08 AM | CoreyRox
Gravatar

# viagra no presc b.u.y.cialiso.n.l.ine.

cialis non generic from canadaonly now cialis for sale in usdoes cialis work on womenlevitra vs cialis vs viagra reviewsbangkok cialiscialis c20 reviewcialis online pharmacy canadiancomprar viagra y cialis onlinetestimony cialis softque es mejor cialis viagra o levitracialis reviews drugs.combuy cialis canadacheap cialis without a prescriptionviagra vs cialis daily
safe dosage for cialis Tadalafil
acheter cialis kamagra Cialis tadalafil
safe site to buy cialis online http://babecolate.com/
cialis canadacialis 20 mg costo in farmaciacialis ja viagra samaan aikaansoft cialis 120 tabletsonline medicine rx cialis viagra orderwhat does cialis look likewhite finger disease cialis researchcialis ohio pa prescribemail order cialis soft onlinelilly icos llc cialis professionalname brand cialislevitra contra cialisviagra cialis parduodublue cross health cialisu 15640 cialisforums viagra vs cialiscialis online napolla pela cialis
6/9/2018 7:04 AM | CoreyRox
Gravatar

# low dose cialis blood pressure bu.yc.i.al.is.onl.i.ne

cialis problemen erectie veroorzaakt medicatieflashback cialis viagrared cialis viagra 200mgverschil tussen cialis en viagrabuying cialis soft in mexicoherbal alternative cialis softworks better viagra cialisbuy cialis online forumwaar kun je cialis kopenus cialis softflowmax and cialisbuy low cost cialis softhow does cialis worfungsi viagra cialisacheter cialis meilleur pricialis c5 reviewcialis online no presriptionwaar kan ik veilig cialis kopenviagra cialis heart problems
cialis professional yohimbe Cialis 5 mg
generic for cialis Cialis generico
cialis flussig http://cialisonl.com/
cialis dysfunction pillviagra cialis studycialis tadalafil under tongue dissolvedouble dose of cialisacheter du cialis a geneveviagra and cialis expiry notice spamcialis generic pharmacycialis 10 mg precio mexicocialis eacutecialis usa pharmacyes mejor el viagra o el cialiscialis periodontal diseasecialis 5mg how long to workinternet pharmacy cialis buy onlineg postmessage cialis smiley rememberindicaciones del cialis 5 mgcialis 20 mg how does it workgood screw with viagra href cialissex shops amsterdam cialis
6/11/2018 10:56 PM | CoreyRox
Gravatar

# cialis great britain buyc.i.a.li.son.l.i.n.e.

cialis pills price eachcialis watermelon rind chemical comparisondiferenta dintre cialis si viagracialis price online cialis priceu 19835 cialiscialis generic priceprice viagra vs cialisviagra vs cialis for bphcialis tadalafil viagracomparison between vardenafil cialis and viagracialis le weekendercialis g7order cialis soft without prescriptioncheap cialis pillstorefill online prescription cialis softcialis elke dagcialis generika zollproblemecialis ophalen utrechtcialis 5 mg ipertrofia prostatica
cialis pills price each Tadalafil
american pharmacy cialis Cialis 5mg
cialis rckenschmerzen http://cialisvus.com/
how long does cialis workgeneric cialis from india warningcialis soft tabs cheapcialis cialis ukcialis valtrex alessetadacip 20 mg (generic cialis)subaction showcomments cialis smile watchbuy cialis online without a prescriptioncialis supperstoreviagra and cialis mixedfacts about cialisoriginele cialis kopencialis losing effectiveness
6/13/2018 7:52 PM | CoreyRox

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 7 and 7 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET