Delete Firebase Users programmatically with Node.js - javascript

I use the Firebase SDK with Node.js and try to delete a bulk of accounts programmatically (identified by their email address).
What does work is to hardcode those accounts in my firebase-delete-users.js file like this:
const uids = [
{email: 'user1#example.com'},
{email: 'user2#example.com'},
];
const markedForDelete = [];
// Retrieve a batch of user accounts.
admin.auth().getUsers(uids)
.then((result) => {
result.users.forEach((user) => {
markedForDelete.push(user.uid);
});
result.notFound.forEach((uid) => {
console.log(`No user found for identifier: ${JSON.stringify(uid)}`)
});
})
.then(() => {
// Delete all marked user accounts in a single API call.
return admin.auth().deleteUsers(markedForDelete);
});
But it does no longer work if I try to get those elements out of a .txt file, where each line is one array-element.
var uids = fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n");
accounts-to-delete.txt :
{email: 'user1#example.com'}
{email: 'user2#example.com'}
The console log also doesn't look exactly the same if I compare uids and uids2 but I don't understand the reason and how to solve it:
var uids = fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n");
const uids2 = [
{email: 'user1#example.com'},
{email: 'user2#example.com'},
];
for(i in uids) {
console.log(uids[i]);
}
for(i in uids2) {
console.log(uids2[i]);
}
If it helps to find a solution:
It doesn’t have to be a .txt file if .json or some other filetype fits better for this use case.

Reading text from a file and iterating elements of an array of objects are completely different tasks. They have little on common, other than iteration.
Your bit of code that iterates an array of objects is simply taking advantage of the fact that the data in uids2 is already structured as Javascript arrays and object. It doesn't work the same for reading lines of raw text out of a file.
Your bit of code that reads the file is not able to assume the JSON structure of the data in its raw form. uids is just an array of strings. You will have to parse the JSON and turn each line into actual JavaScript objects using JSON.parse(). Something like this might work:
var uids = fs
.readFileSync("accounts-to-delete.txt", 'utf8')
.toString()
.split("\n")
.map(line => JSON.parse(line));
With this uids not just an array of strings, as it was before. It's now an array of JavaScript objects that are easier to work with.

fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n"); returns an array of strings instead an array or objectsm which is what you want.
So you can use JSON.parse() to parse each split line.

Related

How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)

Turning JSON.parse() return type to an array of object

I have defined a file called note-data.json which contains json data. In the following code a variable of type of array called notes is declared. What I want to achieve is that the program read the json file save it in the noteString variable and then make a array of object with JSON.parse() from noteString and put it into notes array. So I can add new objects to the json file. But when the programme gets to the line note.push() it complains since, I think, the type of notes has turned to a string and push is not define for string. How can I get around this issue?
Please ignore the fact that if the json file is not provided the the program crashes.
My code:
const addNote = (title, body) => {
let notes= [];
const note = {
title,
body
};
const notesString = fs.readFileSync('node-data.json', 'utf8');
notes = JSON.parse(notesString);
notes.push(note);
fs.writeFileSync('node-data.json', JSON.stringify(note));
}
File note-data.json:
{"title":"Greeting","body":"Hello"}
I think you are fumbling with your variables here. From what I understood - you want to read JSON from a file and append that JSON to an array, right? Following code will help you do just that
const addNote = (title, body) => {
let notes= []; //Declare an array
const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
notes.push(note); //Append new JSON to your array
//This line below appears to have no purpose ??
fs.writeFileSync('node-data.json', JSON.stringify(note));
}

In node.js how to extract uid from returned facebook providerData json array?

I've got my users signing in with facebook and that gets stored in firebase auth. In index.js i've got an onCreate function that stores some facebook related data in firestore.
When i log to cloud functions console event.data.providerData I get this:
[ { displayName: 'xxxx xxxxx',
photoURL: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/xxxxxxxxx_439xxx336xxxxxx.jpg?oh=bcxxxxxxxxxxx431ce&oe=xxxx4xxx3',
providerId: 'facebook.com',
uid: 'xxxxx725xxxxxx80' } ]
In my index.js file i've set this as
const providerData = event.data.providerData;
This always confuses me and i've read about it a lot.
These are my questions:
Is this a javascript object? Or a JSON object? Or a JSON array?
Does this need to be parsed? eg. JSON.parse(event.data.providerData)? What is JSON.parse actually doing?
To get access to the uid I have tried:
providerData[3]
providerData.uid
providerData["uid"]
providerData['uid']
JSON.parse(providerData) - and then all the above again
var obj = JSON.parse(providerData);
console.log( obj.uid );
I know there are plenty of posts out there re: similar topics and I think i've read a lot of them.
Thanks.
It's an array containing a JSON object at index 0.
The javascript interpreter is automatically parsing Valid JSON as a Javascript object.
Knowing that, you can now access directly the properties of your object like this:
providerData[0].displayName
providerData[0].photoURL
providerData[0].providerId
providerData[0].uid // <-- Your use case

Firebase pushing array - Javascript

I am using Firebase to store information for a workout application.
I user adds a workout name and then I push it to the database. I can continue pushing these but my issue is that it does not seem to be pushing as an array just an object. See the screen shots below...
As you can see in the console log picture the workouts property is an object not an array like I expect.
The code I'm using to push it:
let newWorkout = {
title: 'title',
exercises: [{
name: 'pulldownsnsn',
sets: 4
}]}
let ref = firebase.database().ref("/userProfile/"+this.userId);
ref.child("workouts").push(newWorkout);
The Firebase Database stores lists of data in a different format, to cater for the multi-user and offline aspects of modern web. The -K... are called push IDs and are the expected behavior when you call push() on a database reference.
See this blog post on how Firebase handles arrays, this blog post on the format of those keys, and the Firebase documentation on adding data to lists.
Arrays are handy, but they are a distributed database nightmare for one simple reason: index element identification is not reliable when elements get pushed or deleted. Firebase database instead uses keys for element identification:
// javascript object
['hello', 'world']
// database object
{ -PKQdFz22Yu: 'hello', -VxzzHd1Umr: 'world' }
It gets tricky when using push(), because it does not actually behaves like a normal push, but rather as a key generation followed by object modification.
Example usage
firebase.database().ref('/uri/to/list').push(
newElement,
err => console.log(err ? 'error while pushing' : 'successful push')
)
Heres an example from firebase documentation:
const admin = require('firebase-admin');
// ...
const washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
const unionRes = await washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
const removeRes = await washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
More info on this firebase documentation.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Categories

Resources