Home Identifier Source Repository

lib/stores/CountableStore.js

  1. "use strict";
  2.  
  3. import BaseStore from "./BaseStore";
  4. import ObjectHash from "object-hash";
  5.  
  6. /**
  7. * An object representing a resource query.
  8. *
  9. * Can be one of the following:
  10. * * `number` - Assumes the value is a resource id
  11. * * `string` - Assumes the value is a resource id
  12. * * `object` - Will be converted to a query string
  13. * @typedef {number|string|object} ResourceQuery
  14. */
  15.  
  16. function hash(obj) {
  17. return ObjectHash.sha1(obj || {});
  18. }
  19.  
  20. /**
  21. * A base class for resource stores that are countable (have /count.json endpoints).
  22. *
  23. * @extends {BaseStore}
  24. */
  25. export default class extends BaseStore {
  26. /**
  27. * @param {APIDispatcher} dispatcher - The dispatcher to register with
  28. * @param {Actions} actions
  29. */
  30. constructor(dispatcher, actions) {
  31. super(dispatcher, actions);
  32. this._counts = {};
  33. }
  34.  
  35. /**
  36. * Returns the count for the given query
  37. *
  38. * @param {ResourceQuery} [query]
  39. *
  40. * @return {number}
  41. */
  42. count(query) {
  43. return this._counts[hash(query)] || 0;
  44. }
  45.  
  46. /**
  47. * @override
  48. */
  49. reduce(state, action) {
  50. if (action.actionType === this._actions.countAction) {
  51. this._counts[hash(action.query)] = action.count;
  52. this.__emitChange();
  53. return state;
  54. }
  55.  
  56. return super.reduce(state, action);
  57. }
  58. }