How to fix 'RealmObject cannot be called as a function' realm-js error?

820 Views Asked by At

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)

1

There are 1 best solutions below

0
Engr.Aftab Ufaq On

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?'}
    }
  };