bootstrap-table-pipeline.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * @author doug-the-guy
  3. * @version v1.0.0
  4. *
  5. * Bootstrap Table Pipeline
  6. * -----------------------
  7. *
  8. * This plugin enables client side data caching for server side requests which will
  9. * eliminate the need to issue a new request every page change. This will allow
  10. * for a performance balance for a large data set between returning all data at once
  11. * (client side paging) and a new server side request (server side paging).
  12. *
  13. * There are two new options:
  14. * - usePipeline: enables this feature
  15. * - pipelineSize: the size of each cache window
  16. *
  17. * The size of the pipeline must be evenly divisible by the current page size. This is
  18. * assured by rounding up to the nearest evenly divisible value. For example, if
  19. * the pipeline size is 4990 and the current page size is 25, then pipeline size will
  20. * be dynamically set to 5000.
  21. *
  22. * The cache windows are computed based on the pipeline size and the total number of rows
  23. * returned by the server side query. For example, with pipeline size 500 and total rows
  24. * 1300, the cache windows will be:
  25. *
  26. * [{'lower': 0, 'upper': 499}, {'lower': 500, 'upper': 999}, {'lower': 1000, 'upper': 1499}]
  27. *
  28. * Using the limit (i.e. the pipelineSize) and offset parameters, the server side request
  29. * **MUST** return only the data in the requested cache window **AND** the total number of rows.
  30. * To wit, the server side code must use the offset and limit parameters to prepare the response
  31. * data.
  32. *
  33. * On a page change, the new offset is checked if it is within the current cache window. If so,
  34. * the requested page data is returned from the cached data set. Otherwise, a new server side
  35. * request will be issued for the new cache window.
  36. *
  37. * The current cached data is only invalidated on these events:
  38. * * sorting
  39. * * searching
  40. * * page size change
  41. * * page change moves into a new cache window
  42. *
  43. * There are two new events:
  44. * - cached-data-hit.bs.table: issued when cached data is used on a page change
  45. * - cached-data-reset.bs.table: issued when the cached data is invalidated and a
  46. * new server side request is issued
  47. *
  48. **/
  49. const Utils = $.fn.bootstrapTable.utils
  50. $.extend($.fn.bootstrapTable.defaults, {
  51. usePipeline: false,
  52. pipelineSize: 1000,
  53. onCachedDataHit (data) {
  54. return false
  55. },
  56. onCachedDataReset (data) {
  57. return false
  58. }
  59. })
  60. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  61. 'cached-data-hit.bs.table': 'onCachedDataHit',
  62. 'cached-data-reset.bs.table': 'onCachedDataReset'
  63. })
  64. const BootstrapTable = $.fn.bootstrapTable.Constructor
  65. const _init = BootstrapTable.prototype.init
  66. const _initServer = BootstrapTable.prototype.initServer
  67. const _onSearch = BootstrapTable.prototype.onSearch
  68. const _onSort = BootstrapTable.prototype.onSort
  69. const _onPageListChange = BootstrapTable.prototype.onPageListChange
  70. BootstrapTable.prototype.init = function (...args) {
  71. // needs to be called before initServer()
  72. this.initPipeline()
  73. _init.apply(this, Array.prototype.slice.apply(args))
  74. }
  75. BootstrapTable.prototype.initPipeline = function () {
  76. this.cacheRequestJSON = {}
  77. this.cacheWindows = []
  78. this.currWindow = 0
  79. this.resetCache = true
  80. }
  81. BootstrapTable.prototype.onSearch = function (event) {
  82. /* force a cache reset on search */
  83. if (this.options.usePipeline) {
  84. this.resetCache = true
  85. }
  86. _onSearch.apply(this, Array.prototype.slice.apply(arguments))
  87. }
  88. BootstrapTable.prototype.onSort = function (event) {
  89. /* force a cache reset on sort */
  90. if (this.options.usePipeline) {
  91. this.resetCache = true
  92. }
  93. _onSort.apply(this, Array.prototype.slice.apply(arguments))
  94. }
  95. BootstrapTable.prototype.onPageListChange = function (event) {
  96. /* rebuild cache window on page size change */
  97. const target = $(event.currentTarget)
  98. const newPageSize = parseInt(target.text())
  99. this.options.pipelineSize = this.calculatePipelineSize(this.options.pipelineSize, newPageSize)
  100. this.resetCache = true
  101. _onPageListChange.apply(this, Array.prototype.slice.apply(arguments))
  102. }
  103. BootstrapTable.prototype.calculatePipelineSize = (pipelineSize, pageSize) => {
  104. /* calculate pipeline size by rounding up to the nearest value evenly divisible
  105. * by the pageSize */
  106. if (pageSize === 0) return 0
  107. return Math.ceil(pipelineSize / pageSize) * pageSize
  108. }
  109. BootstrapTable.prototype.setCacheWindows = function () {
  110. /* set cache windows based on the total number of rows returned by server side
  111. * request and the pipelineSize */
  112. this.cacheWindows = []
  113. const numWindows = this.options.totalRows / this.options.pipelineSize
  114. for (let i = 0; i <= numWindows; i++) {
  115. const b = i * this.options.pipelineSize
  116. this.cacheWindows[i] = {'lower': b, 'upper': b + this.options.pipelineSize - 1}
  117. }
  118. }
  119. BootstrapTable.prototype.setCurrWindow = function (offset) {
  120. /* set the current cache window index, based on where the current offset falls */
  121. this.currWindow = 0
  122. for (let i = 0; i < this.cacheWindows.length; i++) {
  123. if (this.cacheWindows[i].lower <= offset && offset <= this.cacheWindows[i].upper) {
  124. this.currWindow = i
  125. break
  126. }
  127. }
  128. }
  129. BootstrapTable.prototype.drawFromCache = function (offset, limit) {
  130. /* draw rows from the cache using offset and limit */
  131. const res = $.extend(true, {}, this.cacheRequestJSON)
  132. const drawStart = offset - this.cacheWindows[this.currWindow].lower
  133. const drawEnd = drawStart + limit
  134. res.rows = res.rows.slice(drawStart, drawEnd)
  135. return res
  136. }
  137. BootstrapTable.prototype.initServer = function (silent, query, url) {
  138. /* determine if requested data is in cache (on paging) or if
  139. * a new ajax request needs to be issued (sorting, searching, paging
  140. * moving outside of cached data, page size change)
  141. * initial version of this extension will entirely override base initServer
  142. **/
  143. let data = {}
  144. const index = this.header.fields.indexOf(this.options.sortName)
  145. let params = {
  146. searchText: this.searchText,
  147. sortName: this.options.sortName,
  148. sortOrder: this.options.sortOrder
  149. }
  150. let request = null
  151. if (this.header.sortNames[index]) {
  152. params.sortName = this.header.sortNames[index]
  153. }
  154. if (this.options.pagination && this.options.sidePagination === 'server') {
  155. params.pageSize = this.options.pageSize === this.options.formatAllRows()
  156. ? this.options.totalRows : this.options.pageSize
  157. params.pageNumber = this.options.pageNumber
  158. }
  159. if (!(url || this.options.url) && !this.options.ajax) {
  160. return
  161. }
  162. let useAjax = true
  163. if (this.options.queryParamsType === 'limit') {
  164. params = {
  165. searchText: params.searchText,
  166. sortName: params.sortName,
  167. sortOrder: params.sortOrder
  168. }
  169. if (this.options.pagination && this.options.sidePagination === 'server') {
  170. params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize
  171. params.offset = (this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize) * (this.options.pageNumber - 1)
  172. if (this.options.usePipeline) {
  173. // if cacheWindows is empty, this is the initial request
  174. if (!this.cacheWindows.length) {
  175. useAjax = true
  176. params.drawOffset = params.offset
  177. // cache exists: determine if the page request is entirely within the current cached window
  178. } else {
  179. const w = this.cacheWindows[this.currWindow]
  180. // case 1: reset cache but stay within current window (e.g. column sort)
  181. // case 2: move outside of the current window (e.g. search or paging)
  182. // since each cache window is aligned with the current page size
  183. // checking if params.offset is outside the current window is sufficient.
  184. // need to requery for preceding or succeeding cache window
  185. // also handle case
  186. if (this.resetCache || (params.offset < w.lower || params.offset > w.upper)) {
  187. useAjax = true
  188. this.setCurrWindow(params.offset)
  189. // store the relative offset for drawing the page data afterwards
  190. params.drawOffset = params.offset
  191. // now set params.offset to the lower bound of the new cache window
  192. // the server will return that whole cache window
  193. params.offset = this.cacheWindows[this.currWindow].lower
  194. // within current cache window
  195. } else {
  196. useAjax = false
  197. }
  198. }
  199. } else {
  200. if (params.limit === 0) {
  201. delete params.limit
  202. }
  203. }
  204. }
  205. }
  206. // force an ajax call - this is on search, sort or page size change
  207. if (this.resetCache) {
  208. useAjax = true
  209. this.resetCache = false
  210. }
  211. if (this.options.usePipeline && useAjax) {
  212. /* in this scenario limit is used on the server to get the cache window
  213. * and drawLimit is used to get the page data afterwards */
  214. params.drawLimit = params.limit
  215. params.limit = this.options.pipelineSize
  216. }
  217. // cached results can be used
  218. if (!useAjax) {
  219. const res = this.drawFromCache(params.offset, params.limit)
  220. this.load(res)
  221. this.trigger('load-success', res)
  222. this.trigger('cached-data-hit', res)
  223. return
  224. }
  225. // cached results can't be used
  226. // continue base initServer code
  227. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  228. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  229. }
  230. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  231. $.extend(data, query || {})
  232. // false to stop request
  233. if (data === false) {
  234. return
  235. }
  236. if (!silent) {
  237. this.$tableLoading.show()
  238. }
  239. const self = this
  240. request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  241. type: this.options.method,
  242. url: url || this.options.url,
  243. data: this.options.contentType === 'application/json' && this.options.method === 'post'
  244. ? JSON.stringify(data) : data,
  245. cache: this.options.cache,
  246. contentType: this.options.contentType,
  247. dataType: this.options.dataType,
  248. success (res) {
  249. res = Utils.calculateObjectValue(self.options, self.options.responseHandler, [res], res)
  250. // cache results if using pipelining
  251. if (self.options.usePipeline) {
  252. // store entire request in cache
  253. self.cacheRequestJSON = $.extend(true, {}, res)
  254. // this gets set in load() also but needs to be set before
  255. // setting cacheWindows
  256. self.options.totalRows = res[self.options.totalField]
  257. // if this is a search, potentially less results will be returned
  258. // so cache windows need to be rebuilt. Otherwise it
  259. // will come out the same
  260. self.setCacheWindows()
  261. self.setCurrWindow(params.drawOffset)
  262. // just load data for the page
  263. res = self.drawFromCache(params.drawOffset, params.drawLimit)
  264. self.trigger('cached-data-reset', res)
  265. }
  266. self.load(res)
  267. self.trigger('load-success', res)
  268. if (!silent) self.$tableLoading.hide()
  269. },
  270. error (res) {
  271. let data = []
  272. if (self.options.sidePagination === 'server') {
  273. data = {}
  274. data[self.options.totalField] = 0
  275. data[self.options.dataField] = []
  276. }
  277. self.load(data)
  278. self.trigger('load-error', res.status, res)
  279. if (!silent) self.$tableLoading.hide()
  280. }
  281. })
  282. if (this.options.ajax) {
  283. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  284. } else {
  285. if (this._xhr && this._xhr.readyState !== 4) {
  286. this._xhr.abort()
  287. }
  288. this._xhr = $.ajax(request)
  289. }
  290. }