Is there any way to stop overwriting the json file? - javascript

actually this code works as expected but, if I do input a different userId, it still do overwrite the existing user (not the file) and the ideia was to add another one
const user = userId;
const userObj = {[user]:valueX};
words.users = userObj;
fs.writeFileSync('words.json', JSON.stringify(words,null,2), finished);
input comes from here (readline-sync)
let userId = input.question('Enter yourUserId: ');
and yes i'm reading the file first
let words = JSON.parse(fs.readFileSync('words.json'));

const userObj = {[user]:valueX};
words.users = userObj;
The object you assign to words.users needs to include all the existing users and not just your new one.
const userObj = {...words.users, [user]:valueX };

From your code it looks like words.users is an object and in that case
if(!words.users) words.users = {}; // Make sure the words users are created
words.users[user] = valueX;
This would give you an words.users object that look like this
{user1: valueX1, user2: valueX2}
And you could access like this
console.log(words.users[user1]); // valueX1

Related

Setting and modifying array and pushing to localStorage creates nested array

I have a function that takes a string from a search field during runtime, and stores it to localstorage. Since we want to store all search strings from the end user to record it, we need to get the current data from localstorage, and add the latest search string.
Here is my code:
const setDatatoLocalStorag = (searchQuery: string) => {
let searchHistory = localStorage.getItem("searchHistory");
let searchQueryArr = [];
if (searchHistory) {
JSON.parse(searchHistory);
searchQueryArr.push(searchQuery, searchHistory);
} else {
searchQueryArr.push(searchQuery);
}
localStorage.setItem("searchHistory", JSON.stringify(searchQueryArr));
}
Lets assume we run the function twice, with the searchQuery "dog" and "cat". This is how it will look like in localstorage:
["cat","[\"dog\"]"]
I believe localstorage will get the item as string "[myData]" which will cause the error. How to properly handle this?
I have tried to follow How to store an array of objects in Local Storage? withous success.
The problem is you aren't assigning JSON.parse(searchHistory); to a variable. I think what you want to do is this:
var searchQueryArr = ['dog'];
localStorage.setItem("searchHistory", JSON.stringify(searchQueryArr));
var searchHistory = JSON.parse(localStorage.getItem("searchHistory") || '[]');
console.log(searchQueryArr, searchHistory);
Note I wasn't able to get this to work with the inline editor, but I did try it on a real server and it worked.
Make a setter/getter pair that hide the encoding/unencoding. Then add a higher-level push that does a get and a set...
// const pretend local storage, keys => strings
const myLocalStorage = {}
function mySetItem(key, value) {
// use the actual local storage setItem() here
myLocalStorage[key] = JSON.stringify(value);
}
function myGetItem(key) {
// use the actual local storage getItem() here
return JSON.parse(myLocalStorage[key]);
}
function myPush(key, value) {
let current = myGetItem(key);
current.push(value)
mySetItem(key, current)
}
// test
const key = 'myKey'
mySetItem(key, []);
myPush(key, { message: 'hello' })
myPush(key, { message: 'dolly' })
console.log(myGetItem(key))

How do I check if an IndexedDB database already exists?

I'm working on restaurant website (client-side project) and facing this problem, I want to make an admin page will show me all the orders placed by the customers and the way I choose that to save the order details in local storage then save it in this indexedDB then display the (the orders) at the admin page so I made this code and it work all good I guess to save the order and all customer details
document.getElementById('submittheorder').onclick = function() {
let i = 0;
const versionDB = 1;
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open("CustomersOrders", versionDB);
open.onupgradeneeded = function() {
let db = open.result;
let store = db.createObjectStore("OrdersTable", {
keyPath: "id"
});
let index = store.createIndex("CIndex", ["FullName", "Order", "House", "Road", "Block"]);
};
open.onsuccess = function() {
let db = open.result;
let tx = db.transaction("OrdersTable", "readwrite");
let store = tx.objectStore("OrdersTable");
let index = store.index("CIndex");
store.put({
FullName: (sessionStorage.getItem("Cfullname")),
Order: (sessionStorage.getItem("order")),
House: (sessionStorage.getItem("CHouse")),
Road: (sessionStorage.getItem("CRoad")),
Block: (sessionStorage.getItem("CBlock"))
});
tx.oncomplete = function() {
db.close();
location.href = "Thanks.html";
};
}
}
Now the problem is I want to retrieve all the orders and the details for each object to the admin page
the second problem is that i want to check if the database already exist then insert new object not make a new database and save only one object, in a nutshell i want only one database to make and next times save the orders at that database.
Thank you :)
You can place this logic in the function that handles an upgrade event. There are essentially two ways. You can check if object stores and indices exist, using for example db.objectStoreNames.contains(), or you can compare versions by accessing the version properties from the database object or the event object.
For example, you would want to only create an object store if it did not already exist. If it does not already exists, then you know this is when your database is created.

Delete a array element from a Firestore database

I'm trying to delete an element from an array in a Firestore document. However, none of the approaches I tried had worked so far. My last attempt was like this:
const ref = firestore().collection('events').doc(extraid);
ref.get().then(document => {
const thing = document.data();
const rejected = thing.rejected || [];
const interested = thing.interested || [];
const fieldIndex = interested.findIndex(obj => obj.interestedId === sender);
const fieldToDelete = interested[fieldIndex];
firebase.firestore.FieldValue(fieldToDelete);
firebase.firestore.FieldValue.delete(fieldToDelete);
});
How can I delete an element from an array in a Firestore document?
You will have to update() the modified array field back to the document as suggested by the documentation. Calling FieldValue.delete() isn't enough - that just creates a FieldValue token that you can pass to update() to make the change. It will look something like this:
ref.update('interested', FieldValue.delete(fieldToDelete))

Store multiple channel IDs in a JSON file

I am making a bot using Discord.js and it only needs to track messages in a certain channel, which I currently have this hard-coded for testing purposes.
var { channelID } = require(`./config.json`);
bot.on("message", async (message) => {
const args = message.content.split(/ +/g);
if (message.channel.id === channelID) {
// ...
}
});
I would like for it to store multiple IDs in a JSON file and to have a [p]setchannel command, that would allow me to add one.
I tried this guide, with no luck.
What you probably want to do is store an array of IDs so that you can retrieve them later.
You should have a channelIDs property in your JSON file set to an empty array. Inside your code you can fetch it like this:
const { channelIDs } = require('./config.json') // Now it's an empty array: []
When you want to update this array you should update your local one first, and then you can update the config file: to do that you can use fs.writeFileSync() in combination with JSON.stringify().
const fs = require('fs')
function addChannelID(id) {
channelIDs.push(id) // Push the new ID to the array
let newConfigObj = { // Create the new object...
...require('./config.json'), // ...by taking all the current values...
channelIDs // ...and updating channelIDs
}
// Create the new string for the file so that it's not too difficult to read
let newFileString = JSON.stringify(newConfigObj, null, 2)
fs.writeFileSync('./config.json', newFileString) // Update the file
}
Once you set this function you can add a new ID every time you want, just by calling addChannelID('channel_id').
To check whether the channel the message is coming from should be considered you can use this:
if (channelIDs.includes(message.channel.id)) {
// OK
}

JavaScript send out an alert to prompt and edit array?

//global variable
var memArray =[];
//object
function member(id, password){
this.id = id;
this.pwd = password
}
var memObj1=new member("m001","123");
memArray.push(memObj1);
How do I send out an alert to prompt and edit each object that is push to memArray?
if you want to customize it try to use your own modals instead of window.prompt and just display values with editable text fields, on submit capture those values and change them in array respectively.
var memArray = [];
//object
function member(id, password) {
this.id = id;
this.pwd = password
}
var memObj1 = new member("m001", "123");
var memObj2 = new member("m002", "123");
var memObj3 = new member("m031", "123");
memArray.push(memObj1);
memArray.push(memObj2);
memArray.push(memObj3);
memArray.forEach((val, ind) => {
memArray[ind] = JSON.parse(window.prompt("want to edit values?", JSON.stringify(memArray[ind])));
});
console.log(memArray)
Pavan's answer is good, but to make this testable in automated tests:
// I would name these fields in your API
// by making the constructor take an object.
// Capitalise the name to signal that it can be newed
function Member({id, password}) {
this.id = id;
this.pwd = password
}
// Name the array for what it is
const members = [
new Member({id: "m001", password: "123"}),
new Member({id: "m002", password: "123"}),
new Member({id: "m031", password: "123"})
]
const editInBrowserFn = member => JSON.parse(window.prompt("want to edit values?", JSON.stringify(member)));
const updateMembers = editFn => array => array.map(editFn)
// To get an update
const updatedMembers = updateMembers(editInBrowserFn)(members)
console.log(updatedMembers)
// You can now test it by making an testing editFn that doesn't need user interaction
const testEditFn = m => new Member({id: m.id, password: 'test'})
const testMembers = updateMembers(testEditFn)(members)
console.log(testMembers)
See this article for an in-depth explanation of this approach.
To do it this way, you will need to take it out of the global scope. That is a good discipline to develop. As a first step you could make an object in global scope that holds the latest member list:
const Members = (() => {
let _members = []
return {
setMembers: members => _members = [...members],
getMembers: () => [..._members]
}
})()
Now the way to update the members is like this:
const updateFn = updateMembers(editInBrowser)
function updatePasswords() {
const members = Members.getMembers()
Members.setMembers(updateFn(members))
}
Nothing can accidentally delete or mutate the members array now, so that bug surface area is eliminated.
This is how React setState is designed. It's inspired by functional programming ideas and immutability.
You probably want to be able to update just one member, so:
const Members = (() => {
let _members = []
return {
setMembers: members => _members = [...members],
getMembers: () => [..._members],
updateMember: updated =>
this.members = _members.map(m =>
m.id === updated.id ? updated : m)
}
})()
Now all your array mutation is in one single place, and you only have to make it bug-free there. Otherwise, your global state is exposed and you have to fix bugs everywhere related to it. Without this, all your calling functions are responsibly for correctly managing the global state of the application. Complex.
Crystallise the complexity in one place.
I wrote an article and a complete implementation of the store (in 40 lines of code) here.
As far as I concern, alerts are just models on the browser to provide informative feedback to a particular user on his actions. Therefore, I think it is required to use either a dialog model or a form to edit the objects in the memArray.

Categories

Resources