aboutsummaryrefslogtreecommitdiff
path: root/node_modules/montage/data/change-context.js
blob: c693e59e3c631b284f895b04043c3ce5c1e8eb6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* <copyright>
 This file contains proprietary software owned by Motorola Mobility, Inc.<br/>
 No rights, expressed or implied, whatsoever to this software are provided by Motorola Mobility, Inc. hereunder.<br/>
 (c) Copyright 2011 Motorola Mobility, Inc.  All Rights Reserved.
 </copyright> */
/**
 @module montage/data/context
 @requires montage/core/core
 @requires montage/data/store
 @requires montage/data/blueprint
 @requires montage/data/object-property
 @requires montage/core/shim/weak-map
 @requires montage/core/shim/structures
 @requires montage/core/exception
 @requires montage/core/promise
 @requires montage/core/logger
 */
var Montage = require("montage").Montage;
var Store = require("data/store").Store;
var Blueprint = require("data/blueprint").Blueprint;
var ObjectProperty = require("data/object-property").ObjectProperty;
// TODO [June 5 2011 PJYF] This is temporary implementation of WeakMap to let the browser catch up.
var WeakMap = require("core/shim/weak-map").WeakMap;
var Set = require("core/shim/structures").Set;
var Exception = require("core/exception").Exception;
var Promise = require("core/promise").Promise;
var logger = require("core/logger").logger("change-context");
/**
 @class module:montage/data/change-context.ChangeContext
 @extends module:montage/data/store.Store
 */
var ChangeContext = exports.ChangeContext = Montage.create(Store, /** @lends module:montage/data/change-context.ChangeContext# */ {
    /**
     Collection of object inserted in this context since the last save.
     @private
     */
    _inserted: {
        value: new Set(50),
        serializable: true,
        distinct: true,
        enumerable: false,
        writable: false
    },
    /**
     Collection of object deleted in this context since the last save.
     @private
     */
    _deleted: {
        value: new Set(50),
        serializable: true,
        distinct: true,
        enumerable: false,
        writable: false
    },
    /**
     Collection of object modified in this context since the last save.
     @private
     */
    _modified: {
        value: new Set(50),
        serializable: true,
        distinct: true,
        enumerable: false,
        writable: false
    },

    /**
     Table of fetched objects for uniquing. The key is the object ID the value the actual object or the pledge representing it.<br/>
     <b>Note:<b/> This is a weak map so that the context does not hold on the objects and they can be garbage collected if no one else hold on them.
     @private
     */
    _objectMap: {
        value: new WeakMap(),
        serializable: true,
        enumerable: false,
        writable: false
    },

    /**
     Collection of object inserted in this context since the last save.
     @function
     @returns this._inserted
     @default empty set
     */
    inserted: {
        get: function() {
            return this._inserted;
        }
    },

    /**
     Collection of object deleted in this context since the last save.
     @function
     @returns this._deleted
     @default empty set
     */
    deleted: {
        get: function() {
            return this._deleted;
        }
    },

    /**
     Collection of object modified in this context since the last save.
     @function
     @returns this._modified
     @default empty set
     */
    modified: {
        get: function() {
            return this._modified;
        }
    },

    /**
     Description TODO
     @function
     @param {String} id objectmap
     @returns this._objectMap.get(id) | null
     */
    objectForId: {
        value: function(id) {
            if (this._objectMap.has(id)) {
                return this._objectMap.get(id);
            }
            return null;
        }
    },

    /**
     Inserts a newly created object in the context.
     @function
     @param {Object} instance TODO
     @returns initialized object
     */
    insert: {
        value: function(instance) {
            if (instance !== null) {
                if (typeof instance.context === "undefined") {
                    var metadata = Montage.getInfoForObject(instance);
                    var blueprint = this.blueprintForPrototype(metadata.objectName, metadata.moduleId);
                    if (blueprint !== null) {
                        ObjectProperty.manager.apply(Object.getPrototypeOf(instance), blueprint);
                    } else {
                        throw Exception.create().initWithMessageTargetAndMethod("Cannot find blueprint for: " + metadata.objectName + " " + metadata.moduleId, this, "insert");
                    }
                }
                if (instance.context === null) {
                    instance.context = this;
                    this._inserted.add(instance);
                    return this.initializeObject(instance, this).then(function(instance) {
                        instance.context._objectMap.set(instance.objectId, instance);
                        return Promise.ref(instance);
                    });
                } else if (instance.context !== this) {
                    throw Exception.initWithMessageTargetAndMethod("This instance is already inserted in another context.", this, "insert");
                }
            } else {
                throw Exception.initWithMessageTargetAndMethod("Cannot insert a null object.", this, "insert");
            }
        }
    },

    /**
     Delete an object.<br>
     A deleted object will be deleted from the backing store on the next save.
     @function
     @param {Object} instance TODO
     @returns Promise.ref(instance)
     */
    'delete': {
        value: function(instance) {
            if (instance !== null) {
                if ((typeof instance.context === "undefined") || (instance.context === null)) {
                    return Promise.ref(instance);
                }
                if (instance.context !== this) {
                    throw Exception.initWithMessageTargetAndMethod("This instance is belongs to another context.", this, "delete");
                }
                if (this._inserted.has(instance)) {
                    // We are forgetting a newly inserted object
                    this._inserted.delete(instance);
                    if (typeof instance.context !== "undefined") {
                        instance.context = null;
                    }
                } else {
                    if (this._modified.has(instance)) {
                        // the object was modified before teh delete forget those.
                        this._modified.delete(instance);
                        instance = this._revertValues(instance);
                    }
                    this._deleted.add(instance);
                }
                this._objectMap.delete(instance.objectId);
            } else {
                throw Exception.initWithMessageTargetAndMethod("Cannot delete a null object.", this, "delete");
            }
            return Promise.ref(instance);
        }
    },

    /**
     Revert an object to its saved values.
     @function
     @param {Object} instance TODO
     @returns Promise.ref(instance)
     */
    revert: {
        value: function(instance) {
            if (instance !== null) {
                if (typeof instance.context === "undefined") {
                    return Promise.ref(instance);
                }
                if (instance.context !== null) {
                    if (instance.context !== this) {
                        throw Exception.initWithMessageTargetAndMethod("This instance is belongs to another context.", this, "revert");
                    }
                    if (this._inserted.has(instance)) {
                        // This is a newly inserted object, there is no value to revert to, so do nothing.
                    } else if (this._modified.has(instance)) {
                        this._modified.delete(instance);
                        instance = this._revertValues(instance);
                    }
                } else {
                    // Maybe that object was deleted let retrieve it?
                    if (this._deleted.has(instance)) {
                        this._deleted.delete(instance);
                        instance.context = this;
                        instance = this._revertValues(instance);
                    }
                }
            } else {
                throw Exception.initWithMessageTargetAndMethod("Cannot revert a null object.", this, "revert");
            }
            return  Promise.ref(instance);
        }
    },

    /**
     Description TODO
     @private
     */
    _revertValues: {
        value: function(instance) {
            // TODO [PJYF May 24 2011] We should restore the saved values
            return  Promise.ref(instance);
        }
    },

    /**
     Saves all current changes and deletion to the backing store.
     @function
     */
    save: {
        value: function() {
            // TODO [PJYF Sept 4 2011] This is probably incomplete - we need to handle the callback
            if (this.hasChanges()) {
                this.parent.saveChangesInContext(this);
            }
        }
    },

    /**
     This method from the parent store is overwritten to handle the save from the child context.
     @function
     @param {Property} context The child context
     @param {String} transactionID The transaction id
     */
    saveChangesInContext$Implementation: {
        value: function(context, transactionID) {
            if (context === this) {
                // If called on it-self then save the context
                Store.saveChangesInContext$Implementation.call(this, context, transactionID);
            }
            // The context has all the changes and we need to merge them with our own.
            var inserted = context.inserted;
            var deleted = context.deleted;
            var modified = context.modified;

            var newUpdated = null;
            var removedInserted = null;

            // First create and insert all new objects
            inserted.forEach(function(object) {
                var gid = object.objectId;
                var localObject = this.objectForId(gid);

                if (localObject == null) {
                    // Insert a copy in our context.
                    ;
                } else {
                    // Inserting an object already registered in my context? Pretty bogus! Treat it as an update.
                    ;
                    // Remove from the inserted list and add it to the updated one.
                    ;
                }

            });

            // Initialize the property values in these new objects.

            // Copy the values for all updated objects.

            // Delete removed Objects.

            // TODO [PJYF Sept 4 2011] This needs to be reimplemented

        }
    },

    /**
     Description TODO
     @function
     @param {String} attribute TODO
     @param {Object} instance TODO
     */
    fulfillPropertyForInstance: {
        value: function(attribute, instance) {

        }
    },

    /**
     Description TODO
     @function
     @param {String} attribute TODO
     @param {Object} instance TODO
     */
    willModifyPropertyForInstance:  {
        value: function(attribute, instance, value) {
            // TODO [PJYF Sep 30 2011] We should probably be smarter.
            this._modified.add(instance);
        }
    },

    /**
     Fetch objects from the backing store.
     @function
     @param {String} query TODO
     @returns Promise.ref(this.parent.queryInContext(query, this))
     */
    query: {
        value: function(query) {
            // TODO [PJYF Sept 23 2011] This is probably incomplete - we need to handle the refresh
            return Promise.ref(this.parent.queryInContext(query, this));
        }
    },

    /**
     Reload all objects from the backing store and merges changes in the context with the new values.<br>
     If the target passed is an Array each object will be refreshed.
     @function
     @param {Object} target The target to be refreshed.
     @returns Promise.ref(this.repledgeObject(target, this))
     */
    refresh: {
        value: function(target) {
            // TODO [PJYF May 10 2011] This is incorrect we need to merge the changes in the refaulted objects
            return Promise.ref(this.repledgeObject(target, this));
        }
    },

    /**
     Check if there are unsaved changes in the context.
     @function
     @returns this._inserted.length > 0 or this._modified.length > 0 or this._deleted.length > 0
     */
    hasChanges: {
        value: function() {
            return this._inserted.length > 0 || this._modified.length > 0 || this._deleted.length > 0;
        }
    }

});