Why the current time in node js and when i try to input in mysql is different? - mysql

I just confuse with this case. I've been try to make sure the time zone in MySql and see the data that out from Date(Date.now()). That's all is correct with my timezone. But when i try to input the data to MySql, and i check in my Database. The time zone is wrong and different with my Time zone. Is there anyone can help me ?
This my code
const Employee = require('../models/employee');
const History = require('../models/history');
async createHistory(employee){
let result;
try {
const checkData = await Employee.findOne({where :
{employeeId : employee.employeeId}
});
if(checkData !== null){
const createData = await History.create({
employeeId : employee.employeeId,
in : Date(Date.now())
});
console.log(date.toLocaleString());
console.log('True')
}else {
result = {message : false}
}
} catch (e) {
logEvent.emit('APP_ERROR',{
logTitle: '[CREATE-HISTORY-ERROR]',
logMessage: e
});
}
return result;
}
The Time in field 'in' is wrong, it should be 14:43

I just get the answer,
The answer is .. because i using Sequelize to store the data to MySql i have to input the time zone in my connection.
Here my code :
const connection = new Sequelize(
{
timezone: "+07:00"
}
);

Related

i want to split a result in mysql can you help me?

Well, first that's my code here
client.on('message', async (message) => { //فايف ام داتابيس
if(message.channel.type == 'dm') return;
var prefix = prefixx.get(message.guild.id);
if(message.author.bot) return;
if(message.content.toLowerCase().startsWith(prefix + 'ip')) {
if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('ما عندك رتبة عشان تستخدم الأمر هذا');
let args = message.content.split(" ");
connection1.query(
`select ifnull((select last_login from vrp_users where id = ${args[1]}),'لا يوجد ايدي بهذا الرقم') As ResultFound`, function (error, result, fields) {
if (error) throw error;
console.log(`Got IP of user ${args[1]}`);
if(!result) return message.channel.send('There is an error');
if(error) return message.channel.send('There is an error');
let embed = new Discord.MessageEmbed() .setColor('RANDOM') .setTitle(`اي بي ${args[1]}`) .setThumbnail(message.guild.iconURL( { dynamic : true } )) .setAuthor(client.user.tag, client.user.avatarURL( {dynamic : true} )) .addField('IP', `\`${result[0].ResultFound}\``);
message.channel.send(embed)
}
);
}
});
the result comes like this :
77.223.232.147 23:50:55 29/06/2020
i want the result be only the ip can you guys help me?
Try this:
.addField('IP', `\`${result[0].ResultFound.split(' ')[0]}\``);
For example, if the result is what you provided in your question:
const result = '77.223.232.147 23:50:55 29/06/2020'
// split the message by every space
const array = result.split(' ');
console.log(array[0]); // IP adress
console.log(array[1]); // time (I presume)
console.log(array[2]); // date

Discord.js V12 Vote command not working somehow

so I am working on a command that makes like a vote embed, and it doesn't really work. when I use (in my case) $repvote #user it doesn't recognize the user or anything.., let me know for any solutions!
if (message.author.bot) return;
if (message.content.startsWith(prefix + "repvote")) {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send('You do not have that permission! :x:').then(message.react('❌'));
let repUser = message.mentions.members.first()
if(!repUser) return message.channel.send("Please mention the user you want to setup the vote for!").then(message.react('❌')).then(msg => { msg.delete({ timeout: 5000 });
const repVoteEmbed = new Discord.MessageEmbed()
repVoteEmbed.setTitle("Vote for Representative Members :crown:")
repVoteEmbed.setDescription(`User ${repUser} wants to recieve Representative Members :crown: role! Do you agree?`)
repVoteEmbed.setFooter(`Vote by: ${message.author.tag}, started on : ${message.createdAt}`)
message.channel.send({repVoteEmbed}).then(message.react('✔')).then(message.react('❌'))
})
}})```
You missing message.channel.send(embed).then(msg =>....
Message channel send return a promise of the sent message, so you need use it to react
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.content.startsWith(prefix + 'repvote')) {
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react('❌'));
let repUser = message.mentions.members.first();
if (!repUser) {
message.channel.send('Please mention the user you want to setup the vote for!').then((declineMsg) => {
message.react('❌');
declineMsg.delete({
timeout: 5000,
});
});
return;
}
const repVoteEmbed = new Discord.MessageEmbed();
repVoteEmbed.setTitle('Vote for Representative Members :crown:');
repVoteEmbed.setDescription(`User ${repUser} wants to recieve Representative Members :crown: role! Do you agree?`);
repVoteEmbed.setFooter(`Vote by: ${message.author.tag}, started on : ${message.createdAt}`);
message.channel.send(repVoteEmbed).then((msg) => {
msg.react(`✔`).then(() => msg.react('❌'));
});
}
});

AWS DMS Issue with boolean column

I'm trying to enable replication with DMS, using as source an Aurora mySQL instance and as destination a Redshift instance.
The replication fails on boolean columns. I have declared the boolean column as BIT(1) on the mySQL instance.
According to the documentation boolean columns in mySQL should be defined as BIT:
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MySQL.html#CHAP_Source.MySQL.DataTypes
If I remove the boolean column it works. I also tried to define the column as Boolean. That did not work either.
This is the error I'm getting:
2018-08-26T16:59:19 [TARGET_APPLY ]E: RetCode: SQL_ERROR SqlState:
42804 NativeError: 30 Message: [Amazon][Amazon Redshift] (30) Error
occurred while trying to execute a query: [SQLState 42804] ERROR:
column "state" is of type boolean but expression is of type character
varying, HINT: You will need to rewrite or cast the expression.
[1022502] (ar_odbc_stmt.c:4428)
This turns out to be a bug of DMS. This occurs only during ongoing replication, and not in full load. During replication the from Aurora MySql to Redshift the boolean is cast to Varchar resulting the error above.
I stuck in the same problem but I migrated my base so I solved with a post-script that may be can help you. Also, you can use the DMS events to notify the SMS and then call a lambda to make that.
Using node just run the file.js init()
const AWS = require("aws-sdk");
AWS.config.update({
region: "us-east-1"
});
const documentClient = new AWS.DynamoDB.DocumentClient();
let invalidList = [];
const TableName = 'TableName';
const params = {
TableName: TableName,
};
module.exports.init = function () {
console.log("Start Conversions of Details Booleans")
documentClient.scan(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Scan succeeded.");
// By default scan retrieves at max 1 mb of data
if (typeof data.LastEvaluatedKey != "undefined") {
console.log("Scanning for more...");
params.ExclusiveStartKey = data.LastEvaluatedKey;
documentClient.scan(params, onScan);
}
invalidList = getinvalidList(data);
if(invalidList.length == 0) {
console.log("All data is aready migrated");
return;
}
updateList(invalidList);
}
});
};
function getinvalidList(list) {
return list.Items.reduce((invalidList, item) => {
if (item) {
const variable = (item.variable && item.variable != undefined) ? item.variable : '0';
if (isNotBoolean(variable)) {
invalidList.push(item);
}
}
return invalidList;
}, []);
}
function updateList(list) {
list.forEach(item => {
var params = {
TableName: TableName,
Key: {
"id": item.id,
},
UpdateExpression: "set variable = :variable",
ExpressionAttributeValues: {
":variable": newValue(item.variable),
},
ReturnValues: "UPDATED_NEW"
};
documentClient.update(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
},
)
});
}
function newValue(variable) {
return isNotBoolean(variable) ? !!+variable : variable
}
function isNotBoolean(variable) {
return (typeof variable !== 'boolean')
}

Too tidious hooks when querying in REST. Any ideas?

I've just started using feathers to build REST server. I need your help for querying tips. Document says
When used via REST URLs all query values are strings. Depending on the service the values in params.query might have to be converted to the right type in a before hook. (https://docs.feathersjs.com/api/databases/querying.html)
, which puzzles me. find({query: {value: 1} }) does mean value === "1" not value === 1 ? Here is example client side code which puzzles me:
const feathers = require('#feathersjs/feathers')
const fetch = require('node-fetch')
const restCli = require('#feathersjs/rest-client')
const rest = restCli('http://localhost:8888')
const app = feathers().configure(rest.fetch(fetch))
async function main () {
const Items = app.service('myitems')
await Items.create( {name:'one', value:1} )
//works fine. returns [ { name: 'one', value: 1, id: 0 } ]
console.log(await Items.find({query:{ name:"one" }}))
//wow! no data returned. []
console.log(await Items.find({query:{ value:1 }})) // []
}
main()
Server side code is here:
const express = require('#feathersjs/express')
const feathers = require('#feathersjs/feathers')
const memory = require('feathers-memory')
const app = express(feathers())
.configure(express.rest())
.use(express.json())
.use(express.errorHandler())
.use('myitems', memory())
app.listen(8888)
.on('listening',()=>console.log('listen on 8888'))
I've made hooks, which works all fine but it is too tidious and I think I missed something. Any ideas?
Hook code:
app.service('myitems').hooks({
before: { find: async (context) => {
const value = context.params.query.value
if (value) context.params.query.value = parseInt(value)
return context
}
}
})
This behaviour depends on the database and ORM you are using. Some that have a schema (like feathers-mongoose, feathers-sequelize and feathers-knex), will convert values like that automatically.
Feathers itself does not know about your data format and most adapters (like the feathers-memory you are using here) do a strict comparison so they will have to be converted. The usual way to deal with this is to create some reusable hooks (instead of one for each field) like this:
const queryToNumber = (...fields) => {
return context => {
const { params: { query = {} } } = context;
fields.forEach(field => {
const value = query[field];
if(value) {
query[field] = parseInt(value, 10)
}
});
}
}
app.service('myitems').hooks({
before: {
find: [
queryToNumber('age', 'value')
]
}
});
Or using something like JSON schema e.g. through the validateSchema common hook.

Storing JSON data as columns in Azure table storage

How do a format my json data and/or change my function so that it gets stored as columns in Azure table storage?
I am sending a json string to the IoT hub:
{"ts":"2017-03-31T02:14:36.426Z","timeToConnect":"78","batLevel":"83.52","vbat":"3.94"}
I run the sample function (in the Azure Function App module) to transfer the data from the IoT hub into my storage account:
'use strict';
// This function is triggered each time a message is revieved in the IoTHub.
// The message payload is persisted in an Azure Storage Table
var moment = require('moment');
module.exports = function (context, iotHubMessage) {
context.log('Message received: ' + JSON.stringify(iotHubMessage));
context.bindings.deviceData = {
"partitionKey": moment.utc().format('YYYYMMDD'),
"rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
"message": JSON.stringify(iotHubMessage)
};
context.done();
};
But in my storage table, it shows up as a single string rather than getting split into columns (as seen in the storage explorer.
How do I get it into columns for ts, timeToConnect, batLevel, and vbat?
In case anyone is looking for a solution in c#:
private static async Task ProcessMessage(string message, DateTime enqueuedTime)
{
var deviceData = JsonConvert.DeserializeObject<JObject>(message);
var dynamicTableEntity = new DynamicTableEntity();
dynamicTableEntity.RowKey = enqueuedTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
foreach (KeyValuePair<string, JToken> keyValuePair in deviceData)
{
if (keyValuePair.Key.Equals("MyPartitionKey"))
{
dynamicTableEntity.PartitionKey = keyValuePair.Value.ToString();
}
else if (keyValuePair.Key.Equals("Timestamp")) // if you are using a parameter "Timestamp" it has to be stored in a column named differently because the column "Timestamp" will automatically be filled when adding a line to table storage
{
dynamicTableEntity.Properties.Add("MyTimestamp", EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
}
else
{
dynamicTableEntity.Properties.Add(keyValuePair.Key, EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
}
}
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myStorageConnectionString");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("myTableName");
table.CreateIfNotExists();
var tableOperation = TableOperation.Insert(dynamicTableEntity);
await table.ExecuteAsync(tableOperation);
}
How do I get it into columns for ts, timeToConnect, batLevel, and
vbat?
To get these attributes as separate columns in table, you would need to defalte the object and store them separately (currently you are just converting the entire object into string and storing that string).
Please try the following code:
module.exports = function (context, iotHubMessage) {
context.log('Message received: ' + JSON.stringify(iotHubMessage));
var deviceData = {
"partitionKey": moment.utc().format('YYYYMMDD'),
"rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
};
Object.keys(iotHubMessage).forEach(function(key) {
deviceData[key] = iotHubMessage[key];
});
context.bindings.deviceData = deviceData;
context.done();
};
Please note that I have not tried to execute this code so it may contain some errors.