devextreme
Version:
JavaScript/TypeScript Component Suite for Responsive Web Development
572 lines (570 loc) • 21 kB
JavaScript
/**
* DevExtreme (cjs/__internal/data/data_source/data_source.js)
* Version: 26.1.6
* Build date: Fri Oct 16 2026
*
* Copyright (c) 2012 - 2026 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DataSource = void 0;
var _array_utils = require("../../../common/data/array_utils");
var _operation_manager = _interopRequireDefault(require("../../../common/data/data_source/operation_manager"));
var _utils = require("../../../common/data/data_source/utils");
var _errors = require("../../../common/data/errors");
var _utils2 = require("../../../common/data/utils");
var _events_strategy = require("../../../core/events_strategy");
var _deferred = require("../../../core/utils/deferred");
var _extend = require("../../../core/utils/extend");
var _queue = require("../../../core/utils/queue");
var _type = require("../../../core/utils/type");
var _m_common = _interopRequireDefault(require("../../core/utils/m_common"));
var _custom_store = _interopRequireDefault(require("../../data/custom_store"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : {
default: e
}
}
const isFiniteValue = value => isFinite(Number(value));
const EVENT_OPTIONS = [{
option: "onChanged",
event: "changed"
}, {
option: "onLoadError",
event: "loadError"
}, {
option: "onLoadingChanged",
event: "loadingChanged"
}, {
option: "onCustomizeLoadResult",
event: "customizeLoadResult"
}, {
option: "onCustomizeStoreLoadOptions",
event: "customizeStoreLoadOptions"
}];
class DataSource {
constructor(options) {
this._disposed = false;
this._items = [];
this._userData = {};
this._totalCount = -1;
this._isLoaded = false;
this._isLastPage = false;
const dataSourceOptions = (0, _utils.normalizeDataSourceOptions)(options, void 0);
this._eventsStrategy = new _events_strategy.EventsStrategy(this, {
syncStrategy: true
});
this._store = dataSourceOptions.store;
this._changedTime = 0;
const needThrottling = 0 !== dataSourceOptions.pushAggregationTimeout;
if (needThrottling) {
const throttlingTimeout = void 0 === dataSourceOptions.pushAggregationTimeout ? () => 5 * this._changedTime : dataSourceOptions.pushAggregationTimeout;
const pushState = {};
const throttlingPushHandler = (0, _utils2.throttleChanges)(changes => {
var _pushState$deferred;
null === (_pushState$deferred = pushState.deferred) || void 0 === _pushState$deferred || _pushState$deferred.resolve();
const storePushPending = (0, _deferred.when)(...pushState.lastWaiters ?? []);
storePushPending.done(() => this._onPush(changes));
pushState.lastWaiters = void 0;
pushState.deferred = void 0
}, throttlingTimeout);
this._onPushHandler = args => {
this._aggregationTimeoutId = throttlingPushHandler(args.changes);
pushState.deferred ?? (pushState.deferred = (0, _deferred.Deferred)());
pushState.lastWaiters = args.waitFor;
args.waitFor.push(pushState.deferred.promise())
};
this._store.on("beforePushAggregation", this._onPushHandler)
} else {
this._onPushHandler = changes => this._onPush(changes);
this._store.on("push", this._onPushHandler)
}
this._storeLoadOptions = this._extractLoadOptions(dataSourceOptions);
this._mapFunc = dataSourceOptions.map;
this._postProcessFunc = dataSourceOptions.postProcess;
this._pageIndex = void 0 !== dataSourceOptions.pageIndex ? dataSourceOptions.pageIndex : 0;
this._pageSize = void 0 !== dataSourceOptions.pageSize ? dataSourceOptions.pageSize : 20;
this._loadingCount = 0;
this._loadQueue = this._createLoadQueue();
this._searchValue = "searchValue" in dataSourceOptions ? dataSourceOptions.searchValue : null;
this._searchOperation = dataSourceOptions.searchOperation || "contains";
this._searchExpr = dataSourceOptions.searchExpr;
this._paginate = dataSourceOptions.paginate;
this._reshapeOnPush = dataSourceOptions.reshapeOnPush ?? false;
EVENT_OPTIONS.forEach(_ref => {
let {
option: option,
event: event
} = _ref;
const handler = dataSourceOptions[option];
if (handler) {
this.on(event, handler)
}
});
this._operationManager = new _operation_manager.default;
this._init()
}
_init() {
this._items = [];
this._userData = {};
this._totalCount = -1;
this._isLoaded = false;
if (!(0, _type.isDefined)(this._paginate)) {
this._paginate = !this.group()
}
this._isLastPage = !this._paginate
}
dispose() {
var _this$_delayedLoadTas;
this._store.off("beforePushAggregation", this._onPushHandler);
this._store.off("push", this._onPushHandler);
this._eventsStrategy.dispose();
clearTimeout(this._aggregationTimeoutId);
null === (_this$_delayedLoadTas = this._delayedLoadTask) || void 0 === _this$_delayedLoadTas || _this$_delayedLoadTas.abort();
this._operationManager.cancelAll();
Reflect.deleteProperty(this, "_store");
Reflect.deleteProperty(this, "_items");
Reflect.deleteProperty(this, "_delayedLoadTask");
this._disposed = true
}
_extractLoadOptions(options) {
const result = {};
let names = ["sort", "filter", "langParams", "select", "group", "requireTotalCount"];
const customNames = this._store._customLoadOptions();
if (customNames) {
names = names.concat(customNames)
}
names.forEach(name => {
result[name] = options[name]
});
return result
}
loadOptions() {
return this._storeLoadOptions
}
items() {
return this._items
}
pageIndex(newIndex) {
if (!(0, _type.isDefined)(newIndex) || !(0, _type.isNumeric)(newIndex)) {
return this._pageIndex
}
this._pageIndex = newIndex;
this._isLastPage = !this._paginate;
return
}
paginate(value) {
if (!(0, _type.isBoolean)(value)) {
return this._paginate
}
if (this._paginate !== value) {
this._paginate = value;
this.pageIndex(0)
}
return
}
pageSize(value) {
if (!(0, _type.isDefined)(value) || !(0, _type.isNumeric)(value)) {
return this._pageSize
}
this._pageSize = value;
return
}
isLastPage() {
return this._isLastPage
}
generateStoreLoadOptionAccessor(optionName) {
return args => {
const normalizedArgs = (0, _utils.normalizeStoreLoadOptionAccessorArguments)(args);
if (void 0 === normalizedArgs) {
return this._storeLoadOptions[optionName]
}
this._storeLoadOptions[optionName] = normalizedArgs;
return
}
}
sort() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key]
}
return this.generateStoreLoadOptionAccessor("sort")(args)
}
filter() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2]
}
const newFilter = (0, _utils.normalizeStoreLoadOptionAccessorArguments)(args);
if (void 0 === newFilter) {
return this._storeLoadOptions.filter
}
this._storeLoadOptions.filter = newFilter;
this.pageIndex(0);
return
}
group() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3]
}
return this.generateStoreLoadOptionAccessor("group")(args)
}
select() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4]
}
return this.generateStoreLoadOptionAccessor("select")(args)
}
requireTotalCount(value) {
if (!(0, _type.isBoolean)(value)) {
return this._storeLoadOptions.requireTotalCount
}
this._storeLoadOptions.requireTotalCount = value;
return
}
searchValue() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5]
}
if (args.length < 1) {
return this._searchValue
}
const [value] = args;
this._searchValue = value;
this.pageIndex(0);
return
}
searchOperation(op) {
if (!(0, _type.isDefined)(op) || !(0, _type.isString)(op)) {
return this._searchOperation
}
this._searchOperation = op;
this.pageIndex(0);
return
}
searchExpr() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6]
}
if (0 === args.length) {
return this._searchExpr
}
this._searchExpr = args.length > 1 ? args : args[0];
this.pageIndex(0);
return
}
store() {
return this._store
}
key() {
var _this$_store;
return null === (_this$_store = this._store) || void 0 === _this$_store ? void 0 : _this$_store.key()
}
totalCount() {
return this._totalCount
}
isLoaded() {
return this._isLoaded
}
isLoading() {
return this._loadingCount > 0
}
beginLoading() {
this._changeLoadingCount(1)
}
endLoading() {
this._changeLoadingCount(-1)
}
_createLoadQueue() {
return (0, _queue.create)()
}
_changeLoadingCount(increment) {
const oldLoading = this.isLoading();
this._loadingCount += increment;
const newLoading = this.isLoading();
if (oldLoading !== newLoading) {
this._eventsStrategy.fireEvent("loadingChanged", [newLoading])
}
}
_scheduleLoadCallbacks(deferred) {
this.beginLoading();
deferred.always(() => {
this.endLoading()
})
}
_scheduleFailCallbacks(deferred) {
var _this = this;
deferred.fail(function() {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7]
}
if (args[0] === _utils.CANCELED_TOKEN) {
return
}
_this._eventsStrategy.fireEvent("loadError", args)
})
}
_fireChanged(e) {
const date = Date.now();
this._eventsStrategy.fireEvent("changed", [e]);
this._changedTime = Date.now() - date
}
_scheduleChangedCallbacks(deferred) {
deferred.done(() => this._fireChanged())
}
loadSingle() {
const d = (0, _deferred.Deferred)();
const key = this.key();
const store = this._store;
const options = this._createStoreLoadOptions();
this._scheduleFailCallbacks(d);
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8]
}
const [propName, propValue] = args.length < 2 ? [key, args[0]] : args;
delete options.skip;
delete options.group;
delete options.refresh;
delete options.pageIndex;
delete options.searchString;
const useByKey = propName === key || store instanceof _custom_store.default && !store._byKeyViaLoad();
if (!useByKey) {
options.take = 1;
options.filter = options.filter ? [options.filter, [propName, propValue]] : [propName, propValue]
}
const request = useByKey ? store.byKey(propValue, options) : store.load(options);
request.fail(function() {
d.reject(...arguments)
}).done(data => {
const isEmptyArray = Array.isArray(data) && !data.length;
if (!(0, _type.isDefined)(data) || isEmptyArray) {
d.reject(_errors.errors.Error("E4009"))
} else {
const items = Array.isArray(data) ? data : [data];
d.resolve(this._applyMapFunction(items)[0])
}
});
return d.promise()
}
load() {
const d = (0, _deferred.Deferred)();
this._scheduleLoadCallbacks(d);
this._scheduleFailCallbacks(d);
this._scheduleChangedCallbacks(d);
const loadOperation = this._createLoadOperation(d);
const loadTask = () => {
if (this._disposed) {
return
}
if (!(0, _utils.isPending)(d)) {
return
}
return this._loadFromStore(loadOperation, d)
};
this._eventsStrategy.fireEvent("customizeStoreLoadOptions", [loadOperation]);
this._loadQueue.add(() => {
if ("number" === typeof loadOperation.delay) {
this._delayedLoadTask = _m_common.default.executeAsync(loadTask, loadOperation.delay)
} else {
loadTask()
}
return d.promise()
}, void 0);
return d.promise({
operationId: loadOperation.operationId
})
}
_onPush(changes) {
if (this._reshapeOnPush) {
this.load()
} else {
const changingArgs = {
changes: changes
};
this._eventsStrategy.fireEvent("changing", [changingArgs]);
const group = this.group();
const items = this.items();
let groupLevel = 0;
let dataSourceChanges = this.paginate() || group ? changes.filter(item => "update" === item.type) : changes;
if (group) {
groupLevel = Array.isArray(group) ? group.length : 1
}
if (this._mapFunc) {
dataSourceChanges.forEach(item => {
if ("insert" === item.type) {
var _this$_mapFunc;
item.data = null === (_this$_mapFunc = this._mapFunc) || void 0 === _this$_mapFunc ? void 0 : _this$_mapFunc.call(this, item.data)
}
})
}
if (changingArgs.postProcessChanges) {
dataSourceChanges = changingArgs.postProcessChanges(dataSourceChanges)
}(0, _array_utils.applyBatch)({
keyInfo: this.store(),
data: items,
changes: dataSourceChanges,
groupCount: groupLevel,
useInsertIndex: true
});
this._fireChanged({
changes: changes
})
}
}
_createLoadOperation(deferred) {
const operationId = this._operationManager.add(deferred);
const storeLoadOptions = this._createStoreLoadOptions();
if (this._store && !(0, _type.isEmptyObject)(storeLoadOptions.langParams)) {
this._store._langParams = Object.assign({}, this._store._langParams, storeLoadOptions.langParams)
}
deferred.always(() => this._operationManager.remove(operationId));
return {
operationId: operationId,
storeLoadOptions: storeLoadOptions
}
}
reload() {
const store = this.store();
store._clearCache();
this._init();
return this.load()
}
cancel(operationId) {
const result = this._operationManager.cancel(operationId);
return result
}
cancelAll() {
this._operationManager.cancelAll()
}
_addSearchOptions(storeLoadOptions) {
if (this._disposed) {
return
}
if (this.store()._useDefaultSearch) {
this._addSearchFilter(storeLoadOptions)
} else {
storeLoadOptions.searchOperation = this._searchOperation;
storeLoadOptions.searchValue = this._searchValue;
storeLoadOptions.searchExpr = this._searchExpr
}
}
_createStoreLoadOptions() {
const result = (0, _extend.extend)({}, this._storeLoadOptions);
this._addSearchOptions(result);
if (this._paginate) {
if (this._pageSize) {
result.skip = this._pageIndex * this._pageSize;
result.take = this._pageSize
}
}
result.userData = this._userData;
return result
}
_addSearchFilter(storeLoadOptions) {
const value = this._searchValue;
const op = this._searchOperation;
const searchFilter = [];
if (!value) {
return
}
const selector = this._searchExpr || "this";
const selectors = Array.isArray(selector) ? selector : [selector];
selectors.forEach(item => {
if (searchFilter.length) {
searchFilter.push("or")
}
searchFilter.push([item, op, value])
});
if (storeLoadOptions.filter) {
storeLoadOptions.filter = [searchFilter, storeLoadOptions.filter]
} else {
storeLoadOptions.filter = searchFilter
}
}
_loadFromStore(loadOptions, pendingDeferred) {
const handleSuccess = (data, extra) => {
if (this._disposed) {
return
}
if (!(0, _utils.isPending)(pendingDeferred)) {
return
}
const loadResult = (0, _extend.extend)((0, _utils.normalizeLoadResult)(data, extra), loadOptions);
this._eventsStrategy.fireEvent("customizeLoadResult", [loadResult]);
(0, _deferred.when)(loadResult.data).done(resolvedData => {
loadResult.data = resolvedData;
this._processStoreLoadResult(loadResult, pendingDeferred)
}).fail(function() {
pendingDeferred.reject(...arguments)
})
};
if (loadOptions.data) {
return (0, _deferred.Deferred)().resolve(loadOptions.data).done(handleSuccess)
}
return this.store().load(loadOptions.storeLoadOptions).done(handleSuccess).fail(function() {
pendingDeferred.reject(...arguments)
})
}
_processStoreLoadResult(loadResult, pendingDeferred) {
const {
storeLoadOptions: storeLoadOptions
} = loadResult;
let {
data: data,
extra: extra
} = loadResult;
const resolvePendingDeferred = () => {
this._isLoaded = true;
this._totalCount = isFiniteValue(extra.totalCount) ? extra.totalCount : -1;
return pendingDeferred.resolve(data, extra)
};
const proceedLoadingTotalCount = () => {
this.store().totalCount(storeLoadOptions).done(count => {
extra.totalCount = count;
resolvePendingDeferred()
}).fail(function() {
pendingDeferred.reject(...arguments)
})
};
if (this._disposed) {
return
}
data = this._applyPostProcessFunction(this._applyMapFunction(data));
if (!(0, _type.isObject)(extra)) {
extra = {}
}
this._items = data;
if (!data.length || !this._paginate || this._pageSize && data.length < this._pageSize) {
this._isLastPage = true
}
if (storeLoadOptions.requireTotalCount && !isFiniteValue(extra.totalCount)) {
proceedLoadingTotalCount()
} else {
resolvePendingDeferred()
}
}
_applyMapFunction(data) {
if (this._mapFunc) {
const mapped = (0, _utils.mapDataRespectingGrouping)(data, this._mapFunc, this.group());
return mapped
}
return data
}
_applyPostProcessFunction(data) {
if (this._postProcessFunc) {
const processed = this._postProcessFunc(data);
return processed
}
return data
}
on(eventName, eventHandler) {
this._eventsStrategy.on(eventName, eventHandler);
return this
}
off(eventName, eventHandler) {
this._eventsStrategy.off(eventName, eventHandler);
return this
}
}
exports.DataSource = DataSource;