Mercurial > pub > ImplabJs
comparison 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 |
comparison
equal
deleted
inserted
replaced
26:fb23f3c854df | 27:aee8ea860e9b |
---|---|
1 define([ | |
2 "dojo/_base/declare", | |
3 "dojo/_base/lang", | |
4 "dojo/request", | |
5 "dojo/store/Memory", | |
6 "dojo/Deferred", | |
7 "dojo/store/util/QueryResults" | |
8 | |
9 ], function (declare, lang, request, Memory, Deferred, QueryResults) { | |
10 /** | |
11 * @amdplugin | |
12 * @usage | |
13 * | |
14 * <pre> | |
15 * require([ | |
16 * "tests/store/mock!./data/sample.json" | |
17 * ], function(Store) { | |
18 * var store = new Store(); // will create a memory store | |
19 * }); | |
20 * </pre> | |
21 */ | |
22 var cache = {}; | |
23 return { | |
24 load: function (id, require, callback) { | |
25 var url = require.toUrl(id); | |
26 if (url in cache) { | |
27 callback(cache[url]); | |
28 } else { | |
29 request(url).then(function (data) { | |
30 // handle result as text and parse it every time the | |
31 // store | |
32 // is created to get an independent copy | |
33 var f = cache[url] = function (opts) { | |
34 var store = new Memory(lang.mixin({ | |
35 data: JSON.parse(data), | |
36 async: true, | |
37 delay: 100 | |
38 }, opts || {})); | |
39 | |
40 declare.safeMixin(store, { | |
41 query: function () { | |
42 var results = this.inherited(arguments); | |
43 if (this.async) { | |
44 var d = new Deferred(); | |
45 setTimeout(function () { | |
46 d.resolve(results); | |
47 }, this.delay); | |
48 return new QueryResults(d.promise); | |
49 } | |
50 return results; | |
51 }, | |
52 | |
53 get: function () { | |
54 var results = this.inherited(arguments); | |
55 if (this.async) { | |
56 var d = new Deferred(); | |
57 setTimeout(function () { | |
58 d.resolve(results); | |
59 }, this.delay); | |
60 return d.promise; | |
61 } | |
62 return results; | |
63 }, | |
64 | |
65 put: function () { | |
66 var me = this; | |
67 | |
68 if (me.async) { | |
69 var inherited = me.getInherited(arguments); | |
70 var args = Array.prototype.slice.apply(arguments); | |
71 var d = new Deferred(); | |
72 | |
73 setTimeout(function () { | |
74 d.resolve(inherited.apply(me, args)); | |
75 }, me.delay); | |
76 | |
77 return d.promise; | |
78 } | |
79 return me.inherited(arguments); | |
80 } | |
81 }); | |
82 | |
83 return store; | |
84 }; | |
85 callback(f); | |
86 }, function (err) { | |
87 require.signal("error", [{ | |
88 error: err, | |
89 src: 'implab/store/mock' | |
90 }]); | |
91 }); | |
92 } | |
93 } | |
94 }; | |
95 }); |