简体   繁体   中英

return error when entry not found in firebase database

I have an array including some objecta. The user should be able to call all objects via moduls/ and a specific one via moduls/$id . But when the there is no modul the database should return an error so the client knows there is nothing.

returns no error when the modul doesn't exists:

"moduls": {
  ".read": "true",
    "$modul": {

    }
}

returns error when data doesn't exists but gives error when i want to get all moduls:

"moduls": {
    "$modul": {
        ".read": "data.exists()",
    }
}

So is there a way to solve both cases or is it better to check with the client if a specific value is set like:

if(typeof modul.name === "undefined") {
    //modul not found
}

You seem to want to use security rules to steer client-side logic. This is likely to give more problems than it's worth. Instead: use client-side code to steer client-side logic and security rules that ensure that your business rules are not violated.

If you can rephrase your business logic into something that fits those rules, you'll have a much easier time. For example "any user can create an object, but once it is created no-one can overwrite it", becomes:

"moduls": {
  "$modulId": {
    ".write": "!data.exists() && newData.exists()",
  }
}

And client-side:

function createModul(modulId) {
  var modulRef = ref.child('moduls').child(modulId);
  modulRef.once('value', function(snapshot) {
    if (snapshot.exists()) {
      console.error('Modul with '+modulId+' already exists);
    }
    else {
      modulRef.set('My new value', function(error) {
        if (error) {
          console.error('Write failed, probably somebody created '+modulId+' in the meantime')
        }
      });
    }
  }
}

Now the client checks its own business logic, and the server ensures it cannot be violated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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