简体   繁体   English

如何捆绑领域与本机应用程序

[英]How to bundle realm with react native app

I've just recently started working with react native and Realm, and it works great. 我刚刚开始使用本地和Realm的反应,它的效果非常好。

However up to this point we've only been using the realm file created in the default location, but we want to be able to package a realm file with our app when we ship it. 但是到目前为止,我们只使用在默认位置创建的领域文件,但是我们希望能够在发布时使用我们的应用程序打包领域文件。 Trying to access a direct path will create a new realm in the writable documents folder of our emulator, but I'm unsure how we can package the realm file that we've created and populate data into that folder. 尝试访问直接路径将在我们的模拟器的可写文档文件夹中创建一个新领域,但我不确定如何打包我们创建的领域文件并将数据填充到该文件夹​​中。

Is there a way to tell react native to store a folder at the root of the project (eg ./data/) with the app, and be able to open a realm from that folder? 有没有办法告诉本机反应存储项目根目录下的文件夹(例如./data/)与应用程序,并能够从该文件夹打开领域?

I tried this in the constructor of the page requiring the realm file: 我在需要realm文件的页面的构造函数中尝试了这个:

let realm = new Realm({
        path: './data/ourrealm.realm',
        schema: [schema1, schema2, schema3]
});

But this throws an error like so: 但这会抛出一个错误:

Error: Unable to open a realm at path './data/ourrealm.realm.management': 

make_dir() failed: No such file or directory Path:.

I found an issue on their GitHub about this same problem ( https://github.com/realm/realm-js/issues/816 ) but it seemed that user was able to access the file without an issue like this one, so I assume there's a step I'm missing in including that folder as available resources for the app. 我在他们的GitHub上发现了一个关于同样问题的问题( https://github.com/realm/realm-js/issues/816 ),但似乎用户能够访问该文件没有像这样的问题,所以我假设在将该文件夹包含为应用程序的可用资源时,我缺少一个步骤。

Assuming a structure like this: schema.js 假设这样的结构: schema.js

export const EVENTS_SCHEMA = 'events';
export const EventsSchema = {
  name: EVENTS_SCHEMA,
  primaryKey: 'EventID',
  properties: {
    EventID: 'int',
    EventName: 'string',
    EventDate: 'string'
  }
};

app.js app.js

import React, { Component } from 'react';
import { Text, View, Button, TextInput } from 'react-native';
import axios from 'axios';
import { EventsSchema, EVENTS_SCHEMA } from './allSchemas';
const Realm = require('realm');
const databaseOptions = {
  path: 'realmT4.realm',
  schema: [EventsSchema],
  schemaVersion: 0
};
type Props = {};
export default class App extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = { events: null, size: 0, runTime: 0, findName: '', text: '', updateText: '' };
  }
componentWillMount() {
  Realm.open(databaseOptions).then(realm => {
    this.setState({ size: realm.objects(EVENTS_SCHEMA).length });
  });
}
downloadEvents() {
  const startTime = new Date().getTime();
  axios.get('https://YourAPI/YourMethod')
   .then(response => {
     Realm.open(databaseOptions).then(realm => {
       realm.write(() => {
         response.data.forEach(obj => {
             if (realm.objects(EVENTS_SCHEMA).filtered(`EventID=${obj.EventID}`).length === 0) {
                  realm.create(EVENTS_SCHEMA, obj);
             }
         });
          this.setState({ size: realm.objects(EVENTS_SCHEMA).length });
          const endTime = new Date().getTime();
          this.setState({ runTime: endTime - startTime });
       });
     });
});
}
  uploadEvents() {
  }
clearAllEvents() {
  const startTime = new Date().getTime();
  Realm.open(databaseOptions)
  .then(realm => {
       realm.write(() => {
         const allEvents = realm.objects(EVENTS_SCHEMA);
         realm.delete(allEvents); // Deletes all books
         this.setState({ size: realm.objects(EVENTS_SCHEMA).length });
         const endTime = new Date().getTime();
         this.setState({ runTime: endTime - startTime });
       })
  })
  .catch(error => {
  });
}
findID() {
  const startTime = new Date().getTime();
    const text = this.state.text;
  Realm.open(databaseOptions).then(realm => {
    const res = realm.objects(EVENTS_SCHEMA).filtered(`EventID=${text}`)
    this.setState({ findName: res[0].EventID + ': ' + res[0].EventName })
    const endTime = new Date().getTime();
    this.setState({ runTime: endTime - startTime });
})
.catch((error) => {
  console.log(error);
});
}
findName() {
  const startTime = new Date().getTime();
  const text = this.state.text;
  Realm.open(databaseOptions).then(realm => {
    const res = realm.objects(EVENTS_SCHEMA).filtered(`EventName="${text}"`)
    this.setState({ findName: res[0].EventID + ': ' + res[0].EventName })
    const endTime = new Date().getTime();
    this.setState({ runTime: endTime - startTime });
})
.catch((error) => {
  console.log(error);
});
}
updateName() {
  const startTime = new Date().getTime();
  const updateText = this.state.updateText;
  const text = this.state.text;
  Realm.open(databaseOptions).then(realm => {
    let target = realm.objects(EVENTS_SCHEMA).filtered(`EventID=${text}`)[0];
    if (!target) {
      target = realm.objects(EVENTS_SCHEMA).filtered(`EventName=${text}`)[0];
    }
    realm.write(() => {
      target.EventName = updateText;
    })
    const endTime = new Date().getTime();
    this.setState({ runTime: endTime - startTime });
  })
}
render() {
    const info = 'Number of items in this Realm: ' + this.state.size
    return (
      <View >
        <Text>
          {info}
        </Text>
        <Text>
          Execution time: {this.state.runTime} ms
        </Text>
        <Button onPress={this.downloadEvents.bind(this)} title="Download" />
        <Button onPress={this.uploadEvents.bind(this)} title="Upload" />
        <Button onPress={this.clearAllEvents.bind(this)} title="Delete All" />
        <TextInput
          onChangeText={(text) => this.setState({ text })}
          value={this.state.text}
        />
        <Button onPress={this.findID.bind(this)} title="Find by ID" />
        <Button onPress={this.findName.bind(this)} title="Find by Name" />
        <Text>
          Find user: {this.state.findName}
        </Text>
        <Text>
          Update above user name to:
        </Text>
        <TextInput
          onChangeText={(updateText) => this.setState({ updateText })}
          value={this.state.updateText}
        />
          <Button onPress={this.updateName.bind(this)} title="Update Name" />
      </View>
    );
  }
}

Assuming (based on the example schema), you have a response from the server similar to this: 假设(基于示例模式),您有来自服务器的响应,类似于:

[{"EventID":1325,"EventName":"Summer Night","EventDate":"12/31/2018"},{"EventID":1326,"EventName":"Birthday Party","EventDate":"12/31/2011"}]

If you want to check the file where the data is stored, you might use: How to find my realm file? 如果要检查存储数据的文件,可以使用: 如何查找我的域文件?

How this works for you. 这对你有用吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM