TypeError: Object #<Object> has no method 'push' node js - node.js

when I am trying to add the object to array it while push it in the array I am unable to get push.
console.log('starting password manager');
var storage = require('node-persist');
storage.initSync();
// account.name Facebook
// account.username User12!
// account.password Password123!
accounts = [];
function createAccount (account) {
var accounts = storage.getItemSync('accounts');
if (typeof accounts === 'undefined') {
accounts = [];
}
accounts.push(account);
storage.setItemSync('accounts', accounts);
return account;
}
createAccount({
name: 'Facebook',
username: 'someemail#gmail.com',
password: 'Password123!'
});
I am using npm node-persist to store the var. which will save my used to save the var and push the aobject on the existing saved array.I am using npm node-persist to store the var. which will save my used to save the var and push the aobject on the existing saved array.

From the docs it looks like storage.getItemSync returns a value (which may or may not be an array). Thus, I would recommend adding a check: if(!Array.isArray(accounts)){ accounts = []; } and then proceeding.

Related

Uploading multiple files to stripe.files.create (Node-stripe)

I am trying to upload files to stripe which are submitted by the user in my frontend to verify their identity before they can sell on my platform.
Currently, the files are sent via an API request to the backend where I can upload a single file, and afterwards, I attach it to that user's account.
let file = {
data: fs.readFileSync(files.IDFront.path),
name: files.IDFront.name,
type: files.IDFront.type
}
stripe.files.create({
purpose: 'identity_document',
file
}, function(err, file) {
if(err) res.send({sucess:false, error: err})
else {
//attach to user's account
}
This works just fine, but some identity documents require pictures of the front and back, so my question is can I upload two files at once using stripe.files.create? I can't seem to find anything in Stripe's API docs which mentions this, and I don't want to use stripe.files.create twice in one function because I feel that isn't a very efficient way to write the function.
Any suggestions would be greatly appreciated
It is important to note that your documents still need to be sent to Stripe in their own calls in order to get their respective tokens.
The function below takes an object of document names and the returned stripe tokens
{
document: <stripeToken1>,
additional_document: <stripeToken2>
}
You can then iterate through these and append to the update object in one go
// create the document object template
const documentObject = {
individual: {
verification: {},
},
}
Object.entries(imageTokens).map(([_, token]) => {
const [keyToken] = Object.entries(token)
// separate key and token from object
const [documentKey, stripeTokenId] = keyToken
// convert our naming convention to stripes expected naming
const checkedKey = documentKey === 'document_front' ? 'document' :
documentKey
// append to document object
documentObject.individual.verification[checkedKey] = {
front: stripeTokenId,
}
return await stripe.accounts.update(stripeAccountId, documentObject)

How to interpolate variable into firebase snapshot?

I am using firebase functions to send users a notification. I can user string interpolation like so:
const original = change.after.val();
const lover = context.auth.uid;
const recipient_username = original.username;
const topic = `${recipient_username}_notifications`;
But now I need to make a database call to get the username from the user_id, and use the username to get the value of loves form the 'original' snapshot, but this does not work:
return db.ref('/users/' + lover).once('value', (snapshot) => {
var username = snapshot.val().username;
var love = original.loves.username // I need this to use the variable username, but it is just saying "username"
console.log("lover username")
console.log(username)
console.log("loves")
console.log(loves)
const payload = {
notification:{
title: "You've got Love!",
body: `${username} sent you Love! Refresh your inbox to recieve it, and why not send some back!`
}
};
How can I change var love = original.loves.username to be something like: var love = original.loves.${username}?
The database looks like this:
users/
username: usernamehere
love/
otherusername: 10 // the amount of love they sent.
You have called .val() on the original turning this into a Javascript object.
Traversing paths in Javascript objects can be done with the .loves helper functions or using string lookups. Try the following
var username = snapshot.val().username;
var love = original.loves[username];

How to read data of multiple user id in a single request in cloud functions on firebase

I am using Firebase Database for my Android application and cloud functions. As Firebase stores data in JSON format. Each user has some unique id which assigns to user.
I want to know if there is any way to get multiple users data on a single request. If you see below code it will fetch data only of passed user id.
db
.ref("/users/" + request.query.userId)
.once("value")
.then(function(snapshot) {
I have 10 user ids of which I want to get data on a single request in nodejs. What is the way to get this ?
Store them in an array like this:
var promArr = []
var snapshotData = []
promArr.push(
db
.ref("/users/" + request.query.userId) //put here unique usernames
.once("value")
.then(function(snapshot) {
snapshotData.push(snapshot.val())
})
return Promise.all(promArr).then(snap => {
//loop through snapshotData here
})
This can be written much cleaner:
const records = [
admin.database().ref(`users/${userId1}`).once('value'),
admin.database().ref(`users/${userId2}`).once('value'),
];
return Promise.all(records).then(snapshots => {
const record1 = snapshots[0].val();
const record2 = snapshots[1].val();
});

How to store documents in an ArangoDb graph using ArangoJs?

I am using latest version of ArangoDb and ArangoJs from a nodejs application. I have got following two vertexes
users
tokens
tokens vertex contain the security tokens issues to one of the user in the users vertex. I have got an edge definition named token_belongs_to connecting tokens to users
How do I store a newly generated token belonging to an existing user using ArangoJs?
I am going to assume you are using ArangoDB 2.7 with the latest version of arangojs (4.1 at the time of this writing) as the API has changed a bit since the 3.x release of the driver.
As you don't mention using the Graph API the easiest way is to simply use the collections directly. Using the Graph API however adds benefits like orphaned edges automatically being deleted when any of their vertices are deleted.
First you need to get a reference to each collection you want to work with:
var users = db.collection('users');
var tokens = db.collection('tokens');
var edges = db.edgeCollection('token_belongs_to');
Or if you are using the Graph API:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
In order to create a token for an existing user, you need to know the _id of the user. The _id of a document is made up of the collection name (users) and the _key of the document (e.g. 12345678).
If you don't have the _id or _key you can also look up the document by some other unique attribute. For example, if you have a unique attribute email that you know the value of, you could do this:
users.firstExample({email: 'admin#example.com'})
.then(function (doc) {
var userId = doc._id;
// more code goes here
});
Next you'll want to create the token:
tokens.save(tokenData)
.then(function (meta) {
var tokenId = meta._id;
// more code goes here
});
Once you have the userId and tokenId you can create the edge to define the relation between the two:
edges.save(edgeData, userId, tokenId)
.then(function (meta) {
var edgeId = meta._id;
// more code goes here
});
If you don't want to store any data on the edge you can substitute an empty object for edgeData or simply write it as:
edges.save({_from: userId, _to: tokenId})
.then(...);
So the full example would go something like this:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
Promise.all([
users.firstExample({email: 'admin#example.com'}),
tokens.save(tokenData)
])
.then(function (args) {
var userId = args[0]._id; // result from first promise
var tokenId = args[1]._id; // result from second promise
return edges.save({_from: userId, _to: tokenId});
})
.then(function (meta) {
var edgeId = meta._id;
// Edge has been created
})
.catch(function (err) {
console.error('Something went wrong:', err.stack);
});
Attention - syntax changes:
Edge creation:
const { Database, CollectionType } = require('arangojs');
const db = new Database();
const collection = db.collection("collection_name");
if (!(await collection.exists())
await collection.create({ type: CollectionType.EDGE_COLLECTION });
await collection.save({_from: 'from_id', _to: 'to_id'});
https://arangodb.github.io/arangojs/7.1.0/interfaces/_collection_.edgecollection.html#create

Redis: How to save (and read) Key-Value pairs at once by namespace/rule?

I want to utilize Redis for saving and reading a dynamic list of users.
Essentially, Redis is Key-Value pair storage. How can I read all the saved users at once? (for example, creating a namespace "users/user_id")
And since I am a Redis beginner,
Do you think the use of Redis in the above case is proper/efficient?
Thanks.
When using key/values for storing objects you should create a domain specific key by combining the domain name plus the unique id. For example, a user object that might look like this:
// typical user data model
var User = function(params) {
if (!params) params = {};
this.id = params.id;
this.username = params.username;
this.email = params.email;
// other stuff...
};
Then domain key could be created like this:
var createUserDomainKey = function(id) {
return 'User:' + id;
};
If the id was 'e9f6671440e111e49f14-77817cb77f36' the key would be this:
User:e9f6671440e111e49f14-77817cb77f36
Since redis will store string values, you need to serialize, probably with json so to save the user object. Assuming a valid use object would would do something like this:
var client = redis.createClient(),
key = createUserDomainKey( user.id ),
json = JSON.stringify( user ) ;
client.set( key, json, function(err, result) {
if (err) throw err; // do something here...
// result is 'OK'
});
For simple fire-hose queries returning all users, you can do this:
var client = redis.createClient();
client.keys( createUserDomainKey( '*' ), function(err, keys) {
if (err) throw err; // do something here
// keys contains all the keys matching 'User:*'
});
Note that the redis folks discourage the use of 'keys' for production, so a better approach is to build your own index using sorted-set, but if your user list is limited to a few hundred, there is no problem.
And since it returns a list of keys, you need to loop through and get each user then parse the json string to recover the real object. Assuming a populated list of keys, you could do something like this:
var client = redis.getClient(),
users = [];
var loopCallback = function(err, value) {
if (!err && value) {
// parse and add the user model to the list
users.push( JSON.parse( value ) );
}
// pull the next key, if available
var key = keys.pop();
if (key) {
client.get( key, loopCallback );
} else {
// list is complete so return users, probably through a callback;
}
}
// start the loop
loopCallback();
This is a good general purpose solution, but there are others that use sorted sets that are move efficient when you want access to the entire list with each access. This solution gives you the ability to get a single user object when you know the ID.
I hope this helps.
ps: a full implementation with unit tests of this can be found in the AbstractBaseDao module of this project.

Resources