I am making a game and am working on the accounts. When i have JSON stringify the object and save it to a file, it sometimes (occasionally and at random) writes:
{"example#domain.cm":{"email":"example#domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >}< "example#domain.com":{"email":"example#domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
when i am expecting:
{"example#domain.cm":{"email":"example#domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >,< "example#domain.com":{"email":"example#domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
My Code:
const fs = require('fs');
const { v4: newUuid } = require('uuid');
function save() {
fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {});
}
class User {
static USERS = {};
constructor(email, password, token = newUuid()) {
this.email = email;
this.password = password;
this.token = token;
User.USERS[email] = this;
save();
}
}
What is going on?
EDIT
I am using nodemon. Whenever i save a file (except users.json), it automatically stops and starts it. I am also using express because this script is for the server part. (This is a private project, not looking to make it perfect, just learn)
Thank you, #jabaa
they have pointed out a warning that using fs.writeFile() multiple times without waiting for the callback is unsafe. Here is the solution:
var CAN_SAVE = true;
var PENDING_SAVE = false;
function save() {
if (!CAN_SAVE) {
PENDING_SAVE = true;
return;
}
PENDING_SAVE = false;
CAN_SAVE = false;
fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {
CAN_SAVE = true;
if (PENDING_SAVE) save();
});
}
Another solution is to use fs.writeFileSync(), which might actually be better in my case... (Thank you, #Steven Spungin)
Related
I've never created a Javascript module/library before so this is a bit new to me so apologizes for my lack of knowing what to google.
I'm creating a library that will hold information from a URL that is provided by a user. I want to parse the URL's path (the part that comes after the domain) as well as retain a header value that's provided by the URL's response.
It's basic but here's what I have so far:
function Link(someURL) {
this.url = someURL;
this.urlPath = "";
this.uuid = "";
this.getPath = function (someURL) {
// do regexp parsing and return everything after the domain
};
this.getUUID = function (someURL) {
// fetch the URL and return what is in the response's "uuid" header
}
}
Ideally, I'd the module to automatically get all the information upon construction:
var foo = new Link("http://httpbin.org/response-headers?uuid=36d09ff2-4b27-411a-9155-e82210a100c3")
console.log(foo.urlPath); // should return "uuid"
console.log(foo.uuid); // should return the contents in the "uuid" header in the response
How do I ensure the this.urlPath and this.uuid properties get initialized along with this.url? Ideally, I'd only fetch the URL once (to prevent rate limiting by the target server).
After a lot of trial and error, I ended up doing something more like this:
class Link {
constructor (url_in) {
const re = RegExp("^https://somedomain.com\/(.*)$");
this.url = re[0];
this.linkPath = re[1];
}
async getUUID() {
const res = await fetch("https://fakedomain.com/getUUID?secret=" + this.linkPath);
this.uuid = res.uuid;
}
async getJSON() {
const res = await fetch("https://fakedomain.com/getJSON?uuid=" + this.uuid);
this.json = await res.json();
}
async initialize() {
await this.getUUID();
await this.getJSON();
}
}
const someLinkData = new Link("https://reallydumbdomain.com/2020/10/4/blog");
someLinkData.initialize()
.then(function() {
console.log(this.json); // this now works
});
I think a future iteration of this will require me to send a promise with the initialize function but for now, this works.
I hope everyone is safe and healthy given the current situation.
I have a question in regards to a project with google apps script. I have a web app and I have been able to figure out routing with doGet() using links etc.
//global variables
const sheetId = "foo";
const Route = {};
Route.path = function(route, callback){
Route[route] = callback;
}
function doGet(e){
Route.path("newAccountForm",loadNewForm);
Route.path("updateBrandForm", loadUpdateForm);
if(Route[e.parameters.v]) {
return Route[e.parameters.v]();
} else {
return render("home")
}
};
function loadNewForm() {
const sheetActive = SpreadsheetApp.openById(sheetId);
const mySheet = sheetActive.getSheetByName("Sheet1");
const title = "title";
const index = "index";
return render("addNewAccount",{title: title, index: index});
}
function loadUpdateForm () {
const sheetActive = SpreadsheetApp.openById(sheetId);
const mySheet = sheetActive.getSheetByName("Sheet1");
return render("updateBrand");
}
function render(file,argsObject) {
const tmp = HtmlService.createTemplateFromFile(file);
if(argsObject) {
const keys = Object.keys(argsObject);
keys.forEach(function(key){
tmp[key] = argsObject[key];
})
} // END IF
return tmp.evaluate();
}
The links..
Add New Brand
Update Exisiting Brand
Analytics / Reports
Now I am a bit stuck on handling responses and errors. I have tried using doPost() which works to render a new HTML page. My problem is I am unsure how to tell if the request was successful in the doPost. Is there a way to check that? I can get all the parameters through the event object but not a status.
<form id="myForm" onsubmit="handleNewAccountFormSubmit(this);" method="post" action="<?= ScriptApp.getService().getUrl(); ?>">
I have also been trying to handle it with the included .withFailureHandler() but am unsure how to get it to fire or if it is possible to call back a function from my .GS
I have tried also having the onFail() function outside the FormSubmit function.
function handleNewAccountFormSubmit(formObject) {
google.script.run.withFailureHandler(onFail).withSuccessHandler().processNewAccountForm(formObject);
function onFail(error) {
Logger.log(error)
console.log(error)
return google.script.run.onError();
}
}
I basically want to show if the function ran successfully for user experience but am unsure of best practise or how or even if it is possible(I am sure it is!)
I look forward to any ideas, corrections, and if something is unclear I will do my best to provide more info.
Thanks again.
Use success or failure handlers to alert the user:
function handleNewAccountFormSubmit(formObject) {
alert("Please wait..!")
google.script.run
.withFailureHandler(e => {
console.error(e.message);
alert("Unexpected error! Contact support!")
})
.withSuccessHandler(e => alert("Form submitted successfully!"))
.processNewAccountForm(formObject);
}
I'm quite new to working with telegram bots, but I managed well so far with some basic bot. Now I want to improve a bit things and let my site "feed" the bot.
This is the scenario
I have a Google spreadsheet that make some calculation and then sends a message to the bot with the classic URL. Something like this...
var optionsUG = {
'method' : 'post',
'payload' : formDataUG,
'muteHttpExceptions':true
};
var optionsLG = {
'method' : 'post',
'payload' : formDataLG
};
//SpreadsheetApp.getUi().alert('UrlFetchApp options ['+options+"]");
//UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage?chat_id='+channelNumber+'&text='+text);
var result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage',optionsUG);
Utilities.sleep(5 * 1000);
result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage',optionsLG);
now I would like to make something like but, instead of sendMessage I would like to call a method of my bot
I use JavaScript Telegraf framework ATM, but I can change is not a problem.
I want to achieve something like:
var result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/register',optionsUG);
here is the bot currently configured
const serverPath = "/home/bots/PlatoonAdvisor/telegram";
const commands = require(serverPath+'/package/modules/commands.js');
const config = require(serverPath+'/config.json');
var helpText = require(serverPath+'/package/help.txt');
const token = config.TELEGRAM_BOT_SECRET;
const Telegraf = require('telegraf');
const bot = new Telegraf(token);
const REGISTER_COM = 'register';
const HELP_COM = 'help';
const REQUIREMENTS_COM = 'requirements';
const CAHT_ID_COM = 'chatid';
const getCommandParameters = function (text, command) {
var reg = "/\/"+command+" (.*)/g";
var arr = text.match(reg);
return arr;
}
/*
bot.on('text', message=> {
return message.reply('I am Grooth');
})
*/
bot.command(HELP_COM, ctx=> {
return ctx.reply(helpText);
});
bot.command(REGISTER_COM, ctx=> {
var replyMsg;
var param = getCommandParameters(ctx.message.text, REGISTER_COM);
var player_name, allycode;
if (param != null) {
try {
var params = param.split(",");
if (params.length < 2) {
replyMsg = "Missing parameters, try /help if you need help :)";
throw replyMsg;
}
player_name = params[1];
allycode = params[0];
var channel = ctx.chat.id;
commands.registerTPlayer(player_name, allycode, channel);
replyMsg = "Successfully registered player ${player_name} with allycode ${allycode}!"
} catch (ex) {
console.log (ex);
}
}
return ctx.reply(replyMsg);
});
bot.command(REQUIREMENTS_COM, ctx=> {
var param = getCommandParameters(ctx.message.text, REQUIREMENTS_COM);
var params = param.split(",");
var json = ctx.chat.id;
return ctx.reply(json);
});
bot.command(CAHT_ID_COM, ctx=> {
var id = ctx.chat.id;
var msg = "The chat id requested is ${id}";
return ctx.reply(msg);
});
bot.startPolling();
is that even possible? I'm looking over the internet for a while now and was not able to find any clue about.
EDIT: Doing some more digging I found webhooks to send content to a web server when something happens in the bot but not vice versa. I'm getting frustrated.
My goal is to update the local database with information the spreadsheet have but the bot still don't so users can later ask to the bot to retrieve those information.
I mean I could make an ajax call if it were a real web server, but it is just a spreadsheet which doesn't act as a server.
Ok I forgot to answer this question with the solution I found.
there is no way indeed to call a specific function of the bot from the outside because it is not a real function, it is a parsed string that a user type and the bot interpret as a command.
So I had to be creative and expose a RestServer from the bot itself (the NodeJS express library did the trick) which I was then able to call from the script.
Here an handy guide for Express.js
This is my solution which is working great now.
I have User and File models in Sequlize. User can have several files.
I have association
db.User.hasMany(db.File, {as: 'Files', foreignKey: 'userId', constraints: false});
I want to init User object with several Files and save it to database.
I wrote next code:
var files = [];
var file1 = models.File.build();
file1.name = "JPEG";
file1.save().then(function () {
});
files.push(file1);
var file2 = models.File.build();
file2.name = "PNG";
file2.save().then(function () {
});
files.push(file2);
var newUser = models.User.build();
newUser.email = email;
newUser.save().then(function (usr) {
files.forEach(function (item) {
newUser.addFile(item);
});
});
But I found a bug, sometimes several files were not associated with the user.
I found(in nodejs logs) commands(update) for setting foreign keys for these files.
But commands were not executed. Foreign keys(userId) of several files were empty.
I think the problem is in asynchronous queries.
How to organize code structure to avoid this bug?
The problem is exactly what you think it is, the async code.
You need to move the functions inside of the callbacks otherwise the code gets run before the file is created.
JavaScript doesn't wait before moving on to the next line so it'll run the next line whether its done or not. It has no sense of waiting before moving.
So you're basically adding something that doesn't yet exist because it doesn't wait for the file to be saved before moving on.
This would work though, just moving the code inside of the then callbacks:
var files = [];
var file1 = models.File.build();
file1.name = "JPEG";
file1.save().then(function () {
files.push(file1);
var file2 = models.File.build();
file2.name = "PNG";
file2.save().then(function () {
files.push(file2);
var newUser = models.User.build();
newUser.email = email;
newUser.save().then(function (usr) {
files.forEach(function (item) {
newUser.addFile(item);
});
});
});
});
But that's messy. Instead you can chain promises like this:
var files = [];
var file1 = models.File.build();
file1.name = "JPEG";
file1.save()
.then(function(file1) {
files.push(file1);
var file2 = models.File.build();
file2.name = "PNG";
return file2.save();
})
.then(function(file2) {
files.push(file2);
var newUser = models.User.build();
newUser.email = email;
return newUser.save();
})
.then(function(newUser) {
files.forEach(function(item) {
newUser.addFile(item);
});
});
Now that's a bit cleaner but still a bit messy and also a bit confusing. So you can use generator functions instead like this:
var co = require('co');
co(function*() {
var files = [];
var file1 = models.File.build();
file1.name = "JPEG";
yield file1.save();
files.push(file1);
var file2 = models.File.build();
file2.name = "PNG";
yield file2.save();
files.push(file2);
var newUser = models.User.build();
newUser.email = email;
newUser.save();
files.forEach(function(item) {
newUser.addFile(item);
});
});
Now that's much better.
Look closely and you see what's happening. co accepts a generator function which is basically a regular function with asterisks *. This is a special functions which adds yield expression support.
yield expressions basically wait for the then() callback to be called before moving on and if the then callback has a argument then it'll return it as well.
So you can do something like:
var gif = yield models.File.create({
name: 'gif'
});
instead of:
models.File.create({
name: 'gif'
}).then(function(gif) {
});
You have to use a small node module called co for this though just npm install --save co
I am writing a Javascript API library that provides consumers with an interface that enables them to interact with our backend web services. It is envisioned that a consumer will be writing a javascript client web application that draws heavily on the API provided for by the library.
I have come up with this "pattern" for maintaining state and making functionality "available" as certain criteria are met (for example, an authenticated user is logged in client-side).
Is this an appropriate way to achieve that end? Or am I unwittingly breaking some convention or best practice that will bite me later on?
// file: clientApi.js (library)
ClientObject = function () {
this.objectname = "a client class";
}
ClientObject.prototype.loginUser = function(name) {
this.loggedin = true;
if (typeof this.User === 'undefined') {
this.User = new ClientObject.User(name);
}
}
ClientObject.User = function (name) {
this.username = name;
}
ClientObject.User.prototype.getProfile = function() {
return 'user profile';
}
// file: app.js (consuming application)
var testClient = new ClientObject();
console.log('testClient.User = ' + (typeof testClient.User)); // should not exist
testClient.loginUser('Bob'); // should login 'bob'
console.log('testClient.User = ' + (typeof testClient.User)); // should exist
console.log(testClient.User.username); // bob
testClient.loginUser('Tom'); // should not do anything
console.log(testClient.User.username); // bob still
console.log(testClient.User.getProfile()); // tada, new functionality available
My question: is this approach valid? Is there a pattern that I'm touching on that might offer a better explanation or method of achieving my end goal?
I asked a similar question here with a bunch of other ones, unfortunately the above code was somewhat lost in the noise: Javascript: creation of object from an already instantiated object versus the prototype
Your API should have some secrets. That's why do not make all your functions public. Let's analyze some parts of your code:
testClient.loginUser('Tom'); // should not do anything
But your implementation allows client to do next:
testClient.User = new ClientObject.User(name);
Now user will be changed to "Tom".
Let's change your clientApi.js code, using revealing prototype pattern:
ClientObject = function () {
this.objectname = "a client class";
this.username;
this.User;
this.loggedin;
}
ClientObject.prototype = function() {
var loginUser = function(name) {
this.loggedin = true;
if (typeof this.User === 'undefined') {
this.User = new User(name);
}
};
var User = function (name) {
this.username = name;
};
User.prototype.getProfile = function() {
return 'user profile';
};
return {
loginUser : loginUser
}
}()
Now client cannot change logged in User like in first version of the library. You can use some variations, but that's the idea.