EddyVerbruggen / nativescript-secure-storage

:closed_lock_with_key: NativeScript plugin for secure local storage of fi. passwords
MIT License
111 stars 26 forks source link

Saving multiple values or objects #6

Closed davorpeic closed 7 years ago

davorpeic commented 7 years ago

Hi Eddy,

just to be sure this is the right way, I have a user object that I would like to save, maybe not entire object, but most of the fields, so would like to know if there is a way to pass multiple values in one set method or I need to create n calls to set each value separately. The other question is if I send object to set, do you convert it to string or that is needed to be done before setting the value?

right now I'm saving multiple times..

        this.secureStorage.set({
            key: "user_email",
            value: user.email
        });
        this.secureStorage.set({
            key: "user_id",
            value: user.id
        });
        this.secureStorage.set({
            key: "user_name",
            value: user.first_name
        });

thanks

danielgek commented 7 years ago

@davorpeic you don't need to convert so string value can be an object and the key should be a string.

If you want you can create a new object and store only the fields you would like, or a entire object

Example:


let objectExample = {
    field: "value"
};

this.secureStorage.set({
    key: "user",
    value: {
        first_name: user.first_name
        email: user.email,
        id: user.id,
        objectExample: objectExample 
    }
});
davorpeic commented 7 years ago

thanks @danielgek this was exactly my idea :) thanks!!

danielgek commented 7 years ago

@davorpeic no problem ;) (updated with one or more things)

davorpeic commented 7 years ago

Ok, first I had to adopt interface so ts wouldn't scream

export interface SetOptions {
    service?: string;
    key: string;
    value: any; // change from string to any
}

but after that when I try to save an object I get

CONSOLE WARN file:///app/tns_modules/nativescript-secure-storage/secure-storage.js:30:18: Fatal JavaScript exception - application has been terminated.
file:///app/tns_modules/nativescript-secure-storage/secure-storage.js:30:18: JS ERROR Error: -[TNSDictionaryAdapter dataUsingEncoding:]: unrecognized selector sent to instance 0x17402eca0

Do you have idea why is this so?

EddyVerbruggen commented 7 years ago

@davorpeic did you try JSON.stringify on that value as well, so it's a string, and when read use JSON.parse to create the object again?

davorpeic commented 7 years ago

Hey @EddyVerbruggen yes, this is how I'm using it actually, I was wondering if there is 'better' way :)

EddyVerbruggen commented 7 years ago

The problem is the underlying system on iOS (keychain, exposed through the SAMKeychain library) doesn't allow anything other than strings. Android allows any type, but that's the reason the TS definition specs string.

I will add an example for stringify and parse to the readme 👍