PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/db/collection.js

https://bitbucket.org/cinos/comicvine-client
JavaScript | 111 lines | 84 code | 15 blank | 12 comment | 16 complexity | 2529b47d682e0dcefd401b6159d82a60 MD5 | raw file
  1. var backbone = require('backbone');
  2. var Collection = backbone.Collection.extend({
  3. pageSize: 100,
  4. total: 0,
  5. lastPage: -1,
  6. ttl: 1000 * 60 * 60 * 24 * 7,
  7. url: function(options) {
  8. var url = this.baseUrl + "?format=json";
  9. if (typeof options.page == "number" || this.pageSize !== 100) {
  10. var offset = (options.page||0)*this.pageSize;
  11. var limit = this.pageSize;
  12. url += "&offset="+offset+"&limit="+limit;
  13. }
  14. return url;
  15. },
  16. fetchAll: function(callbacks) {
  17. var each = callbacks.each;
  18. var error = callbacks.error;
  19. var success = callbacks.success;
  20. var collection = this;
  21. function nextPage() {
  22. if (collection.hasMorePages()) {
  23. collection.fetchNextPage({
  24. success:function(){
  25. if (typeof each == "function") {
  26. each(collection);
  27. }
  28. process.nextTick(nextPage);
  29. },
  30. error: error
  31. })
  32. } else {
  33. if (typeof success == "function") {
  34. success(collection);
  35. }
  36. }
  37. }
  38. nextPage();
  39. },
  40. loadAllItems: function(each) {
  41. var collection = this;
  42. this.invoke('fetch');
  43. /*
  44. function loadItem(item) {
  45. var model = collection.at(item);
  46. if (model) {
  47. model.fetch({success: function() {
  48. each();
  49. loadItem(item+1);
  50. }});
  51. }
  52. };
  53. */
  54. //loadItem(0);
  55. },
  56. parse: function(response) {
  57. this.isLoading = false;
  58. this.total = response["number_of_total_results"];
  59. this.lastPage = (response["offset"] || response["limit"] / response["limit"]) - 1;
  60. return response.results;
  61. },
  62. fetchNextPage: function(callbacks) {
  63. if (!this.isLoading) {
  64. this.fetch({
  65. page: this.lastPage+1,
  66. success: callbacks.success,
  67. error: callbacks.error,
  68. add: true
  69. });
  70. this.isLoading = true;
  71. }
  72. },
  73. hasMorePages: function() {
  74. return (this.total===0 || this.total > (this.lastPage*this.pageSize));
  75. },
  76. createItem: function(data) {
  77. var returnSingle = false;
  78. if (!Array.isArray(data)) {
  79. data = [data];
  80. returnSingle = true;
  81. }
  82. var result = [];
  83. for (var i = 0, len=data.length; i<len; i++) {
  84. var rawModel = data[i];
  85. var currentModel = this.get(rawModel.id);
  86. if (currentModel) {
  87. result[i] = currentModel;
  88. } else {
  89. result[i] = new this.model(rawModel);
  90. this.add(result[i]);
  91. }
  92. }
  93. return returnSingle?result[0]:result;
  94. }
  95. });
  96. module.exports = Collection;