NodeJS using single quotes instead of double quotes in object [Answered] - node.js

[Answered by: Loulou BadWeed]
Hi #NickP. , did you stringify/serialize your payload before passing
it in the fetch body ? Does not seem the case from your example and I
don't think fetch does that for you. Try JSON.stringify(config) in the
body argument of the fetch function
I have a "small" problem.
I can't figure out, why nodejs uses single quotes for the string value instead of double quotes...
My Code
let config = {}
config["active"] = 1
config["domain"] = req.body.domain
config["mailboxes"] = req.body.mailboxes
config["defquota"] = req.body.defquota
config["maxquota"] = req.body.maxquota
config["quota"] = req.body.quota
config["restart_sogo"] = 10
console.log(req.body.domain)
console.log(config)
What I input:
{
"domain": "domain.tld",
"mailboxes": 10,
"defquota": 512,
"maxquota": 1024,
"quota": 10240
}
What I get:
{
active: 1,
domain: 'domain.tld',
mailboxes: 10,
defquota: 512,
maxquota: 1024,
quota: 10240,
restart_sogo: 10
}
The problem I have with this, is that the mailcow api doesn't like single quotes in the request body. :) Does anyone know, why this happens and can help me?
I tried replacing the single quotes with str.replace() or str.replaceAll(). But that didn't work. I tried using both types where I used the '' outside of the "".
I also already asked ChatGPT for help, but the results were just the replace and replaceAll...
PS: It's 4:30 AM when I wrote this. I'm not at 100% of my usual capacity. So please don't hate me for my question.

Related

Cloudwatch alarm creation fails due to heredoc

I am trying to create a composite cloudwatch alarm using terraform. But unfortunately my terraform code breaks with the following error:
Error: error creating CloudWatch Composite Alarm
(node-count-office-time-composite-alarm-DP-1474-desert):
ValidationError: AlarmRule must not contain leading or trailing
whitespace or be null
status code: 400, request id: 272b14ae-e6bd-4e65-8bb8-25372d9a5f7c
Following is my terraform code:
resource "aws_cloudwatch_composite_alarm" "node_count_office_time_alarm" {
depends_on = [aws_cloudwatch_metric_alarm.node_count, aws_cloudwatch_metric_alarm.office_time]
alarm_description = "Composite alarm for node count & office time"
alarm_name = "node-count-office-time-composite-alarm-${local.postfix}"
alarm_actions = [var.sns_topic_arn]
ok_actions = [var.sns_topic_arn]
alarm_rule =<<-EOF
ALARM(${aws_cloudwatch_metric_alarm.node_count.alarm_name}) AND
ALARM(${aws_cloudwatch_metric_alarm.office_time.alarm_name})
EOF
}
I checked many times and there are no leading or trailing spaces in my alarm_rule. Only new line after AND operator. I am using terraform 0.15.3 version. Anyone faces similar issues and how can I resolve this issue? thanks
I did not find the solution to how to make the heredoc working. But I fixed it for the time being using direct string expression instead of heredoc block. Following is the string expression:
alarm_rule = "ALARM(${aws_cloudwatch_metric_alarm.node_count.alarm_name}) AND ALARM(${aws_cloudwatch_metric_alarm.office_time.alarm_name})"
I hope it is useful for others if they face the same issue. thanks
Terraform instructions https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_composite_alarm are not accurate as of this writing in 2021.
alarm_rule accepts a single string argument, EOF/heredoc has to be processed to create a literal string:
locals {
alarm_rule_with_newlines = <<-EOF
ALARM(${aws_cloudwatch_metric_alarm.alpha.alarm_name}) OR
ALARM(${aws_cloudwatch_metric_alarm.bravo.alarm_name})
EOF
}
[...]
alarm_rule = trimspace(replace(local.alarm_rule_with_newlines, "/\n+/", " "))
I was not satisfied with neither of proposed answers so I have another solution.
Move your composite alert rules to separate file and just read it:
alarm_rule = file("./composite-alert-rule")
or
alarm_rule = templatefile("./composite-alert-rule", { arg = ... })
if you need to pass some dynamic args.
Check terraform docs for reference:
https://www.terraform.io/language/functions/templatefile
https://www.terraform.io/language/functions/file

How to remove quotes in suds-py3 requests

I´m using suds-py3 to make requests to a service with complex arguments that requires numbers and texts. This is the code i´m trying:
from suds.client import Client
url = <service_url>
parameter = <service_method_parameter>
method = <service_method>
client = Client(url)
parameter_object = client.factory.create(str(parameter))
Until here, i´ve created a dictionary of the values that the service asks that looks like this:
parameter_object = {
'codigoAmbiente': '',
'codigoModalidad': '',
'codigoPuntoVenta': '',
'codigoSistema': '',
'codigoSucursal': '',
'cuis': '',
'nit': ''
}
So to make the request, i create another dictionary with the required values:
request_dictionary = {
'codigoAmbiente': 2,
'codigoModalidad': 2,
'codigoPuntoVenta': 0,
'codigoSistema': 'AA5BB4CC3',
'codigoSucursal': 0,
'cuis': 'A1B2C3',
'nit': 12343456
}
Then i send the values to the service with the following code.
for var, value in request_dictionary.items():
parameter_object[str(var)] = value
request_response = getattr(client.service, method)()
print(request_response)
The problem is that the service sends back an error because of the quotes, it doesn´t recognise them. If i try to send a dictionary like the following:
request_dictionary = {
'codigoAmbiente': 2,
'codigoModalidad': 2,
'codigoPuntoVenta': 0,
'codigoSistema': AA5BB4CC3,
'codigoSucursal': 0,
'cuis': A1B2C3,
'nit': 12343456
}
Python throws the error "NameError: AA5BB4CC3 is not defined".
How should my code look like so the request to the service is as intended?
I´ve made a mistake in my code. It wasn´t the quotes. The correct code is the following:
from suds.client import Client
url = <service_url>
parameter = <service_method_parameter>
method = <service_method>
client = Client(url)
parameter_object = client.factory.create(str(parameter))
for var, value in request_dictionary.items():
parameter_object[str(var)] = value
request_response = getattr(client.service, method)(parameter_object)
print(request_response)
As you can notice, the mistake was in this line:
request_response = getattr(client.service, method)(parameter_object)
in wich the "parameter_object" dicitonary that contains the request values was missing.

Lua string from file

I'm trying to make a system which backs up and restores points for a gameserver, so it can safely restart without loosing anything.
I have made a script to do just this and the actual backing up part works fine, but the restore part does not.
This is the script that runs if 'Backup(read)' is used (Backup(write) works perfectly as it is designed to do):
if (source and read) then
System.LogAlways("[System] Restoring serverdata from file 'backup.CHK'");
for line in source:lines() do
Backup = {};
Backup.Date = (Date or line:match("File Last Modified: (.-)"));
Backup.Time = (Time or line:match("time: (.-)"));
US = tonumber((US or line:match("us: (.-)")));
NK = tonumber((NK or line:match("nk: (.-)")));
local params = {class = "Player";
position = {x = 1, y = 1, z = -1000};
Respawn = { bRespawn = 0; nTimer =0; bUnique = 1; };
bUsable = 0;
orientation = {0, 90, 135};
name = "BackupEntity"; };
local ent = System.SpawnEntity(params);
g_gameRules.game:SetTeam(1, ent.id);
g_gameRules.game:SetSynchedEntityValue(playerId, 100, (NK/3));
g_gameRules.game:SetTeam(2, ent.id);
g_gameRules.game:SetSynchedEntityValue(playerId, 100, (US/3));
System.RemoveEntity(params);
end
source:close();
return;
end
I'm not sure what I'm doing wrong,and most sites that I have looked at don't help that much. The problem is that it's not reading any values from the file.
Any help will be appreciated :).
Edit:
The reason that we have to divide the score by 3 is because the server multiplies all scores by 3. If we were not to divide it by 3, then the score will always be 3 times larger on each restore.
Example contents of the backup.CHK file:
The server is dependent on this file, and writes to it every hour. Please do not edit.
File Last Modified: 11/07/2013
This file was generated by the servers' autobackup system.
--------------------------
time: 22:51
us: 453445
nk: 454567
A couple of ideas of what might be causing the problem:
Use of (.-) lazy matching which matches the shortest pattern possible -- this can include an empty string. Usually, you want to make the pattern as specific as possible while still matching the required possible inputs. eg. It looks like (%d+) for us and nk is an appropriate fit.
The for line in source:lines() do reads one line at a time. That necessarily means not all the variables are going to be set inside the loop. Yet everything starting at local params and down uses those variables as if they were. It seems to me that section of code shouldn't even be in the loop.
Lastly, have you considered saving the Backup file as just another lua file? Doing so means you can let lua do the heavy lifting for you and you won't have to bother parsing it yourself. That also minimizes the risk for error.

Groovy TimeCategory bad millseconds addition

When try this sample code:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}
in groovy web console, I get a funny result:
0.1100 seconds
Does any one know why this happens or how to fix it?
That looks like a bug, the TimeDuration contains 1100 milliseconds, but when it prints it out, it converts it wrongly to seconds.
I've added it to the Groovy JIRA as a bug EDIT It's now marked as FIXED for versions 2.0.6, 1.8.9 and 2.1.0
In the mean time, I guess you'll need to do your own converter from TimeDuration to String :-/
Edit
You could do something like this (and there is probably a neater way of doing it)
groovy.time.TimeDuration.metaClass.normalize = { ->
def newdmap = ['days','hours','minutes','seconds','millis'].collectEntries {
[ (it):delegate."$it" ]
}.with { dmap ->
[millis:1000,seconds:60,minutes:60,hours:24,days:-1].inject( [ dur:[ days:0, hours:0, minutes:0, seconds:0, millis:0 ], roll:0 ] ) { val, field ->
val.dur."$field.key" = dmap."$field.key" + val.roll
val.roll = val.dur."$field.key".intdiv( field.value )
val.dur."$field.key" = field.value < 0 ?
val.dur."$field.key" :
val.dur."$field.key" % field.value
val
}.dur
}
new TimeDuration( newdmap.days, newdmap.hours, newdmap.minutes, newdmap.seconds, newdmap.millis )
}
That adds a normalize method to TimeDuration, so then doing:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}.normalize()
Shows 1.100 seconds
I haven't done a huge amount of testing on that method, so be warned it could do with some unit tests to make sure it doesn't fall over with other situations.

Nodejs parameter resolution and printing

I am trying to debug my mobile website which is running on Nodejs.
In some part there are those lines:
var log_line = {accessCount: accessCount, x: x, time: t};
logstream.write(JSON.stringify(log_line));
Which are suppose to log parts of the users page request. The path is defined as app.get('/:x?.:y?.:z?', function(req, res){ ).
For some users this works fine, but for others in the log I only find a line saying "{"accessCount": 1, "time": "10/10/10"}". How is it possible? shouldn't it at least printed the x without anything beside it? what could cause this effect?
If x is undefined, it won't get printed:
> JSON.stringify({x:undefined})
'{}'
If you are looking for a solution to get over it. Change the code as
if (!x) {
x = "NOT_DEFINED" // or your own place holder value
}
var log_line = {accessCount: accessCount, x: x :, time: t};
or more terse would be
var log_line = {accessCount: accessCount, x: x ? x : "NOT_DEFINED", time: t};

Resources