cache.js 1.6 KB

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