JSON Variable for a nodejs script - node.js

im searching for an idea to fix my problem. First of all, there is a server.exe software, that can load some stuff. But if i change something, it needs a restart, but not, if i use a json file to store account names. Look:
const allowedPlayers =
[
"Socialclubuser1",
"Socialclubuser2",
"Socialclubuser3"
]
mp.events.add("playerJoin", (player) => {
if (!allowedPlayers.includes(player.socialClub)) {
player.notify('Youre not whitelisted!');
}
});
mp.events.add("playerJoin", (player) => {
if (!allowedPlayers.includes(player.socialClub)) {
player.kick('Youre not whitelisted!');
}
});
i would use account.json, and insert there the stuff but how?
greetings

Create an account.json file and require it using require on start.
// account.json
// ["Socialclubuser1", "Socialclubuser2", "Socialclubuser3"]
const allowedPlayers = require("./account.json");
// rest of the code
mp.events.add("playerJoin", player => {
if (allowedPlayers.indexOf(player.socialClub) === -1) {
player.notify("Youre not whitelisted!");
player.kick("Youre not whitelisted!");
}
});

Related

Correct way to organise this process in Node

I need some advice on how to structure this function as at the moment it is not happening in the correct order due to node being asynchronous.
This is the flow I want to achieve; I don't need help with the code itself but with the order to achieve the end results and any suggestions on how to make it efficient
Node routes a GET request to my controller.
Controller reads a .csv file on local system and opens a read stream using fs module
Then use csv-parse module to convert that to an array line by line (many 100,000's of lines)
Start a try/catch block
With the current row from the csv, take a value and try to find it in a MongoDB
If found, take the ID and store the line from the CSV and this id as a foreign ID in a separate database
If not found, create an entry into the DB and take the new ID and then do 6.
Print out to terminal the row number being worked on (ideally at some point I would like to be able to send this value to the page and have it update like a progress bar as the rows are completed)
Here is a small part of the code structure that I am currently using;
const fs = require('fs');
const parse = require('csv-parse');
function addDataOne(req, id) {
const modelOneInstance = new InstanceOne({ ...code });
const resultOne = modelOneInstance.save();
return resultOne;
}
function addDataTwo(req, id) {
const modelTwoInstance = new InstanceTwo({ ...code });
const resultTwo = modelTwoInstance.save();
return resultTwo;
}
exports.add_data = (req, res) => {
const fileSys = 'public/data/';
const parsedData = [];
let i = 0;
fs.createReadStream(`${fileSys}${req.query.file}`)
.pipe(parse({}))
.on('data', (dataRow) => {
let RowObj = {
one: dataRow[0],
two: dataRow[1],
three: dataRow[2],
etc,
etc
};
try {
ModelOne.find(
{ propertyone: RowObj.one, propertytwo: RowObj.two },
'_id, foreign_id'
).exec((err, searchProp) => {
if (err) {
console.log(err);
} else {
if (searchProp.length > 1) {
console.log('too many returned from find function');
}
if (searchProp.length === 1) {
addDataOne(RowObj, searchProp[0]).then((result) => {
searchProp[0].foreign_id.push(result._id);
searchProp[0].save();
});
}
if (searchProp.length === 0) {
let resultAddProp = null;
addDataTwo(RowObj).then((result) => {
resultAddProp = result;
addDataOne(req, resultAddProp._id).then((result) => {
resultAddProp.foreign_id.push(result._id);
resultAddProp.save();
});
});
}
}
});
} catch (error) {
console.log(error);
}
i++;
let iString = i.toString();
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(iString);
})
.on('end', () => {
res.send('added');
});
};
I have tried to make the functions use async/await but it seems to conflict with the fs.openReadStream or csv parse functionality, probably due to my inexperience and lack of correct use of code...
I appreciate that this is a long question about the fundamentals of the code but just some tips/advice/pointers on how to get this going would be appreciated. I had it working when the data was sent one at a time via a post request from postman but can't implement the next stage which is to read from the csv file which contains many records
First of all you can make the following checks into one query:
if (searchProp.length === 1) {
if (searchProp.length === 0) {
Use upsert option in mongodb findOneAndUpdate query to update or upsert.
Secondly don't do this in main thread. Use a queue mechanism it will be much more efficient.
Queue which I personally use is Bull Queue.
https://github.com/OptimalBits/bull#basic-usage
This also provides the functionality you need of showing progress.
Also regarding using Async Await with ReadStream, a lot of example can be found on net such as : https://humanwhocodes.com/snippets/2019/05/nodejs-read-stream-promise/

Compare API response against itself

I am trying to:
Poll a public API every 5 seconds
Store the resulting JSON in a variable
Store the next query to this same API in a second variable
Compare the first variable to the second
Print the second variable if it is different from the first
Else: Print the phrase: 'The objects are the same' if they haven't changed
Unfortunately, the comparison part appears to fail. I am realizing that this implementation is probably lacking the appropriate variable scoping but I can't put my finger on it. Any advice would be highly appreciated.
data: {
chatters: {
viewers: {
},
},
},
};
//prints out pretty JSON
function prettyJSON(obj) {
console.log(JSON.stringify(obj, null, 2));
}
// Gets Users from Twitch API endpoint via axios request
const getUsers = async () => {
try {
return await axios.get("http://tmi.twitch.tv/group/user/sixteenbitninja/chatters");
} catch (error) {
console.error(error);
}
};
//Intended to display
const displayViewers = async (previousResponse) => {
const usersInChannel = await getUsers();
if (usersInChannel.data.chatters.viewers === previousResponse){
console.log("The objects are the same");
} else {
if (usersInChannel.data.chatters) {
prettyJSON(usersInChannel.data.chatters.viewers);
const previousResponse = usersInChannel.data.chatters.viewers;
console.log(previousResponse);
intervalFunction(previousResponse);
}
}
};
// polls display function every 5 seconds
const interval = setInterval(function () {
// Calls Display Function
displayViewers()
}, 5000);```
The issue is that you are using equality operator === on objects. two objects are equal if they have the same reference. While you want to know if they are identical. Check this:
console.log({} === {})
For your usecase you might want to store stringified version of the previousResponse and compare it with stringified version of the new object (usersInChannel.data.chatters.viewers) like:
console.log(JSON.stringify({}) === JSON.stringify({}))
Note: There can be issues with this approach too, if the order of property changes in the response. In which case, you'd have to check individual properties within the response objects.
May be you can use npm packages like following
https://www.npmjs.com/package/#radarlabs/api-diff

cy.readFile results in timeout?

I am trying to read an JSON file that I have just written with another test in the same cypress project. However when it tries to read the file it times out after 4000 milliseconds.
Has anyone experienced this before? How could I solve it?
I have tried increasing the time out by giving it a settings object but that doesn't increase the time out time. I thought it might be a file permissions issue but that doesn't seem to be it either.
I am running on Mac but tried the same project on Windows with the same result.
before('grab generated user data', function (){
let data = cy.readFile("Generated User/Cypress test 131.json", {log:true, timeout: 180000});
}
I expect it to just give back the parsed JSON object. As it says in the Cypress docs. (https://docs.cypress.io/api/commands/readfile.html#Syntax)
1.Your file should be in the project directory where cypress.json file is present.
2.Your file name should be Cypresstest131.json or Cypress-test-131.json
before('grab generated user data', function (){
let data = cy.readFile("Cypresstest131.json", {log:true, timeout: 4000});
data.its('name').should('eq', 'Eliza')
})
or
before('grab generated user data', function (){
cy.readFile("Cypress-test-131.json", {log:true, timeout: 4000}).its('name').should('eq', 'Eliza')
})
Hope this help you
I ended up creating a data.json with cy.createFileSync(). When I want to read the file instead of using cypresses cy.readFile() function I created a cypress task that uses the fs library to read the file.
I am leaving you with the code snipped of the task I used to read the file.
const fs = require('fs');
const request = require('request');
module.exports = (on, config) => {
on('task', {
// Cypress task to get the last ID
getLastId: () => {
// Make a promise to tell Cypress to wait for this task to complete
return new Promise((resolve) => {
fs.readFile("data.json", 'utf8', (err, data) => {
if (data !== null && data !== undefined) {
data = JSON.parse(data);
if (data.hasOwnProperty('last_id')) {
resolve(data.last_id);
} else {
resolve("Missing last_id");
}
} else {
resolve(err);
}
});
});
}
Calling this function would be as simple as
let id = 0;
before('grab generated user data', function (){
cy.task('getLastId').then((newID)=>{
id = newID;
});
});

validating lack of parameters in feathresjs

I've read the feathersjs documentation, but after doing a find method in a service I realized that if I don't give any query parameters, the service returns all the data, which is something I don't want. How can I define a hook to validate that there are at least one query parameter in order to proceed; otherwise, send back a 403 error (bad request).?
I have doubts in the way to do it I tried this:
app.service('myService')
.before(function(hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
})
.find({
query: {
$sort: {
year: -1
}
}
})
And I tried in hook file on hooks this (that seemed really desperate & | stupid):
function noparams (hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
}
module.exports = {
before: {
find: [ noparams(this) ] ...
}
}
but it does not compile (I don't know what to send as a parameter there), and the examples seemed to be for pre 2.0 version and on top of that the code I found seemed to be in the app.js, but all is differently coded using feathers-cli, so the examples, even in the book, aren't against the scaffolded version, which is confusing because they shows the code in a different file were should be.
Thanks.
I ended using a before hook, so the code used is this:
const errors = require('feathers-errors');
module.exports = function () {
return function (hook) {
if(hook.method === 'find'){
if (hook.params.query.name === undefined || hook.params.query.length == 0){
throw new errors.BadRequest('Invalid Parameters');
}else{
return hook;
}
}
}
};
If have used feathers-cli to generate your application (feathers v2.x) you don't need to do anything else. If is an earlier version you maybe need to add the Express error handler and it is pointed out in the documentation|Errors|REST.
Thanks.

How to make conditional get in Ionic Storage

I'm developing Ionic2 App which is running on android phone.
It does not need remote db. so I decided to use local storage 'Store'.
I found some article and made some improvements like below.
I succeded to get all values but I want to get something on some condition like 'where' statement in SQL. (getWorksOn(someDate){...})
I searched and read more than 30 top articles but I couldn't find the way.
Please let me know if there's any way.
// work-service.ts
addWork(work){
this.storage.get('myWorks').then((data) => {
if(data != null){
data.push(work);
this.storage.set('myWorks', data);
} else {
let tempWorks = [];
tempWorks.push(work);
this.storage.set('myWorks', tempWorks);
}
});
}
getWorks(){
return this.storage.get('myWorks');
}
getWorksOn(someDate){
// I want to return works that worked on someDate
// Is there any way to get some value conditionally
return this.storage.get('myWorks');
}
// work-list.ts
works:any;
...
ngOnInit(){
this.workService.getWorks().then((data)=>{
this.works = data;
});
}
If you're using Lodash then you can do it as shown below.
Note: You cannot do this inside the local storage.You have to do something like this then...
getWorksOn(someDate){
this.storage.get('myWorks').then((val) => {
let myworkArray = val; //firstly, fetched the data
let myworkArray2= _.filter(myworkArray , { 'date': someDate});//after that filter out according to your condition
});
}
OP's Feedbackusing map and filter function of array
this.workService.getWorks().then((works) => { this.works = works.filter(work
=> work.dateStr === this.dateStr ); });

Resources