Uploaded image for project: 'Realm JavaScript SDK'
  1. Realm JavaScript SDK
  2. RJS-2672

Realm file upload, can't able to process the data inside it, ( no realm export and import ) in React Native

      Problem

      There is no official way to export or import the realm data. I am able to download the .realm file but can't able to retrieve the data from that.

      this is the export function

      Unable to find source-code formatter for language: import. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      import RNFS from 'react-native-fs';
      import {getRealm} from './realmService';
      
      export const exportRealmData = async () => {
        try {
          const realm: Realm = await getRealm();
          const exportFileName = 'qqqq.realm';
          const exportFilePath = `${RNFS.DocumentDirectoryPath}/${exportFileName}`;
      
          if (await RNFS.exists(exportFilePath)) {
            await RNFS.unlink(exportFilePath);
          }
      
          const config = {
            path: exportFilePath,
            schema: realm.schema,
            schemaVersion: realm.schemaVersion + 1,
            encryptionKey: realm.encryptionKey,
          };
      
          realm.writeCopyTo(config);
      
          const downloadsFolder = RNFS.DownloadDirectoryPath;
          const destinationFilePath = `${downloadsFolder}/${exportFileName}`;
      
          await RNFS.moveFile(exportFilePath, destinationFilePath);
      
          console.log('Realm data exported to', destinationFilePath);
          return destinationFilePath;
        } catch (error) {
          console.error('Error exporting Realm data', error);
        }
      };
      

      I have tried to upload and retrieve the data, but i am unable to do that

        function normalizePath(path: string | undefined) {
          try {
            if (path === undefined) {
              throw console.error('undefined');
            }
            if (Platform.OS === 'ios' || Platform.OS === 'android') {
              const filePrefix = 'file:';
              if (path.startsWith(filePrefix)) {
                path = path.substring(filePrefix.length);
              }
              path = decodeURIComponent(path);
              return path;
            }
          } catch (e) {
            console.error({msg: 'Failed to normalize path', data: e});
          }
        }
      
        const handleFilePick = async () => {
          try {
            const result = await DocumentPicker.pick({
              type: [DocumentPicker.types.allFiles],
            });
            console.log(result);
            const {0: file1} = result;
      
            const path = normalizePath(file1?.uri);
            console.log(path);
            setRealmFile(path);
          } catch (err) {
            console.error(err);
          }
        };
      
        console.log(realmFile);
      
        const handleDataSubmit = async () => {
          try {
            if (!realmFile) {
              console.error('Please upload a .realm file');
              return;
            }
      
            const realm = await getRealm();
            const existingRealm = await Realm.open({path: realmFile.uri});
      
            console.log('This is the existing realm:', existingRealm);
      
            realm.write(() => {
              [User, Category, Expense, Currency, Debtor, Debt].forEach(schema => {
                const objects = existingRealm.objects(schema.schema.name);
                console.log(`Data for ${schema.schema.name}:`, objects.toJSON());
      
                objects.forEach(object => {
                  realm.create(schema.schema.name, object, Realm.UpdateMode.Modified);
                });
              });
            });
      
            await AsyncStorageService.setItem('isOnboarded', JSON.stringify(true));
            dispatch(setIsOnboarded(true));
      
            console.log('Data updated successfully!');
          } catch (error) {
            console.error('Error updating data:', error);
          }
        };
      

      This is the log

      LOG  content://com.android.providers.downloads.documents/document/msf:1000000035
       LOG  [{"fileCopyUri": null, "name": "qqqq.realm", "size": 4848, "type": "application/octet-stream", "uri": "content://com.android.providers.downloads.documents/document/msf%3A1000000035"}]
       LOG  content://com.android.providers.downloads.documents/document/msf:1000000035
       LOG  This is the existing realm: {"beforeNotifyListeners": {"eventType": "beforenotify", "listeners": Set {}, "realm": [Circular]}, "changeListeners": {"eventType": "change", "listeners": Set {}, "realm": [Circular]}, "schemaExtras": {}, "schemaListeners": {"eventType": "schema", "listeners": Set {}, "realm": [Circular]}, "syncSession": null}
      

      Solution

      a simple realm.export and realm.import function will be easy to interact with the data.

      Alternatives

      No response

      How important is this improvement for you?

      Would be a major improvement

      Feature would mainly be used with

      Local Database only

            Assignee:
            Unassigned Unassigned
            Reporter:
            unitosyncbot Unito Sync Bot
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: