仰望星辰工作室

better-staridc-MNBT

better-staridc-MNBT/ imsetes/js/bootstrap-table/extensions/pipeline/bootstrap-table-pipeline.js 11.3 KB · 320 行 原始文件
Z zfhsh first commit 2 个月前
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
50const Utils = $.fn.bootstrapTable.utils
51
52$.extend($.fn.bootstrapTable.defaults, {
53 usePipeline: false,
54 pipelineSize: 1000,
55 onCachedDataHit (data) {
56 return false
57 },
58 onCachedDataReset (data) {
59 return false
60 }
61})
62
63$.extend($.fn.bootstrapTable.Constructor.EVENTS, {
64 'cached-data-hit.bs.table': 'onCachedDataHit',
65 'cached-data-reset.bs.table': 'onCachedDataReset'
66})
67
68const BootstrapTable = $.fn.bootstrapTable.Constructor
69const _init = BootstrapTable.prototype.init
70const _initServer = BootstrapTable.prototype.initServer
71const _onSearch = BootstrapTable.prototype.onSearch
72const _onSort = BootstrapTable.prototype.onSort
73const _onPageListChange = BootstrapTable.prototype.onPageListChange
74
75BootstrapTable.prototype.init = function (...args) {
76 // needs to be called before initServer()
77 this.initPipeline()
78 _init.apply(this, Array.prototype.slice.apply(args))
79}
80
81BootstrapTable.prototype.initPipeline = function () {
82 this.cacheRequestJSON = {}
83 this.cacheWindows = []
84 this.currWindow = 0
85 this.resetCache = true
86}
87
88BootstrapTable.prototype.onSearch = function (event) {
89 /* force a cache reset on search */
90 if (this.options.usePipeline) {
91 this.resetCache = true
92 }
93 _onSearch.apply(this, Array.prototype.slice.apply(arguments))
94}
95
96BootstrapTable.prototype.onSort = function (event) {
97 /* force a cache reset on sort */
98 if (this.options.usePipeline) {
99 this.resetCache = true
100 }
101 _onSort.apply(this, Array.prototype.slice.apply(arguments))
102}
103
104BootstrapTable.prototype.onPageListChange = function (event) {
105 /* rebuild cache window on page size change */
106 const target = $(event.currentTarget)
107 const newPageSize = parseInt(target.text())
108 this.options.pipelineSize = this.calculatePipelineSize(this.options.pipelineSize, newPageSize)
109 this.resetCache = true
110 _onPageListChange.apply(this, Array.prototype.slice.apply(arguments))
111}
112
113BootstrapTable.prototype.calculatePipelineSize = (pipelineSize, pageSize) => {
114 /* calculate pipeline size by rounding up to the nearest value evenly divisible
115 * by the pageSize */
116 if (pageSize === 0) return 0
117 return Math.ceil(pipelineSize / pageSize) * pageSize
118}
119
120BootstrapTable.prototype.setCacheWindows = function () {
121 /* set cache windows based on the total number of rows returned by server side
122 * request and the pipelineSize */
123 this.cacheWindows = []
124 const numWindows = this.options.totalRows / this.options.pipelineSize
125 for (let i = 0; i <= numWindows; i++) {
126 const b = i * this.options.pipelineSize
127 this.cacheWindows[i] = {'lower': b, 'upper': b + this.options.pipelineSize - 1}
128 }
129}
130
131BootstrapTable.prototype.setCurrWindow = function (offset) {
132 /* set the current cache window index, based on where the current offset falls */
133 this.currWindow = 0
134 for (let i = 0; i < this.cacheWindows.length; i++) {
135 if (this.cacheWindows[i].lower <= offset && offset <= this.cacheWindows[i].upper) {
136 this.currWindow = i
137 break
138 }
139 }
140}
141
142BootstrapTable.prototype.drawFromCache = function (offset, limit) {
143 /* draw rows from the cache using offset and limit */
144 const res = $.extend(true, {}, this.cacheRequestJSON)
145 const drawStart = offset - this.cacheWindows[this.currWindow].lower
146 const drawEnd = drawStart + limit
147 res.rows = res.rows.slice(drawStart, drawEnd)
148 return res
149}
150
151BootstrapTable.prototype.initServer = function (silent, query, url) {
152 /* determine if requested data is in cache (on paging) or if
153 * a new ajax request needs to be issued (sorting, searching, paging
154 * moving outside of cached data, page size change)
155 * initial version of this extension will entirely override base initServer
156 **/
157
158 let data = {}
159 const index = this.header.fields.indexOf(this.options.sortName)
160
161 let params = {
162 searchText: this.searchText,
163 sortName: this.options.sortName,
164 sortOrder: this.options.sortOrder
165 }
166
167 let request = null
168
169 if (this.header.sortNames[index]) {
170 params.sortName = this.header.sortNames[index]
171 }
172
173 if (this.options.pagination && this.options.sidePagination === 'server') {
174 params.pageSize = this.options.pageSize === this.options.formatAllRows()
175 ? this.options.totalRows : this.options.pageSize
176 params.pageNumber = this.options.pageNumber
177 }
178
179 if (!(url || this.options.url) && !this.options.ajax) {
180 return
181 }
182
183 let useAjax = true
184 if (this.options.queryParamsType === 'limit') {
185 params = {
186 searchText: params.searchText,
187 sortName: params.sortName,
188 sortOrder: params.sortOrder
189 }
190 if (this.options.pagination && this.options.sidePagination === 'server') {
191 params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize
192 params.offset = (this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize) * (this.options.pageNumber - 1)
193 if (this.options.usePipeline) {
194 // if cacheWindows is empty, this is the initial request
195 if (!this.cacheWindows.length) {
196 useAjax = true
197 params.drawOffset = params.offset
198 // cache exists: determine if the page request is entirely within the current cached window
199 } else {
200 const w = this.cacheWindows[this.currWindow]
201 // case 1: reset cache but stay within current window (e.g. column sort)
202 // case 2: move outside of the current window (e.g. search or paging)
203 // since each cache window is aligned with the current page size
204 // checking if params.offset is outside the current window is sufficient.
205 // need to requery for preceding or succeeding cache window
206 // also handle case
207 if (this.resetCache || (params.offset < w.lower || params.offset > w.upper)) {
208 useAjax = true
209 this.setCurrWindow(params.offset)
210 // store the relative offset for drawing the page data afterwards
211 params.drawOffset = params.offset
212 // now set params.offset to the lower bound of the new cache window
213 // the server will return that whole cache window
214 params.offset = this.cacheWindows[this.currWindow].lower
215 // within current cache window
216 } else {
217 useAjax = false
218 }
219 }
220 } else {
221 if (params.limit === 0) {
222 delete params.limit
223 }
224 }
225 }
226 }
227
228 // force an ajax call - this is on search, sort or page size change
229 if (this.resetCache) {
230 useAjax = true
231 this.resetCache = false
232 }
233
234 if (this.options.usePipeline && useAjax) {
235 /* in this scenario limit is used on the server to get the cache window
236 * and drawLimit is used to get the page data afterwards */
237 params.drawLimit = params.limit
238 params.limit = this.options.pipelineSize
239 }
240
241 // cached results can be used
242 if (!useAjax) {
243 const res = this.drawFromCache(params.offset, params.limit)
244 this.load(res)
245 this.trigger('load-success', res)
246 this.trigger('cached-data-hit', res)
247 return
248 }
249 // cached results can't be used
250 // continue base initServer code
251 if (!($.isEmptyObject(this.filterColumnsPartial))) {
252 params.filter = JSON.stringify(this.filterColumnsPartial, null)
253 }
254
255 data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
256
257 $.extend(data, query || {})
258
259 // false to stop request
260 if (data === false) {
261 return
262 }
263
264 if (!silent) {
265 this.$tableLoading.show()
266 }
267 const self = this
268
269 request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
270 type: this.options.method,
271 url: url || this.options.url,
272 data: this.options.contentType === 'application/json' && this.options.method === 'post'
273 ? JSON.stringify(data) : data,
274 cache: this.options.cache,
275 contentType: this.options.contentType,
276 dataType: this.options.dataType,
277 success (res) {
278 res = Utils.calculateObjectValue(self.options, self.options.responseHandler, [res], res)
279 // cache results if using pipelining
280 if (self.options.usePipeline) {
281 // store entire request in cache
282 self.cacheRequestJSON = $.extend(true, {}, res)
283 // this gets set in load() also but needs to be set before
284 // setting cacheWindows
285 self.options.totalRows = res[self.options.totalField]
286 // if this is a search, potentially less results will be returned
287 // so cache windows need to be rebuilt. Otherwise it
288 // will come out the same
289 self.setCacheWindows()
290 self.setCurrWindow(params.drawOffset)
291 // just load data for the page
292 res = self.drawFromCache(params.drawOffset, params.drawLimit)
293 self.trigger('cached-data-reset', res)
294 }
295 self.load(res)
296 self.trigger('load-success', res)
297 if (!silent) self.$tableLoading.hide()
298 },
299 error (res) {
300 let data = []
301 if (self.options.sidePagination === 'server') {
302 data = {}
303 data[self.options.totalField] = 0
304 data[self.options.dataField] = []
305 }
306 self.load(data)
307 self.trigger('load-error', res.status, res)
308 if (!silent) self.$tableLoading.hide()
309 }
310 })
311
312 if (this.options.ajax) {
313 Utils.calculateObjectValue(this, this.options.ajax, [request], null)
314 } else {
315 if (this._xhr && this._xhr.readyState !== 4) {
316 this._xhr.abort()
317 }
318 this._xhr = $.ajax(request)
319 }
320}