2015-04-15 26 views
7

nodeJS ile dinlendirici bir API geliştiriyorum.Polimorfizm nodeJS

exports.postCreature = function (req, res) { 

    var creature = new Creature({ 
      name: req.body.name, id_user: req.user._id 
     }); 

    creature.save(function (err) { 
     if (err) 
      res.status(400).send(Error.setError('impossible to save the your creature', err)); 
     else 
      res.status(201).send(); 
    }); 
}; 

//CODE DUPLICATE 
exports.createCreature = function(user, callback) { 
    console.log('Creature created'); 
    var creature = new Creature({ 
     name: user.username, id_user: user._id 
    }); 

    creature.save(function (err) { 
     if (err) 
      callback(err, null); 
     else 
      callback(null, creature); 
    }); 
} 

İki işlev aynı kodu ancak aynı parametrelerle yürütmez. Kodumda çoğaltma yapmaktan kaçınmak istiyorum.

Kodumun çoğaltılmasını önlemek için nasıl yapabilirim? Diğer fonksiyonlarda sonra

function createCreature (creatureName, user, callback) { 
    console.log('Creature created'); 
    var creature = new Creature({ 
     name: creatureName, id_user: user._id 
    }); 

    creature.save(function (err, creature) { 
     if (err) 
      callback(err, null); 
     else 
      callback(null, creature); 
    }); 
} 

Ve:

+0

bir nesne olduğunu ama farklı özellikleriyle (varlıklarını kontrol edebilirdiniz) ve ikinci argüman * ne yapılacağını saptamanın başka bir yolu olan * XHR veya Fonksiyonudur. – Touffy

cevap

7

Ben fazlalıklar işlemek için başka bir fonksiyon yaratacak o da işleve ilk argüman benziyor Kodunuzla itibaren

exports.postCreature = function (req, res) { 
    createCreature(req.body.name, req.user, function (err, creature) { 
     if (err) 
      res.status(400).send(Error.setError('impossible to save the your creature', err)); 
     else 
      res.status(201).send(); 
    }; 
}; 

exports.createCreature = function(user, callback) { 
    console.log('Creature created'); 
    createCreature (user.username, user, callback); 
} 
+0

Bu iyi çalışıyor! – Bob

+0

Yay! Yardımcı olduğuma sevindim! –