Good way to replace invalid characters in firebase keys?

前端 未结 4 515
执念已碎
执念已碎 2020-12-05 13:43

My use case is saving a user\'s info. When I try to save data to Firebase using the user\'s email address as a key, Firebase throws the following error:

4条回答
  •  攒了一身酷
    2020-12-05 14:31

    I can think of two major ways to solve this issue:

    1. Encode/Decode function

    Because of the limited set of characters allowed in a Firebase key, a solution is to transform the key into an valid format (encode). Then have an inverse function (decode) to transform the encoded key back as the original key.

    A general encode/decode function might be transforming the original key into bytes, then converting them to a hexadecimal representation. But the size of the key might be an issue.

    Let's say you want to store users using the e-mail as key:

    # path: /users/{email} is User;
    /users/alice@email.com: {
        name: "Alice",
        email: "alice@email.com"
    }
    

    The example above doesn't work because of the dot in the path. So we use the encode function to transform the key into a valid format. alice@email.com in hexadecimal is 616c69636540656d61696c2e636f6d, then:

    # path: /users/{hex(email)} is User;
    /users/616c69636540656d61696c2e636f6d: {
        name: "Alice",
        email: "alice@email.com"
    }
    

    Any client can access that resource as long as they share the same hex function.

    Edit: Base64 can also be used to encode/decode the key. May be more efficient than hexadecimals, but there are many different implementations. If clients doesn't share the exact same implementation, then they will not work properly.

    Specialized functions (ex. that handles e-mails only) can also be used. But be sure to handle all the edge cases.

    1. Encode function with original key stored

    Doing one way transformation of the key is a lot easier. So, instead of using a decode function, just store the original key in the database.

    A good encode function for this case is the SHA-256 algorithm. It's a common algorithm with implementations in many platforms. And the chances of collisions are very slim.

    The previous example with SHA-256 becomes like this:

    # path: /users/{sha256(email)} is User;
    /users/55bf4952e2308638427d0c28891b31b8cd3a88d1610b81f0a605da25fd9c351a: {
        name: "Alice",
        email: "alice@email.com"
    }
    

    Any client with the original key (the e-mail) can find this entry, because the encode function is known (it is known). And, even if the key gets bigger, the size of the SHA-256 will always be the same, therefore, guaranteed to be a valid Firebase key.

提交回复
热议问题