Mercurial > pub > ImplabJs
diff src/utest/store/mock.js @ 27:aee8ea860e9b
added utest/store/mock - json based mock store
author | cin |
---|---|
date | Mon, 11 Dec 2017 16:48:19 +0300 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/utest/store/mock.js Mon Dec 11 16:48:19 2017 +0300 @@ -0,0 +1,95 @@ +define([ + "dojo/_base/declare", + "dojo/_base/lang", + "dojo/request", + "dojo/store/Memory", + "dojo/Deferred", + "dojo/store/util/QueryResults" + +], function (declare, lang, request, Memory, Deferred, QueryResults) { + /** + * @amdplugin + * @usage + * + * <pre> + * require([ + * "tests/store/mock!./data/sample.json" + * ], function(Store) { + * var store = new Store(); // will create a memory store + * }); + * </pre> + */ + var cache = {}; + return { + load: function (id, require, callback) { + var url = require.toUrl(id); + if (url in cache) { + callback(cache[url]); + } else { + request(url).then(function (data) { + // handle result as text and parse it every time the + // store + // is created to get an independent copy + var f = cache[url] = function (opts) { + var store = new Memory(lang.mixin({ + data: JSON.parse(data), + async: true, + delay: 100 + }, opts || {})); + + declare.safeMixin(store, { + query: function () { + var results = this.inherited(arguments); + if (this.async) { + var d = new Deferred(); + setTimeout(function () { + d.resolve(results); + }, this.delay); + return new QueryResults(d.promise); + } + return results; + }, + + get: function () { + var results = this.inherited(arguments); + if (this.async) { + var d = new Deferred(); + setTimeout(function () { + d.resolve(results); + }, this.delay); + return d.promise; + } + return results; + }, + + put: function () { + var me = this; + + if (me.async) { + var inherited = me.getInherited(arguments); + var args = Array.prototype.slice.apply(arguments); + var d = new Deferred(); + + setTimeout(function () { + d.resolve(inherited.apply(me, args)); + }, me.delay); + + return d.promise; + } + return me.inherited(arguments); + } + }); + + return store; + }; + callback(f); + }, function (err) { + require.signal("error", [{ + error: err, + src: 'implab/store/mock' + }]); + }); + } + } + }; +}); \ No newline at end of file