Advertisement
Guest User

Untitled

a guest
Jan 28th, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /**
  2. * FILE: api/hooks/reindex-db.js
  3. *
  4. * Created by mcrowe on 1/28/15.
  5. *
  6. * Insures indices recreated if needed, and allows complex indicies to be specified in the model as well. Example:
  7. *
  8. module.exports = {
  9. schema : true,
  10. version : "1.3",
  11. attributes: {
  12. ...
  13. nextCheckDateMax: { type: 'DATE', index: true },
  14. currentSequenceNumber: { type: 'INTEGER' },
  15. enabled: { type: 'BOOLEAN', defaultsTo: true }
  16. },
  17. compoundIndices: {
  18. ci_1: { nextCheckDateMax: 1, currentSequenceNumber: 1 }
  19. }
  20. }
  21.  
  22. */
  23.  
  24. var _ = require('lodash');
  25.  
  26. function ensureIndexCreated(model, collection) {
  27. var promises = [];
  28. _.each(model.attributes, function(params, index) {
  29. if ( _.has(params,'index') ) {
  30. collection.ensureIndex(index, {background: true}, function(err) {
  31. if ( err ) {
  32. console.log('Error re-indexing collection', err);
  33. }
  34. });
  35. }
  36. });
  37. _.each(model.compoundIndices, function(index) {
  38. collection.ensureIndex(index, {background: true}, function(err) {
  39. if ( err ) {
  40. console.log('Error re-indexing collection', err);
  41. }
  42. });
  43. });
  44. return [];
  45. }
  46.  
  47. module.exports = function hook(sails) {
  48. return {
  49. /**
  50. * Private hook method to do actual database data operations.
  51. *
  52. * @param {Function} next Callback function to call after all is done
  53. */
  54. indexDatabase: function indexDatabase(next) {
  55. _.each(sails.models, function(model) {
  56. model.native(function(err, collection) { ensureIndexCreated(model, collection); });
  57. });
  58. console.log("Indices rebuild");
  59. next();
  60. },
  61.  
  62. /**
  63. * Method that runs automatically when the hook initializes itself.
  64. *
  65. * @param {Function} next Callback function to call after all is done
  66. */
  67. initialize: function initialize(next) {
  68. var hook = this;
  69.  
  70. // Wait for sails orm hook to be loaded
  71. sails.after('hook:orm:loaded', function onAfter() {
  72. hook.indexDatabase(next);
  73. });
  74. }
  75. }
  76. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement