cache.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const Schema = require('warehouse').Schema;
  3. const Promise = require('bluebird');
  4. module.exports = ctx => {
  5. const Cache = new Schema({
  6. _id: {type: String, required: true},
  7. hash: {type: String, default: ''},
  8. modified: {type: Number, default: Date.now}
  9. });
  10. Cache.static('compareFile', function(id, hashFn, statFn) {
  11. const cache = this.findById(id);
  12. const self = this;
  13. let mtime;
  14. // If cache does not exist, then it must be a new file. We have to get both
  15. // file hash and stats.
  16. if (!cache) {
  17. return Promise.all([hashFn(id), statFn(id)]).spread((hash, stats) => self.insert({
  18. _id: id,
  19. hash,
  20. modified: stats.mtime
  21. })).thenReturn({
  22. type: 'create'
  23. });
  24. }
  25. // Get file stats
  26. return statFn(id).then(stats => {
  27. mtime = stats.mtime;
  28. // Skip the file if the modified time is unchanged
  29. if (cache.modified === mtime) {
  30. return {
  31. type: 'skip'
  32. };
  33. }
  34. // Get file hash
  35. return hashFn(id);
  36. }).then(result => {
  37. // If the result is an object, skip the following steps because it's an
  38. // unchanged file
  39. if (typeof result === 'object') return result;
  40. const hash = result;
  41. // Skip the file if the hash is unchanged
  42. if (cache.hash === hash) {
  43. return {
  44. type: 'skip'
  45. };
  46. }
  47. // Update cache info
  48. cache.hash = hash;
  49. cache.modified = mtime;
  50. return cache.save().thenReturn({
  51. type: 'update'
  52. });
  53. });
  54. });
  55. return Cache;
  56. };