dao-factory-manager.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var Toposort = require('toposort-class')
  2. , DaoFactory = require('./dao-factory')
  3. module.exports = (function() {
  4. var DAOFactoryManager = function(sequelize) {
  5. this.daos = []
  6. this.sequelize = sequelize
  7. }
  8. DAOFactoryManager.prototype.addDAO = function(dao) {
  9. this.daos.push(dao)
  10. return dao
  11. }
  12. DAOFactoryManager.prototype.removeDAO = function(dao) {
  13. this.daos = this.daos.filter(function(_dao) {
  14. return _dao.name != dao.name
  15. })
  16. }
  17. DAOFactoryManager.prototype.getDAO = function(daoName, options) {
  18. options = options || {}
  19. options.attribute = options.attribute || 'name'
  20. var dao = this.daos.filter(function(dao) {
  21. return dao[options.attribute] === daoName
  22. })
  23. return !!dao ? dao[0] : null
  24. }
  25. DAOFactoryManager.prototype.__defineGetter__('all', function() {
  26. return this.daos
  27. })
  28. /**
  29. * Iterate over DAOs in an order suitable for e.g. creating tables. Will
  30. * take foreign key constraints into account so that dependencies are visited
  31. * before dependents.
  32. */
  33. DAOFactoryManager.prototype.forEachDAO = function(iterator) {
  34. var daos = {}
  35. , sorter = new Toposort()
  36. this.daos.forEach(function(dao) {
  37. var deps = []
  38. daos[dao.tableName] = dao
  39. for (var attrName in dao.rawAttributes) {
  40. if (dao.rawAttributes.hasOwnProperty(attrName)) {
  41. if (dao.rawAttributes[attrName].references) {
  42. deps.push(dao.rawAttributes[attrName].references)
  43. }
  44. }
  45. }
  46. deps = deps.filter(function (dep) {
  47. return dao.tableName !== dep
  48. })
  49. sorter.add(dao.tableName, deps)
  50. })
  51. sorter.sort().reverse().forEach(function(name) {
  52. iterator(daos[name], name)
  53. })
  54. }
  55. return DAOFactoryManager
  56. })()