Merge pull request #340 from realm/sk-collection

Make List and Results inherit from Collection
This commit is contained in:
Scott Kyle 2016-03-21 15:27:18 -07:00
commit 0e74362e4c
23 changed files with 567 additions and 250 deletions

View File

@ -5,6 +5,7 @@
### Enhancements
* Support for encryption
* List and Results now inherit from Realm.Collection
* Add common Array methods to List and Results
* Accept constructor in create() and objects() methods
* Support relative paths when opening realms

View File

@ -76,6 +76,8 @@
F6BCCFE21C8380A400FE31AE /* lib in Resources */ = {isa = PBXBuildFile; fileRef = F6BCCFDF1C83809A00FE31AE /* lib */; };
F6C74DF01C732CC500C9DDCD /* RealmAnalytics.h in Headers */ = {isa = PBXBuildFile; fileRef = F6C74DEE1C732CC500C9DDCD /* RealmAnalytics.h */; };
F6C74DF11C732CC500C9DDCD /* RealmAnalytics.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6C74DEF1C732CC500C9DDCD /* RealmAnalytics.mm */; };
F6CB31001C8EDDAB0070EF3F /* js_collection.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F6CB30FC1C8EDD760070EF3F /* js_collection.cpp */; };
F6CB31011C8EDDBB0070EF3F /* js_collection.hpp in Headers */ = {isa = PBXBuildFile; fileRef = F6CB30FD1C8EDD760070EF3F /* js_collection.hpp */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@ -247,6 +249,8 @@
F6C3FBBC1BF680EC00E6FFD4 /* json.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = json.hpp; sourceTree = "<group>"; };
F6C74DEE1C732CC500C9DDCD /* RealmAnalytics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RealmAnalytics.h; path = "react-native/RealmAnalytics.h"; sourceTree = "<group>"; };
F6C74DEF1C732CC500C9DDCD /* RealmAnalytics.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = RealmAnalytics.mm; path = "react-native/RealmAnalytics.mm"; sourceTree = "<group>"; };
F6CB30FC1C8EDD760070EF3F /* js_collection.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = js_collection.cpp; sourceTree = "<group>"; };
F6CB30FD1C8EDD760070EF3F /* js_collection.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = js_collection.hpp; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -309,6 +313,8 @@
F62A35141C18E783004A917D /* Object Store */,
029048011C0428DF00ABDED4 /* js_init.cpp */,
029048021C0428DF00ABDED4 /* js_init.h */,
F6CB30FC1C8EDD760070EF3F /* js_collection.cpp */,
F6CB30FD1C8EDD760070EF3F /* js_collection.hpp */,
029048031C0428DF00ABDED4 /* js_list.cpp */,
029048041C0428DF00ABDED4 /* js_list.hpp */,
029048051C0428DF00ABDED4 /* js_object.cpp */,
@ -535,6 +541,7 @@
029048181C0428DF00ABDED4 /* js_realm.hpp in Headers */,
029048141C0428DF00ABDED4 /* js_list.hpp in Headers */,
F6BB7DF21BF681BC00D0A69E /* base64.hpp in Headers */,
F6CB31011C8EDDBB0070EF3F /* js_collection.hpp in Headers */,
0290481C1C0428DF00ABDED4 /* js_schema.hpp in Headers */,
029048161C0428DF00ABDED4 /* js_object.hpp in Headers */,
029048371C042A3C00ABDED4 /* platform.hpp in Headers */,
@ -787,6 +794,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
F6CB31001C8EDDAB0070EF3F /* js_collection.cpp in Sources */,
02F59EE31C88F2BB007F774C /* transact_log_handler.cpp in Sources */,
F63FF2E81C159C4B00B3B8E0 /* platform.mm in Sources */,
02F59EC31C88F17D007F774C /* results.cpp in Sources */,

View File

@ -6,6 +6,7 @@
}
},
"rules": {
"no-undef": 0,
"no-unused-vars": 0
}
}

279
docs/collection.js Normal file
View File

@ -0,0 +1,279 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
/**
* Abstract base class containing methods shared by {@link Realm.List} and {@link Realm.Results}.
* @memberof Realm
* @since 0.11.0
*/
class Collection {
/**
* The number of objects in the collection.
* @type {number}
* @readonly
*/
get length() {}
/**
* Returns new _Results_ that represent this collection being filtered by the provided query.
* @param {string} query - Query used to filter objects from the collection.
* @param {...any} [arg] - Each subsequent argument is used by the placeholders
* (e.g. `$0`, `$1`, `$2`, ) in the query.
* @throws {Error} If the query or any other argument passed into this method is invalid.
* @returns {Realm.Results} filtered according to the provided query.
* @example
* let merlots = wines.filtered('variety == "Merlot" && vintage <= $0', maxYear);
*/
filtered(query, ...arg) {}
/**
* Returns new _Results_ that represent this collection being sorted by the provided property
* (or properties) of each object.
* @param {string|Realm.Results~SortDescriptor[]} descriptor - The property name(s) to sort
* the objects in the collection.
* @param {boolean} [reverse=false] - May only be provided if `descriptor` is a string.
* @throws {Error} If a specified property does not exist.
* @returns {Realm.Results} sorted according to the arguments passed in
*/
sorted(descriptor, reverse) {}
/**
* Create a frozen snapshot of the collection. This means objects added to and removed from the
* original collection will not be reflected in the _Results_ returned by this method.
* However, objects deleted from the Realm will become `null` at their respective indices.
* This is **not** a _deep_ snapshot, meaning the objects contained in this snapshot will
* continue to update as changes are made to them.
* @returns {Realm.Results} which will **not** live update.
*/
snapshot() {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries Array.prototype.entries}
* @returns {Realm.Collection~Iterator} of each `[index, object]` pair in the collection
* @since 0.11.0
*/
entries() {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys}
* @returns {Realm.Collection~Iterator} of each index in the collection
* @since 0.11.0
*/
keys() {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values Array.prototype.values}
* @returns {Realm.Collection~Iterator} of each Realm object in the collection
* @since 0.11.0
*/
values() {}
/**
* This is the same method as the {@link Realm.Collection#values values()} method.
* Its presence makes collections _iterable_, thus able to be used with ES6
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of `for-of`}
* loops,
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator `...`}
* spread operators, and more.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator Symbol.iterator}
* and the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable iterable protocol}
* @returns {Realm.Collection~Iterator} of each Realm object in the collection
* @since 0.11.0
* @example
* for (let object of collection) {
* // do something with each object
* }
*/
[Symbol.iterator]() {}
/**
* Joins all objects in the collection into a string.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join Array.prototype.join}
* @param {string} [separator=","] - A string to separate the return values of the
* `toString()` method being called on each object in the collection.
* @returns {string}
* @since 0.11.0
*/
join(separator) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice Array.prototype.slice}
* @param {number} [start=0] - The start index. If negative, then the start index will be
* counted from the end of the collection.
* @param {number} [end] - The end index. The objects up to, but not including, the end
* index will be include in the return value. If negative, then the end index will be
* counted from the end of the collection. If omitted, then all objects from the start
* index will be included in the return value.
* @returns {Realm.Object[]} containing the objects from the start index up to, but not
* including, the end index.
* @since 0.11.0
*/
slice(start, end) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find Array.prototype.find}
* @param {function} callback - Function to execute on each object in the collection.
* If this function returns `true`, then that object will be returned by this method.
* This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @returns {Realm.Object|undefined} if the `callback` did not return `true` for any object
* in the collection.
* @since 0.11.0
*/
find(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex Array.prototype.findIndex}
* @param {function} callback - Function to execute on each object in the collection.
* If this function returns `true`, then the index of that object will be returned
* by this method. This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @returns {number} representing the index where the `callback` returned `true`, or `-1`
* if `true` was never returned.
* @since 0.11.0
*/
findIndex(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach Array.prototype.forEach}
* @param {function} callback - Function to execute on each object in the collection.
* This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @since 0.11.0
*/
forEach(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every Array.prototype.every}
* @param {function} callback - Function to execute on each object in the collection.
* If this function returns `true` for every object, then this method will return `true`.
* This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @returns {boolean} representing if `callback` returned `true` for every object in the
* collection.
* @since 0.11.0
*/
every(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some Array.prototype.some}
* @param {function} callback - Function to execute on each object in the collection.
* If this function ever returns `true`, then this method will return `true`.
* This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @returns {boolean} `true` when `callback` returns `true` for an object in the collection,
* otherwise `false`.
* @since 0.11.0
*/
some(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.prototype.map}
* @param {function} callback - Function to execute on each object in the collection.
* This function takes three arguments:
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [thisArg] - The value of `this` when `callback` is called.
* @returns {any[]} the return values of `callback` after being called on every object
* in the collection.
* @since 0.11.0
*/
map(callback, thisArg) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.prototype.reduce}
* @param {function} callback - Function to execute on each object in the collection.
* This function takes four arguments:
* - `previousValue` The value previously returned in the last invocation of the callback,
* or `initialValue`, if supplied.
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [initialValue] - The value to use as the first argument to the first call
* of the `callback`.
* @throws {TypeError} If the collection is empty and no `initialValue` was supplied.
* @returns {any} the value returned by the final invocation of `callback`, _except_ for
* the following special cases:
* - If collection consists of a single object, and no `initalValue` was supplied, then
* that object will be returned.
* - If the collection is empty, then `initialValue` _must_ be supplied and will be returned.
* @since 0.11.0
*/
reduce(callback, initialValue) {}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight Array.prototype.reduceRight}
* @param {function} callback - Function to execute on each object, from **right to left**,
* in the collection. This function takes four arguments:
* - `previousValue` The value previously returned in the last invocation of the callback,
* or `initialValue`, if supplied.
* - `object` The current object being processed in the collection.
* - `index` The index of the object being processed in the collection.
* - `collection` The collection itself.
* @param {object} [initialValue] - The value to use as the first argument to the first call
* of the `callback`.
* @throws {TypeError} If the collection is empty and no `initialValue` was supplied.
* @returns {any} the value returned by the final invocation of `callback`, _except_ for
* the following special cases:
* - If collection consists of a single object, and no `initalValue` was supplied, then
* that object will be returned.
* - If the collection is empty, then `initialValue` _must_ be supplied and will be returned.
* @since 0.11.0
*/
reduceRight(callback, initialValue) {}
}
/**
* This is an ES6 iterator.
* @typedef Realm.Collection~Iterator
* @property {function} next - Returns an object with two properties:
* - `done` `true` if the iterator is done iterating through items in the collection,
* otherwise `false`
* - `value` the next item being iterated through in the collection, or `undefined` when
* `done` is `true`
* @property {function} Symbol.iterator - This method simply returns `this`, thus making this
* iterator itself _iterable_ (i.e. usable in
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of `for-of`}
* loops, with the
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator `...`}
* spread operator, and more).
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator iterator protocol}
*/
/**
* The sort descriptors may either just be a string representing the property name, **or** an
* array with two items: `[propertyName, reverse]`
* @typedef Realm.Collection~SortDescriptor
* @type {string|Array}
*/

@ -1 +1 @@
Subproject commit 951723451f8ff082d657135486b6fb30de8c2a26
Subproject commit ab495962a2cf92718374d53f9b7c2f7b7d164068

View File

@ -21,55 +21,10 @@
* (see {@linkplain Realm~ObjectSchemaProperty ObjectSchemaProperty}).
* The objects contained in a list are accessible through its index properties and may only be
* modified inside a {@linkplain Realm#write write} transaction.
* @extends Realm.Collection
* @memberof Realm
*/
class List {
/**
* The number of objects in the list.
* @type {number}
* @readonly
*/
get length() {}
/**
* Returns new results that represent this list being filtered by the provided query.
* ```js
* let merlots = wines.filtered('varietal == "Merlot" && vintage <= $0', maxYear);
* ```
* @param {string} query - Query used to filter results.
* @param {...any} [arg] - Each subsequent argument is used by the placeholders
* (e.g. `$0`, `$1`, `$2`, ) in the query.
* @throws {Error} If the query or any other argument passed into this method is invalid.
* @returns {Realm.Results} filtered according to the provided query.
*/
filtered(query, ...arg) {}
/**
* Returns new results that represent this list being sorted by the provided property
* (or properties) of each object.
* @param {string|Realm.Results~SortDescriptor[]} descriptor - The property name(s) to sort
* results by.
* @param {boolean} [reverse=false] - May only be provided if `descriptor` is a string.
* @throws {Error} If a specified property does not exist.
* @returns {Realm.Results} sorted according to the arguments passed in
*/
sorted(descriptor, reverse) {}
/**
* Create a frozen snapshot of the list. This means changes to the list will not be
* reflected in the results returned by this method. However, deleted objects will become
* `null` at their respective indices.
* @returns {Realm.Results} which will **not** live update.
*/
snapshot() {}
/**
* Remove the **first** object from the list and return it.
* @throws {Error} If not inside a write transaction.
* @returns {Realm.Object|undefined} if the list is empty.
*/
shift() {}
class List extends Collection {
/**
* Remove the **last** object from the list and return it.
* @throws {Error} If not inside a write transaction.
@ -88,6 +43,13 @@ class List {
*/
push(...object) {}
/**
* Remove the **first** object from the list and return it.
* @throws {Error} If not inside a write transaction.
* @returns {Realm.Object|undefined} if the list is empty.
*/
shift() {}
/**
* Changes the contents of the list by removing objects and/or inserting new objects.
* @see {@linkcode https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice}

View File

@ -16,57 +16,13 @@
//
////////////////////////////////////////////////////////////////////////////
/**
* Instances of this class are typically **live** collections returned by
* {@link Realm#objects objects()} that will update as new objects are either
* added to or deleted from the Realm that match the underlying query. Results returned by
* {@link Realm.Results#snapshot snapshot()}, however, are will **not** live update.
* @extends Realm.Collection
* @memberof Realm
*/
class Results {
/**
* The number of objects in the results.
* @type {number}
* @readonly
*/
get length() {}
/**
* Returns new results that are filtered by the provided query.
* ```js
* let merlots = wines.filtered('varietal == "Merlot" && vintage <= $0', maxYear);
* ```
* @param {string} query - Query used to filter results.
* @param {...any} [arg] - Each subsequent argument is used by the placeholders
* (e.g. `$0`, `$1`, `$2`, ) in the query.
* @throws {Error} If the query or any other argument passed into this method is invalid.
* @returns {Realm.Results} filtered according to the provided query.
*/
filtered(query, ...arg) {}
/**
* Returns new results that are sorted by the provided property (or properties) of each object.
* @param {string|Realm.Results~SortDescriptor[]} descriptor - The property name(s) to sort
* results by.
* @param {boolean} [reverse=false] - May only be provided if `descriptor` is a string.
* @throws {Error} If a specified property does not exist.
* @returns {Realm.Results} sorted according to the arguments passed in
*/
sorted(descriptor, reverse) {}
/**
* Create a frozen snapshot of the results. This means changes to the list will not be
* reflected in the results returned by this method. However, deleted objects will become
* `null` at their respective indices.
* @returns {Realm.Results} which will **not** live update.
*/
snapshot() {}
class Results extends Collection {
}
/**
* The sort descriptors may either just be a string representing the property name, **or** an
* array with two items: `[propertyName, reverse]`
* @typedef Realm.Results~SortDescriptor
* @type {string|Array}
*/

125
lib/browser/collections.js Normal file
View File

@ -0,0 +1,125 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
'use strict';
import { keys } from './constants';
import { getterForProperty, setterForProperty } from './util';
let mutationListeners = {};
export default class Collection {
constructor() {
throw new TypeError('Illegal constructor');
}
}
export function addMutationListener(realmId, callback) {
let listeners = mutationListeners[realmId] || (mutationListeners[realmId] = new Set());
listeners.add(callback);
}
export function removeMutationListener(realmId, callback) {
let listeners = mutationListeners[realmId];
if (listeners) {
listeners.delete(callback);
}
}
export function clearMutationListeners() {
mutationListeners = {};
}
export function fireMutationListeners(realmId) {
let listeners = mutationListeners[realmId];
if (listeners) {
listeners.forEach((cb) => cb());
}
}
export function createCollection(prototype, realmId, info, mutable) {
let collection = Object.create(prototype);
let size = 0;
Object.defineProperties(collection, {
'length': {
get: getterForProperty('length'),
},
'-1': {
value: undefined,
},
});
let resize = function(length) {
if (length == null) {
length = collection.length;
}
if (length == size) {
return;
}
let props = {};
if (length > size) {
for (let i = size; i < length; i++) {
props[i] = {
get: getterForProperty(i),
set: mutable ? setterForProperty(i) : undefined,
enumerable: true,
configurable: true,
};
}
}
else if (length < size) {
for (let i = size; i >= length; i--) {
delete collection[i];
}
}
// Helpfully throw an exception on attempts to set to one past the last index.
props[length] = {
value: undefined,
configurable: true,
};
Object.defineProperties(collection, props);
size = length;
};
collection[keys.realm] = realmId;
collection[keys.id] = info.id;
collection[keys.type] = info.type;
resize(info.size);
addMutationListener(realmId, function listener() {
try {
resize();
} catch (e) {
// If the error indicates the collection was deleted, then remove this listener.
if (e.message.indexOf('is not attached') > 0) {
removeMutationListener(realmId, listener);
} else {
throw e;
}
}
});
return collection;
}

View File

@ -20,18 +20,19 @@
import { NativeModules } from 'react-native';
import { keys, propTypes, objectTypes } from './constants';
import * as lists from './lists';
import Collection, * as collections from './collections';
import List, { createList } from './lists';
import Results, { createResults } from './results';
import * as objects from './objects';
import * as results from './results';
import * as rpc from './rpc';
import * as util from './util';
const {debugHosts, debugPort} = NativeModules.Realm;
const listenersKey = Symbol();
rpc.registerTypeConverter(objectTypes.LIST, lists.create);
rpc.registerTypeConverter(objectTypes.LIST, createList);
rpc.registerTypeConverter(objectTypes.RESULTS, createResults);
rpc.registerTypeConverter(objectTypes.OBJECT, objects.create);
rpc.registerTypeConverter(objectTypes.RESULTS, results.create);
export default class Realm {
constructor(config) {
@ -137,7 +138,7 @@ export default class Realm {
callback();
} catch (e) {
rpc.cancelTransaction(realmId);
util.fireMutationListeners(realmId);
collections.fireMutationListeners(realmId);
throw e;
}
@ -159,11 +160,14 @@ util.createMethods(Realm.prototype, objectTypes.REALM, [
], true);
Object.defineProperties(Realm, {
Collection: {
value: Collection,
},
List: {
value: lists.List,
value: List,
},
Results: {
value: results.Results,
value: Results,
},
Types: {
value: Object.freeze(propTypes),
@ -179,7 +183,7 @@ Object.defineProperties(Realm, {
},
clearTestState: {
value: function() {
util.clearMutationListeners();
collections.clearMutationListeners();
rpc.clearTestState();
},
},

View File

@ -18,13 +18,11 @@
'use strict';
import Collection, { createCollection } from './collections';
import { objectTypes } from './constants';
import { createCollection, createMethods } from './util';
import { createMethods } from './util';
export class List {
constructor() {
throw new TypeError('Illegal constructor');
}
export default class List extends Collection {
}
// Non-mutating methods:
@ -43,6 +41,6 @@ createMethods(List.prototype, objectTypes.LIST, [
'splice',
], true);
export function create(realmId, info) {
export function createList(realmId, info) {
return createCollection(List.prototype, realmId, info, true);
}

View File

@ -18,13 +18,11 @@
'use strict';
import Collection, { createCollection } from './collections';
import { objectTypes } from './constants';
import { createCollection, createMethods } from './util';
import { createMethods } from './util';
export class Results {
constructor() {
throw new TypeError('Illegal constructor');
}
export default class Results extends Collection {
}
createMethods(Results.prototype, objectTypes.RESULTS, [
@ -33,6 +31,6 @@ createMethods(Results.prototype, objectTypes.RESULTS, [
'snapshot',
]);
export function create(realmId, info) {
export function createResults(realmId, info) {
return createCollection(Results.prototype, realmId, info);
}

View File

@ -18,106 +18,10 @@
'use strict';
import { fireMutationListeners } from './collections';
import { keys } from './constants';
import * as rpc from './rpc';
let mutationListeners = {};
function addMutationListener(realmId, callback) {
let listeners = mutationListeners[realmId] || (mutationListeners[realmId] = new Set());
listeners.add(callback);
}
function removeMutationListener(realmId, callback) {
let listeners = mutationListeners[realmId];
if (listeners) {
listeners.delete(callback);
}
}
export function clearMutationListeners() {
mutationListeners = {};
}
export function fireMutationListeners(realmId) {
let listeners = mutationListeners[realmId];
if (listeners) {
listeners.forEach((cb) => cb());
}
}
export function createCollection(prototype, realmId, info, mutable) {
let list = Object.create(prototype);
let size = 0;
Object.defineProperties(list, {
'length': {
get: getterForProperty('length'),
},
'-1': {
value: undefined,
},
});
let resize = function(length) {
if (length == null) {
length = list.length;
}
if (length == size) {
return;
}
let props = {};
if (length > size) {
for (let i = size; i < length; i++) {
props[i] = {
get: getterForProperty(i),
set: mutable ? setterForProperty(i) : undefined,
enumerable: true,
configurable: true,
};
}
}
else if (length < size) {
for (let i = size; i >= length; i--) {
delete list[i];
}
}
// Helpfully throw an exception on attempts to set to list[list.length].
props[length] = {
value: undefined,
configurable: true,
};
Object.defineProperties(list, props);
size = length;
};
list[keys.realm] = realmId;
list[keys.id] = info.id;
list[keys.type] = info.type;
resize(info.size);
addMutationListener(realmId, function listener() {
try {
resize();
} catch (e) {
// If the error indicates the list was deleted, then remove this listener.
if (e.message.indexOf('is not attached') > 0) {
removeMutationListener(realmId, listener);
} else {
throw e;
}
}
});
return list;
}
export function createMethods(prototype, type, methodNames, mutates) {
let props = {};

View File

@ -20,6 +20,19 @@
var arrayPrototype = Array.prototype;
// eslint-disable-next-line no-undef
var iteratorSymbol = typeof Symbol != 'undefined' && Symbol.iterator;
var iteratorPrototype = {};
if (iteratorSymbol) {
// These iterators should themselves be iterable.
Object.defineProperty(iteratorPrototype, iteratorSymbol, {
value: function() {
return this;
}
});
}
[
'join',
'slice',
@ -43,35 +56,36 @@ var arrayPrototype = Array.prototype;
var self = this;
var index = 0;
return {
next: function() {
if (!self || index >= self.length) {
self = null;
return {done: true, value: undefined};
}
return Object.create(iteratorPrototype, {
next: {
value: function() {
if (!self || index >= self.length) {
self = null;
return {done: true, value: undefined};
}
var value;
switch (methodName) {
case 'entries':
value = [index, self[index]];
break;
case 'keys':
value = index;
break;
default:
value = self[index];
}
var value;
switch (methodName) {
case 'entries':
value = [index, self[index]];
break;
case 'keys':
value = index;
break;
default:
value = self[index];
}
index++;
return {done: false, value: value};
index++;
return {done: false, value: value};
}
}
};
});
};
exports[methodName] = {value: method};
});
/* global Symbol */
if (typeof Symbol != 'undefined' && Symbol.iterator) {
exports[Symbol.iterator] = exports.values;
if (iteratorSymbol) {
exports[iteratorSymbol] = exports.values;
}

View File

@ -18,7 +18,7 @@
'use strict';
var arrayMethods = require('./array-methods');
var arrayMethods = require('./collection-methods');
var realmConstructor;
if (typeof Realm != 'undefined') {
@ -31,8 +31,7 @@ if (typeof Realm != 'undefined') {
throw new Error('Missing Realm constructor - please ensure RealmReact framework is included!');
}
// Add the specified Array methods to the prototype of List and Results.
Object.defineProperties(realmConstructor.List.prototype, arrayMethods);
Object.defineProperties(realmConstructor.Results.prototype, arrayMethods);
// Add the specified Array methods to the Collection prototype.
Object.defineProperties(realmConstructor.Collection.prototype, arrayMethods);
module.exports = realmConstructor;

View File

@ -15,6 +15,7 @@ include $(CLEAR_VARS)
LOCAL_MODULE := librealmreact
LOCAL_SRC_FILES := \
src/js_collection.cpp \
src/js_list.cpp \
src/js_results.cpp \
src/js_init.cpp \

30
src/js_collection.cpp Normal file
View File

@ -0,0 +1,30 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "js_collection.hpp"
static JSClassRef RJSCreateCollectionClass() {
JSClassDefinition classDefinition = kJSClassDefinitionEmpty;
classDefinition.className = "Collection";
return JSClassCreate(&classDefinition);
}
JSClassRef RJSCollectionClass() {
static JSClassRef s_collectionClass = RJSCreateCollectionClass();
return s_collectionClass;
}

23
src/js_collection.hpp Normal file
View File

@ -0,0 +1,23 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "js_util.hpp"
JSClassRef RJSCollectionClass();

View File

@ -19,6 +19,7 @@
#include "js_init.h"
#include "js_realm.hpp"
#include "js_object.hpp"
#include "js_collection.hpp"
#include "js_list.hpp"
#include "js_results.hpp"
#include "js_util.hpp"
@ -69,6 +70,7 @@ static JSValueRef ClearTestState(JSContextRef ctx, JSObjectRef function, JSObjec
JSObjectRef RJSConstructorCreate(JSContextRef ctx) {
static JSStringRef clearTestStateString = JSStringCreateWithUTF8CString("clearTestState");
static JSStringRef collectionString = JSStringCreateWithUTF8CString("Collection");
static JSStringRef listString = JSStringCreateWithUTF8CString("List");
static JSStringRef resultsString = JSStringCreateWithUTF8CString("Results");
static JSStringRef typeString = JSStringCreateWithUTF8CString("Types");
@ -76,6 +78,9 @@ JSObjectRef RJSConstructorCreate(JSContextRef ctx) {
JSObjectRef realmObject = JSObjectMake(ctx, RJSRealmConstructorClass(), NULL);
JSPropertyAttributes attributes = kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete;
JSObjectRef collectionConstructor = JSObjectMakeConstructor(ctx, RJSCollectionClass(), UncallableConstructor);
RJSValidatedSetProperty(ctx, realmObject, collectionString, collectionConstructor, attributes);
JSObjectRef listConstructor = JSObjectMakeConstructor(ctx, RJSListClass(), UncallableConstructor);
RJSValidatedSetProperty(ctx, realmObject, listString, listConstructor, attributes);

View File

@ -17,6 +17,7 @@
////////////////////////////////////////////////////////////////////////////
#include "js_list.hpp"
#include "js_collection.hpp"
#include "js_object.hpp"
#include "js_results.hpp"
#include "js_util.hpp"
@ -271,6 +272,6 @@ static const JSStaticFunction RJSListFuncs[] = {
};
JSClassRef RJSListClass() {
static JSClassRef s_listClass = RJSCreateWrapperClass<List *>("RealmList", ListGetProperty, ListSetProperty, RJSListFuncs, ListPropertyNames);
static JSClassRef s_listClass = RJSCreateWrapperClass<List *>("List", ListGetProperty, ListSetProperty, RJSListFuncs, ListPropertyNames, RJSCollectionClass());
return s_listClass;
}

View File

@ -17,6 +17,7 @@
////////////////////////////////////////////////////////////////////////////
#include "js_results.hpp"
#include "js_collection.hpp"
#include "js_object.hpp"
#include "object_accessor.hpp"
#include "results.hpp"
@ -243,6 +244,6 @@ static const JSStaticFunction RJSResultsFuncs[] = {
};
JSClassRef RJSResultsClass() {
static JSClassRef s_objectClass = RJSCreateWrapperClass<Results *>("Results", ResultsGetProperty, ResultsSetProperty, RJSResultsFuncs, ResultsPropertyNames);
static JSClassRef s_objectClass = RJSCreateWrapperClass<Results *>("Results", ResultsGetProperty, ResultsSetProperty, RJSResultsFuncs, ResultsPropertyNames, RJSCollectionClass());
return s_objectClass;
}

View File

@ -54,7 +54,7 @@ inline T RJSGetInternal(JSObjectRef jsObject) {
template<typename T>
JSClassRef RJSCreateWrapperClass(const char * name, JSObjectGetPropertyCallback getter = NULL, JSObjectSetPropertyCallback setter = NULL, const JSStaticFunction *funcs = NULL,
JSObjectGetPropertyNamesCallback propertyNames = NULL) {
JSObjectGetPropertyNamesCallback propertyNames = NULL, JSClassRef parentClass = NULL) {
JSClassDefinition classDefinition = kJSClassDefinitionEmpty;
classDefinition.className = name;
classDefinition.finalize = RJSFinalize<T>;
@ -62,6 +62,7 @@ JSClassRef RJSCreateWrapperClass(const char * name, JSObjectGetPropertyCallback
classDefinition.setProperty = setter;
classDefinition.staticFunctions = funcs;
classDefinition.getPropertyNames = propertyNames;
classDefinition.parentClass = parentClass;
return JSClassCreate(&classDefinition);
}

View File

@ -30,6 +30,7 @@ module.exports = BaseTest.extend({
realm.write(function() {
var obj = realm.create('PersonList', {list: []});
TestCase.assertTrue(obj.list instanceof Realm.List);
TestCase.assertTrue(obj.list instanceof Realm.Collection);
});
TestCase.assertThrows(function() {
@ -575,20 +576,24 @@ module.exports = BaseTest.extend({
TestCase.assertEqual(list.reduce(function(n, p) {return n + p.age}, 0), 33);
TestCase.assertEqual(list.reduceRight(function(n, p) {return n + p.age}, 0), 33);
[
'entries',
'keys',
'values',
typeof Symbol != 'undefined' && Symbol.iterator, // eslint-disable-line no-undef
].forEach(function(methodName) {
if (!methodName) {
return;
}
// eslint-disable-next-line no-undef
var iteratorSymbol = typeof Symbol != 'undefined' && Symbol.iterator;
var iteratorMethodNames = ['entries', 'keys', 'values'];
if (iteratorSymbol) {
iteratorMethodNames.push(iteratorSymbol);
}
iteratorMethodNames.forEach(function(methodName) {
var iterator = list[methodName]();
var count = 0;
var result;
if (iteratorSymbol) {
// This iterator should itself be iterable.
TestCase.assertEqual(iterator[iteratorSymbol](), iterator);
}
while ((result = iterator.next()) && !result.done) {
var value = result.value;

View File

@ -29,6 +29,7 @@ module.exports = BaseTest.extend({
var objects = realm.objects('TestObject');
TestCase.assertTrue(objects instanceof Realm.Results);
TestCase.assertTrue(objects instanceof Realm.Collection);
TestCase.assertThrows(function() {
new Realm.Results();