看看这段代码,它需要本地.realm
文件并将其复制到远程同步领域。代码可以简化,因为看起来您已经知道架构 - 此代码动态加载架构。希望能帮助到你
// Copy local realm to ROS
const Realm = require('realm');
// UPDATE THESE
const realm_server = 'localhost:9080';
const source_realm_path = './localRealm.realm'; // path on disk
const target_realm_path = '/syncRealm'; // path on server
function copyObject(obj, objSchema, targetRealm) {
const copy = {};
for (var key in objSchema.properties) {
const prop = objSchema.properties[key];
if (prop.type == 'list') {
const propObjSchema = targetRealm.schema.find((s) => s.name == prop.objectType)
copy[key] = obj[key].map((obj) => copyObject(obj, propObjSchema, targetRealm))
}
else if (prop.type == 'object') {
const propObjSchema = targetRealm.schema.find((s) => s.name == prop.objectType)
copy[key] = obj[key] ? copyObject(obj[key], propObjSchema, targetRealm) : obj[key];
}
else {
copy[key] = obj[key];
}
}
return copy;
}
function getMatchingObjectInOtherRealm(sourceObj, source_realm, target_realm, class_name) {
const allObjects = source_realm.objects(class_name);
const ndx = allObjects.indexOf(sourceObj);
// Get object on same position in target realm
return target_realm.objects(class_name)[ndx];
}
function addLinksToObject(sourceObj, targetObj, objSchema, source_realm, target_realm) {
for (var key in objSchema.properties) {
const prop = objSchema.properties[key];
if (prop.hasOwnProperty('objectType')) {
if (prop['type'] == "list") {
var targetList = targetObj[key];
sourceObj[key].forEach((linkedObj) => {
const obj = getMatchingObjectInOtherRealm(linkedObj, source_realm, target_realm, prop.objectType);
targetList.push(obj);
});
}
else {
// Find the position of the linked object
const linkedObj = sourceObj[key];
if (linkedObj === null) {
continue;
}
// Set link to object on same position in target realm
targetObj[key] = getMatchingObjectInOtherRealm(linkedObj, source_realm, target_realm, prop.objectType);
}
}
}
}
function copyRealm(user, local_realm_path, remote_realm_url) {
// Open the local realm
const source_realm = new Realm({path: local_realm_path});
// Create the new realm (with same schema as the source)
const target_realm = new Realm({
sync: {
user: user,
url: remote_realm_url,
},
schema: require('./realmmodels')
});
// Copy all objects but ignore links for now
target_realm.schema.forEach((objSchema) => {
console.log("copying objects:", objSchema['name']);
const allObjects = source_realm.objects(objSchema['name']);
target_realm.write(() =>
allObjects.forEach((obj) => {
// Add this object to the target realm
target_realm.create(objSchema.name, copyObject(obj, objSchema, target_realm), true)
}));
});
}
const remote_realm_url = "realm://" + realm_server + target_realm_path;
copyRealm(Realm.Sync.User.adminUser("ADMIN_TOKEN"),
source_realm_path, remote_realm_url);
console.log("done");