Can't access a javascript Object via Postman's environment variables - javascript

I am new to postman API testing.
Recently I am using it's collection runner to test request iteration with data file(json).
The weird thing is if I try to access the environment variable that I set before, the console log always shows [object Object] instead of Object {}.
Here's my pre-request code on postman:
postman.setEnvironmentVariable("username", data.username);
postman.setEnvironmentVariable("password", data.password);
and the Tests code on postman:
var userData = {
username: environment.username,
password: environment.password
};
postman.setEnvironmentVariable("user", userData);
console.log(environment.user);
for(var key in environment.user){
console.log(key + ": "+ environment.user[key]);
}
Request URL: https://echo.getpostman.com/get?username={{username}}&password={{password}}
data.json:
[{
"username" : "Jon Snow",
"password" : "iloveGot123"
},{
"username" : "Akali",
"password" : "iWillKickyalla55"
},{
"username" : "Ricky Grimmes",
"password" : "rg0123455"
}]
Please help thank you.

According to the documentation:
postman.setEnvironmentVariable(variableName, variableValue): Sets an environment variable “variableName”, and assigns the string “variableValue” to it. You must have an environment selected for this method to work. Note: Only strings can be stored. Storing other types of data will result in unexpected behavior.
https://www.getpostman.com/docs/sandbox
So basically it's showing that because it wants a string only.
You can wrap the object with JSON.stringify() to convert it to a string and then use JSON.parse() when you want to turn it back into an object.

Related

Null object is String type in localStorage

I am coming from Java dev and new to javascript, can someone explains what is going on.
I am using localStorage to store my token in my browser.
localStorage.token = 'xxx'
When the users sign out, we remove the token, here is the code
localStorage.token = null
If we want to check wether the user is authenticated or not, we check the token
const isAuth = localStorage.token !== null
Here is the thing becomes weird to me. After I marked localStorage.token to null,
the result of localStorage.token !== null is still true !
I had done some investigation,
I logged the localStorage object and found out the token variable is "null" instead of null.
Here is my assumption.
When the browser needs to store the localStorage, it iterates inside the object fields, after finding the null object, it use toString to store the final form?
Localstorage in the browsers work only on the string types
localStorage.getItem('someItem');
localStorage.setItem('someItem', 'string value');
localStorage.removeItem('someItem');
give a value or overwrite the one present in the localstorage with the function set item, like code below :
localStorage.setItem('token' , 'your token here ');
and for access the value :
localStorage.getItem('token')
window.console.log("token :",localStorage.getItem('token'))
Use localStorage methods for setting, getting and removing token.
Check this link for more details: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
And for checking weather the token exists or not you can do this:
const isAuth = !!localStorage.token
You can use removeItem() to remove items from your localstorage.
localStorage.removeItem('token')
You can also use the function getItem() to retrieve the item.
localStorage.getItem('token')
This will return null when it doesn't exist.
Documentation
https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
https://blog.logrocket.com/localstorage-javascript-complete-guide/
Local storage can only save strings. That is a simple fact of life.
This is why JSON.parse and JSON.stringify are synonymous with reading and writing from and to local storage.
null is no exception.

Firebase js library retrieves empty data from non empty database

steps to reproduce:
Initialize your firebase db to:
{
"restaurants" : [ {
"address" : "via Rettifilo, 34 Castelguidone CH Italy",
"title" : "Dama & Dama"
}, {
"address" : "Corso Umberto I, 3 Castelguidone CH Italy",
"title" : "Bar sabatino"
} ]
}
Check your read/write firebase persmission rules to be
{
"rules": {
".read": true,
".write": true
}
}
Execute this js code:
firebase.inizializeApp(yourJsonConfig)
\*code*\
firebase.database().ref().once('value').then(function(snapshot){
console.log(snapshot.val()); \\ this will print Array(0)
})
Expected behaviour: console logs "{'restaurants' ........}"
Actual behaviour: console logs "Array(0)" i.e. NO DATA!
I use firebase js library (version 4.13.1). Where am I wrong?
You need use val() method to return your data.
firebase.database().ref().once('value').then(function(snapshot){
console.log(snapshot.val());
})
Edit: Then your problem exist in another piece of code what you did not show.
Check this example: http://jsfiddle.net/zgfr91yd/
In console log:
And see my data:
You need a unique key for parent of each restaurant. You can use 'push' function in Firebase for that.
The snapshot argument that's being passed to your callback is an object of type DataSnapshot. You shouldn't assume that the JSON formatting string of a DataSnapshot contains just the data from that location in the database. As you can see from the API docs, there are a lot of methods functionality in a DataSnapshot.
What you what to do is call val() on that snapshot in order to extract a JavaScript value from it. Read the API docs to further understand what that object may contain.

Firebase retrieves snapshot value as null

I use the .once( function in Firebase and am successfully retrieving the snapshot.key NAME of the directory. But this key has also a value.
When requesting snapshot.val() also gives out null despise it having a value.
The database looks like this:
stages {
stage1AVERYLONGHASH : "values i want to get"
stage2AVERYLONGHASH : "values i want to get"
}
My code
var ref = "stage1AVERYLONGHASH";
var branch = firebase.database().ref(ref).once('value').then(function(s){
console.log(s.key); // GIVES THE CORRECT ANSWER
console.log(s.val()); //GIVES null ... doesn't give me the "values i want.."
Am i doing it completely wrong?
I'm new to Firebase.
Please know that the database is structured like this intentionally.
I restricted read permission on "stages".
The game works as just requesting a hash from the database as a reference, to get contents.
I think you suppose to get the reference of the stage and then get the stage1 reference from him like :
.ref("stage").child("stage1")
I'm not sure about the actual syntax but I know that this is how I get my firebase data in android studio

Write an object containing an array of objects to a mongo database in Meteor

In my user collection, I have an object that contains an array of contacts.
The object definition is below.
How can this entire object, with the full array of contacts, be written to the user database in Meteor from the server, ideally in a single command?
I have spent considerable time reading the mongo docs and meteor docs, but can't get this to work.
I have also tried a large number of different commands and approaches using both the whole object and iterating through the component parts to try to achieve this, unsuccessfully. Here is an (unsuccessful) example that attempts to write the entire contacts object using $set:
Meteor.users.update({ _id: this.userId }, {$set: { 'Contacts': contacts}});
Thank you.
Object definition (this is a field within the user collection):
"Contacts" : {
"contactInfo" : [
{
"phoneMobile" : "1234567890",
"lastName" : "Johnny"
"firstName" : "Appleseed"
}
]
}
This update should absolutely work. What I suspect is happening is that you're not publishing the Contacts data back to the client because Meteor doesn't publish every key in the current user document automatically. So your update is working and saving data to mongo but you're not seeing it back on the client. You can check this by doing meteor mongo on the command line then inspecting the user document in question.
Try:
server:
Meteor.publish('me',function(){
if (this.userId) return Meteor.users.find(this.userId, { fields: { profile: 1, Contacts: 1 }});
this.ready();
});
client:
Meteor.subscribe('me');
The command above is correct. The issue is schema verification. Simple Schema was defeating the ability to write to the database while running 'in the background'. It doesn't produce an error, it just fails to produce the expected outcome.

Properly handling duplicated key with node-mysql

I'm writing a registration form in my application, the user's name and the user's email must be unique.
I run a mysql database and use node-mysql (v 2.0.0) as driver.
When a user tries to use a name that is allready registered in the database, mysql raises the following error : Error: ER_DUP_ENTRY: Duplicate entry 'John' for key 'nickname', but in the Error object raised by node-mysql contains no usefull informations about the error :
console.log(JSON.stringify(err));
{"code": "ER_DUP_ENTRY", "errno": 1062, "sqlState": "23000", "index": 0}
Where can I get the involved entry and key ? I need to know which of the key nickname or the key email is responsible for the duplicate key error, so that I can warn the user.
I know I can find this info doing err.toString() and parsing the result (which contains is the mysql error string itself) but I would like to know if there is a better way to do so.
The reason you don't see the message and other Error properties is that some of those "standard" properties are not set as enumerable and as a result JSON.stringify() does not pick them up.
You could add a toJSON() to Error that correctly returns serializes all properties. This method is automatically called by JSON.stringify() if it detects its existence on the value you pass in. Example:
var config = {
configurable: true,
value: function() {
var alt = {};
var storeKey = function(key) {
alt[key] = this[key];
};
Object.getOwnPropertyNames(this).forEach(storeKey, this);
return alt;
}
};
Object.defineProperty(Error.prototype, 'toJSON', config);

Categories