0

In a react-native project using Realm-js, I've just created a clone of the app, integrated all libs, and copied over all src directories.

The app builds installs and runs on Android.

When i go through the authentication flow (which utilizes realm to store auth data), i ultimately get an error:

[ Error: RealmObject cannot be called as a function ]

login function:

async function login(username, password) {
    try {
      const result = await Api.login({
        username: username,
        pass: password,
      });

      const userAuthResult = await Db.updateAuth(result);
      setUserAuth(userAuthResult);
    } catch (err) {
      console.log('[ ERROR ]:', err)
      if (!err.message || err.message.includes('Network Error')) {
        throw new Error('Connection error');
      }
      throw new Error('Wrong username or password');
    }
  }

and ive narrowed down the issue to Db.updateAuth(...)

updateAuth:

export const updateAuth = (params) => {
  console.log(' [ HERE 1 ]')
  const auth = {
    id: params.id,
    token: params.token,
    refreshToken: params.refresh_token,
    tokenExpiresAt: Math.floor(Date.now() / 1000) + 600, //params.expires_at,
    federatedToken: params.federatedToken ?? '',
    federatedTokenExpiresAt: params.federatedTokenExpiresAt ?? 0,
    username: params.username,
    name: params.name,
    roleName: params.role_name,
    roleId: params.role_id,
    lastLogin: Math.floor(Date.now() / 1000),
  };
  console.log(' [ HERE 2 ]')

  realm.write(() => {
    console.log(' [ HERE 3 ]')

    realm.create('Authorizations', auth, 'modified'); // PROBLEM
  });

  return auth;
};

inspecting the schema, i found theres no federatedToken propereties, yet in the auth update object, there are two. not sure why it wouldnt be throwing an error in the original non-cloned app.

authorizations schema:

AuthorizationsSchema.schema = {
  name: 'Authorizations',
  primaryKey: 'id',
  properties: {
    id: 'int',
    token: 'string',
    refreshToken: 'string',
    tokenExpiresAt: 'int',
    username: 'string',
    name: 'string',
    roleName: 'string',
    roleId: 'int',
    lastLogin: 'int',
  },
};

Realm.js (class declaration) -> https://pastebin.pl/view/c903b2e2

from realm instantiation:

let realm = new Realm({
  schema: [
    schema.AccountSchema,
    schema.AuthorizationsSchema,
    schema.AvailableServiceSchema,
    schema.FederatedTokensSchema,
    schema.NoteSchema,
    schema.PhotoSchema,
    schema.PhotoUploadSchema,
    schema.PrintQueueSchema,
    schema.ProductSchema,
    schema.ReportSchema,
    schema.ServicesSchema,
    schema.UploadQueueJobSchema,
    schema.InvoicesSchema,
    schema.TestSchema
  ],
  schemaVersion: 60,
  deleteRealmIfMigrationNeeded: true,
  //path: './myrealm/data',
});

this logs the 1, 2, and 3 statements. The issue seems to come from the 'problem' line. Im not sure what exactly this error means, as there doesnt seem to be anything in realm's repo about it, and in the app this was cloned from, there was no issue with this line. I can also see other lines are throwing similar errors later on the user flows

Anyone know what this is about? or where i can learn more?

React-native: v64.2

realm-js: 10.6.0 (app cloned from was v10.2.0)

MacOS: 11.3 (M1 architecture)

Jim
  • 1,988
  • 6
  • 34
  • 68
  • As a test, change this `realm.create('Authorizations', auth, 'modified');` to this `realm.create('Person', { _id: 1234, name: "Joseph", }, 'modified');` and see if it still errors. I think the model is the issue. Oh, be sure to create a simple Person model with a name property prior to that code. Something similar to the [docs](https://docs.mongodb.com/realm/sdk/react-native/examples/read-and-write-data/#about-the-examples-on-this-page) – Jay Jul 26 '21 at 20:41
  • @Jay ok, i finished the test, it didnt throw an error on that line, why is that and what can do about this? – Jim Jul 26 '21 at 22:21
  • Good! That means the issue is in the model. So. Update your `Person` to include the first 1/2 of the auth properties., id, token, refreshToken etc. Then run the code. If it works then you know the issue is not one of those properties. Replace them with the second half of the properties and run it. This process is called a 'split half search' where we are attempting to isolate the offending property. Use that pattern over and over until you know which property is causing the crash – Jay Jul 26 '21 at 22:30
  • @Jay ok, actually, it appears the app wasnt fully reloaded, all caches cleared, our test schema is throwing the same 'RealmObject cannot be called as a function' error. i also outlined the schema in the post – Jim Jul 27 '21 at 14:14
  • That isolates it to how Realm is being used. If this `Db.updateAuth(result)` is throwing the error then either DB. is incorrect, updateAuth is or the result is. However, we don't know what those are or how that are instantiated. – Jay Jul 27 '21 at 16:53
  • class declaration and instatiation have been added to the post details @Jay – Jim Jul 27 '21 at 19:23
  • any additional input @Jay? im at a loss – Jim Jul 30 '21 at 03:03

1 Answers1

-1

in order to create you have the first call, the realm.write a method like this.

const storeInDataBase = (res,selectedfile) => {
    try{
        realm.write(() => {
            var ID =
            realm.objects(DocumentConverstionHistory).sorted('HistoryID', true).length > 0
            ? realm.objects(DocumentConverstionHistory).sorted('HistoryID', true)[0]
                .HistoryID + 1
            : 1;
            realm.create(DocumentConverstionHistory, {
                HistoryID: ID,
                Name:`${selectedfile.displayname}.pdf`,
                Uri:`file://${res.path()}`,
                Date: `${new Date()}`
            });
        })
    }catch(err){
        alert(err.message)
    }
}

Here is the schema file

export const DATABASENAME = 'documentconverter.realm';
export const DocumentConverstionHistory = "DocumentConverstionHistory"
export const DocumentConverstionHistorySchema = {
    name: "DocumentConverstionHistory",
    primaryKey: 'HistoryID',
    properties: {
        HistoryID: {type: 'int'},
        Name: {type: 'string'},
        Uri: {type: 'string?'},
        Type: {type: 'string?'},
        Size: {type: 'string?'},
        Date: {type: 'date?'}
    }
  };
  
Engr.Aftab Ufaq
  • 3,356
  • 3
  • 21
  • 47