realm-js/lib/realm.js

87 lines
2.2 KiB
JavaScript
Raw Normal View History

'use strict';
2015-10-06 19:36:56 +00:00
let lists = require('./lists');
let objects = require('./objects');
2015-10-08 00:08:19 +00:00
let results = require('./results');
2015-10-06 19:36:56 +00:00
let rpc = require('./rpc');
let types = require('./types');
let util = require('./util');
let realmKey = util.realmKey;
// TODO: DATA
rpc.registerTypeConverter(types.DATE, (_, info) => new Date(info.value));
rpc.registerTypeConverter(types.LIST, lists.create);
rpc.registerTypeConverter(types.OBJECT, objects.create);
2015-10-08 17:22:52 +00:00
rpc.registerTypeConverter('ObjectTypesRESULTS', results.create);
class Realm {
constructor(config) {
let schema = typeof config == 'object' && config.schema;
let constructors = {};
for (let i = 0, len = schema ? schema.length : 0; i < len; i++) {
let item = schema[i];
let proto = item.prototype;
2015-10-06 19:36:56 +00:00
if (proto && proto.schema) {
schema.splice(i, 1, proto.schema);
constructors[proto.schema.name] = item;
}
}
let realmId = this[realmKey] = rpc.createRealm(config);
2015-10-06 07:52:15 +00:00
objects.registerConstructors(realmId, constructors);
}
addNotification(callback) {
// TODO
}
write(callback) {
2015-10-08 22:32:14 +00:00
let realmId = this[realmKey];
if (!realmId) {
throw new TypeError('write method was not called on a Realm object!');
}
if (typeof callback != 'function') {
throw new TypeError('Realm.write() must be passed a function!');
2015-10-08 22:32:14 +00:00
}
rpc.beginTransaction(realmId);
try {
callback();
} catch (e) {
2015-10-08 22:32:14 +00:00
rpc.cancelTransaction(realmId);
throw e;
}
2015-10-08 22:32:14 +00:00
rpc.commitTransaction(realmId);
}
}
[
'create',
'delete',
'deleteAll',
'objects',
].forEach(function(name) {
Object.defineProperty(Realm.prototype, name, {
value: function() {
let realmId = this[realmKey];
if (!realmId) {
throw new TypeError(name + ' method was not called on a Realm object!');
}
return rpc.callRealmMethod(realmId, name, Array.from(arguments));
}
});
});
Object.defineProperty(Realm, 'Types', {value: types});
module.exports = Realm;