I am writing a code to store some information to worklight Encrypted cache.
I am trying to encrypt a value which is primary key in my local DB which looks like 50005 it is a number and I am passing it to write method of encrypted cache
I am running project in web preview environment.
The error is Invalid argument value '50005', expected null or 'string'.
Following is the code snippet
function setUserId(userId){
WL.EncryptedCache.write("USER_ID",userId, onCompleteHandler, onErrorHandler);
}
function onCompleteHandler(status){
console.log("Global cache write success.");
}
function onErrorHandler(status){
console.log("Global cache open error."+status);
switch(status){
case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
console.log("ERROR: KEY CREATION IN PROGRESS");
break;
case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
console.log("ERROR: LOCAL STORAGE NOT SUPPORTED");
break;
case WL.EncryptedCache.ERROR_NO_EOC:
console.log("ERROR: NO EOC");
break;
case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
console.log("ERROR: COULD NOT GENERATE KEY");
break;
case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
console.log("ERROR: CREDENTIALS MISMATCH");
break;
default:
console.log("AN ERROR HAS OCCURED. STATUS :: " + status);
}
}
Always look at the API documentation before using an API call. Here's the documentation for write.
It says:
Parameters:
value - Mandatory. String. The data to encrypt. When set to null, the key is removed.
Change:
WL.EncryptedCache.write("USER_ID",userId, onCompleteHandler, onErrorHandler);
to:
WL.EncryptedCache.write("USER_ID",userId.toString(), onCompleteHandler, onErrorHandler);
You can only store strings using that API. If you want to store objects, you must use JSON.stringify (object to string) and JSON.parse (string to object). If you want to go from string to int, you can use the parseInt function like this: parseInt(userId)
.
Alternatively, you could use the JSONStore API instead. Note it's only supported on Android and iOS (in Worklight v6.2 it's supported on WP8 and W8 too). The code would look something like this:
var collections = {
users : {
searchFields : {'userid' : 'integer'}
}
};
var options = {
password: '123'
};
WL.JSONStore.init(collections, options)
.then(function () {
return WL.JSONStore.get('users').add({userid: 50005});
})
.then(function () {
return WL.JSONStore.get('users').findAll();//or .find({userid: 50005})
})
.then(function (results) {
WL.Logger.debug(results);
})
.fail(function () {
//handle failure in any of the API calls above
});
There's documentation here for JSONStore.