What is the correct path for a prefilled Realm file? - react-native

I have a realm file that is prefilled with the correct data. That file has the following schemas defined:
import Realm from 'realm';
let WordSchema = {
name: 'Word',
properties: {
word: 'string',
definition: 'string'
}
}
let BookmarkSchema = {
name: 'Bookmark',
properties: {
words: {type: 'list', object: 'Word'}
}
}
export default new Realm({
path: 'dictionary.realm',
schema: [WordSchema, BookmarkSchema]
}
I am having huge trouble trying bundle a prefilled Realm database.
Do I have the correct path name? The realm file is located in the same folder as the script.
Thank you for reading my question.

Related

Realm JS + React-Native: “no internal field” when creating a new object

I’m using the WildAid O-FISH post to create a similar project using realm JS react-native SDK with flexible sync.
I’m trying to create a Photo object but I get a “no internal field” error.
Here’s my Photo model
export class Photo extends Realm.Object {
_id;
user;
result;
picture;
pictureUrl;
annotation;
userInputs;
createdAt;
projectId;
static schema = {
name: "Photo",
properties: {
_id: "objectId",
user: "string",
result: "Result?",
picture: "data?",
pictureUrl: "string?",
annotation: "string?",
userInputs: "{}?",
createdAt: "date",
projectId: "objectId",
},
primaryKey: "_id",
};
}
export const ResultSchema = {
name: "Result",
embedded: true,
properties: {
traits: "{}?",
errors: "{}?",
score: "{}?",
},
};
And here’s how I’m creating a new photo
// Write transaction omitted
// Read a local image and convert it to base64
const picture = await readFile(path, "base64");
// Convert the base64 image to Buffer
const binaryBuffer = Buffer.from(picture, "base64");
const newPhoto = realm.create("Photo", {
_id: new Realm.BSON.ObjectId(),
user: user.profile.email,
userInputs: section.userInputs,
createdAt: new Date(),
projectId: new Realm.BSON.ObjectId(projectId),
annotation: "someString",
picture: binaryBuffer,
})
I feel like the problem might come from the picture property. I read in the doc that data type maps to ArrayBuffer which is what a Buffer is. Maybe it’s another field causing the problem but I really don’t know which one.
Thanks in advance!

Vuex Modules Creating Nested Object

I have been trying to separate my store.js file into multiple store modules. I have it working (somewhat), but it also created kind of a big issue.
In my initial one single file store, let's suppose this is my state object:
state: { user: '' }
And the output in the Vuex developer tools shows the user object as it should:
User: { name: "John", age: 33 }
But after splitting the the store into modules the user object in the Vuex developer tools is as follows:
User: { User: { name: "John", age: 33 } }
So it creates a new object using the name I give it in the modules object and import in the main store.js file, which then contains the "true" user object.
Is there any way to have it not create a new object and keep it the same as if the entire store lived inside the store.js file?
-Sergio
EDIT:
Here is the structure of my files:
store
store.js
modules
user.js
The code in the modules/user.js:
const state = { User: '' }
const mutations = { ... }
const actions = { ... }
export default { state, mutations, actions }
The code in my store.js
import User from './modules/user';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
User
}
});
Prior to externalizing the store I would get in Vuex dev tools:
User: { name: "John", age: 33 }
After externalizing the store I get:
User: { User: { name: "John", age: 33 } }
It's nesting User from the modules/user file inside the User in the store.js file. I want to avoid that (if its possible) so that I don't have to change everything in my components/template files.
The 'extra parent object' shown in the Vue Devtools is actually the namespaced module. If you set the User module's namespace attribute to false, the User state will no longer be placed within a namespaced object and will instead be
registered under the global namespace. (Vuex Namespacing)
Setting namespace: false is totally fine if you don't expect User function names to conflict with other modular state function names.
const store = new Vuex.Store({
modules: {
User: {
namespaced: false,
state: { user: '' },
...
}
}
}

ember multi level has many serialization issue

I am facing some issues with my serialization of model. Below is a detailed code which will show how my current model and corresponding serializers look.
User model
export default Model.extend({
name: attr('string'),
accounts: hasMany('account', {async: false})
});
Account model
export default Model.extend({
type: attr('string'),
transactions: hasMany('transaction')
})
Transaction model
export default Model.extend({
date: attr('string'),
amount: attr('number')
})
So basically its a hasMany within another hasMany.
Serializers looks like this:
base serializer:
export default BaseSerializer.extend({
keyForAttribute(key) {
return key.underscore();
},
keyForRelationship(key, relationship) {
return key.underscore();
}
});
User serializer:
export default BaseSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
account: { embedded: 'always' }
}
});
Account serializer:
export default BaseSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
transaction: { embedded: 'always' }
}
});
Now when I am invoking api call which gives me a json response where user model has a property named as accounts: which internally have another property called as transactions, I am expecting them to serialize but somehow its not working. have I done anything wrong here? Please advise as I am new to ember and still learning it.
Base serializer is:
export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, {
keyForRelationship(key, relationship) {
return key.underscore();
}
})
Serialized json
I dont have it but from the console logs, seems like only user model is getting serialized as when I tried to print console.log(user.get('accounts').get('firstObject').get('type') then i saw undefined there.
What I want is:
{
name: "bhavya"
accounts: [
{
type : 'savings',
transactions: [
{
amount: 500
}
]
}
]
}

React Native Realm data not persisted

I am using realm.write however my default.realm file is not being updated. I have also added another object to my schema and I can use this whilst developing my React Native app, but the default.realm file is not updated to include this new object.
I can confirm it is not being saved by opening default.realm in Realm Browser. Also, after turning my mac on this morning (after shutting down last night) and running my React Native app then data was not in my Realm when I tried to access it.
Example code:
#queries.js
import Realm from 'realm'
// Define your models and their properties
class Car {}
Car.schema = {
name: 'Car',
primaryKey: 'id',
properties: {
id: 'int',
make: 'string',
model: {type: 'string', optional: true}
}
}
class Person {}
Person.schema = {
name: 'Person',
properties: {
id: 'int',
name: 'string'
}
}
// Get the default Realm with support for our objects
let realm = new Realm({schema: [Car, Person], schemaVersion: 3});
class Queries {
async syncCars()
{
try {
let responsePromise = await fetch(`http://api.localhost.com:3000/v1/cars?auth_token=xxx`).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
let responseJson = await responsePromise.json();
realm.write(() => {
responseJson.forEach((values) => {
realm.create('Car', values, true);
});
});
}
catch(error) {
console.log("error " + error);
}
}
}
export default new Queries
and then in my component code I have:
import Queries from './queries'
await Queries.syncCars();
As Kristian Dupont pointed out in the comments above, I was looking at the wrong file.
Following this answer I used realm.path in the Chrome debugger console and found the correct default.realm in a path that included /Library/Developer/CoreSimulator/Devices/. I'm not sure why OSX finder wasn't able to find this file. I'm unsure why a default.realm file was also created in my React Native directory but I have since deleted this file to avoid confusion and have had no further issues.

Keys in One Object Must be the Same as Keys in Another Object

Initial Setting
You have a JavaScript object for keeping configs, it may be extended by plugins, each plugin has a version and one property on the configs object.
const CONFIGS = {
plugins: {
plugins: { version: '0.15' }, // Plugins is a plugin itself.
proxies: { version: '0.15' } // Used to configure proxies.
},
proxies: {
HTTPS: ['satan.hell:666']
}
}
Question
How to express in JSON schema, that each key of CONFIGS.plugins MUST have corresponding property on root of CONFIGS object and vice versa.
My Failed Attempt
ajv is 4.8.2, prints "Valid!" but must be "Invalid"
'use strict';
var Ajv = require('ajv');
var ajv = Ajv({allErrors: true, v5: true});
var schema = {
definitions: {
pluginDescription: {
type: "object",
properties: {
version: { type: "string" }
},
required: ["version"],
additionalProperties: false
}
},
type: "object",
properties: {
plugins: {
type: "object",
properties: {
plugins: {
$ref: "#/definitions/pluginDescription"
}
},
required: ["plugins"],
additionalProperties: {
$ref: "#/definitions/pluginDescription"
}
}
},
required: { $data: "0/plugins/#" }, // current obj > plugins > all props?
additionalProperties: false
};
var validate = ajv.compile(schema);
test({
plugins: {
plugins: { version: 'def' },
proxies: { version: 'abc' }
}
// Sic! No `proxies` prop, but must be.
});
function test(data) {
var valid = validate(data);
if (valid) console.log('Valid!');
else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}
There are three solutions here:
create another property on the root level, e.g. requiredProperties. Its value should be an array with the list of properties you want to have both on the top level and inside plugins. Then you can use required with $data pointing to this array both on top level and inside plugins.
See example here: https://runkit.com/esp/581ce9faca86cc0013c4f43f
use custom keyword(s).
check this requirement in code - there is no way in JSON schema to say keys in one object should be the same as keys in another (apart from above options).