Script create duplicate convensations Mongodb - javascript

I'm currently developing a conversation system with messages.
It checks if it has an active conversation ( hasConversation function) , and then determines what it should do.
If it has a conversation, then it shall only send a message, else create a conversation and then send message.
Anyway, it seems like something is wrong with my hasConversation function.
No matter what I do, it always creates two conversations, even if one exists.
It might also act like, if I call the function three times, it might create one,
then create another one, but then send the 3rd call message within the 2nd conversation.
What is wrong with my function?
It should check if both users are in a conversation.
function:
function hasConversation(userid,user2) {
return new Promise(function(resolve, reject) {
var x = [userid,user2];
var y = [user2, userid];
conversations.findOne( { members: {$all: x} }).then(function (conversation) {
// conversations.findOne({ members: x }).then(function (conversation) {
return resolve(conversation);
});
});
}
model:
var conversationsSchema = new Schema({
initiateduser : String,
name: {type:String, default: 'no name'},
members: { type: [String], default: []},
time: Number,
global: { type: Boolean, default: false},
gang: { type: Boolean, default: false},
});
a conversation is created by the following:
function createConversation(userid,user2,message) {
return new Promise(function(resolve, reject) {
var conv = new convensations();
conv.members = [userid, user2];
conv.initiateduser = userid;
conv.save(function (err,room) {
if (room._id) {
console.log("conv created, sending message");
createMessage(userid, room._id, message);
return resolve(room._id);
} else {
console.log(err);
return resolve(err);
}
});
});
}
example of calls:
Messages_model.sendNPCmessage('59312d2b329b7535b07e273c','testing','testshit?');
Messages_model.sendNPCmessage('59312d2b329b7535b07e273c','testing','testshit2?');
Messages_model.sendNPCmessage('59312d2b329b7535b07e273c','testing','testshit2?');
current output:
EDIT 1:
here is the main function calling it:
function sendNPCmessage(userid,from,message) {
console.log("checking npc conv");
return hasConversation(userid,from).then(function (haveconv) {
console.log("having conv? " + from);
console.log(haveconv);
if (haveconv) {
console.log("yes?");
return createMessage(from,haveconv._id,message).then(function (result) {
console.log("created mess?");
return result;
});
} else {
console.log("no?");
return createConversation(from,userid,message).then(function (result) {
console.log("created conv?");
return result;
});
}
});
}

Related

SQL Tedious Loop through object of array and execute insert statement function error Request is not a constructor

I'm new to Js, and would appreciate some help.
Currently, via tedious js, I've written a sql function that passes an insert statement that loops through an array of objects and inserts each property in each object in array to SQL.
To do this, I've written a loop to iterate through the array, and insert each property as a new entry into sql.
However, when i try to execute the function after the connect, the function returns error Request is not a constructor
Here is the full code below. Is there some scope issue here, or am I not correctly handling the tedious js events properly or is there some sort of issue with my for loop?
var jsonArray = [];
let jsonobj = {
test: "1",
test2: "2"
}
let jsonobj1 = {
test: "23",
test2: "54"
}
jsonArray.push(jsonobj)
jsonArray.push(jsonobj1)
jsonArray.push(jsonobj)
var config = {
server: '123', //update me
authentication: {
type: 'default',
options: {
userName: '123', //update me
password: '1234' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
//encrypt: true,
requestTimeout: 30 * 1000,
trustServerCertificate: true,
database: 'db', //update me
rowCollectionOnRequestCompletion: true,
rowCollectionOnDone: true
}
};
var connection = new Connection(config);
connection.on('debug', function(err) { console.log('debug:', err);})
connection.on('connect', function(err) {
});
for (var i = 0; i < jsonArray.length; i++){
var sql = `insert into store (storekey,ip,port) values ( \'${jsonArray[i].test2}\' , '2' , '6');`
executeStatement1(sql)
}
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement1(sql) {
request = new Request(sql, function(err) {
if (err) {
console.log(err);}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(" success " + column.value);
}
});
});
connection.execSql(request);
}

can't get data from web worker

I have the following forEach:
hosts.forEach((host) => {
filterByHost(host);
});
as you can see the forEach call the following method where I pretend to use a web worker
function filterByHost(host) {
let sortedHost = [];
const filterHost = data.filter((element) => element.host.includes(host));
if (window.Worker) {
const worker = new Worker('utils.js');
worker.postMessage({ cmd: 'sortHost', filterHost });
worker.onmessage = function (event) {
switch (event.data.cmd) {
case 'sortHost':
servers = {
...servers,
[host]: event.data.data,
};
break;
default:
break;
}
};
}
}
the code inside my utils.js file is the following:
self.addEventListener(
'message',
function (event) {
switch (event.data.cmd) {
case 'uniqueHosts':
postMessage({ cmd: 'other', data: other(event.data.data) });
break;
case 'sortHost':
postMessage({
cmd: 'sortHost',
data: sortHost(event.data.filterHost),
});
break;
default:
break;
}
},
false
);
function other(data) {
return bla bla bla;
}
function sortHost(filterHost) {
return filterHost.sort((a, b) => {
if (a.apdex < b.apdex) {
return 1;
}
if (a.apdex > b.apdex) {
return -1;
}
return 0;
});
}
As you can see I trying to using a web worker in order to sort a big array of objects, and the worker works, it return a sorted array, but when I try to spread the results inside my servers I have and empty array, is like when the forEach call a the new Worker every thing is restarted and I can't find why

Add data to returned model sequelize

I have a sequelize model object that is working like expected.
const part = sequalize.define("part", {
id: {type:Sequalize.INTEGER, primaryKey: true, autoIncrement: true},
part_number: {type : Sequalize.STRING(12), unique: true, allowNull: false},
description: {type : Sequalize.STRING(255), allowNull: false}, true}
})
But I want to run an additional function when this model is called for example in a query.
I have this function now:
part.prototype.getTotalStock = function () {
let _this = this;
return new Promise(function(resolve, reject) {
part.findOne({
where: {id: _this.id},
include: [{
model: sequalize.models.location,
}]
}).then(result => {
if (result) {
var totalStock = 0;
let stockOnLocation = result.dataValues.locations
stockOnLocation.forEach(function (entry) {
totalStock += entry.stock.amount
});
_this.setDataValue('totalStock', totalStock);
return resolve(_this)
} else {
return resolve(0)
}
}).catch(err => {
return reject(err)
});
})
}
What i'm doing is that I do a query so I have 1 part object. After that I can call:
queryResult.getTotalStock().then(result => {
//data here in result
})
That is working, its retrieving the stock, calculating it, and it is adding the data to self. Now my question, is it possible to append the result of getTotalStock automatically when the model is being used? So that I don't have to call getTotalStock on the returned object?

asyncronous functions run in order when inside of a loop using promises

I have a method that runs in a for loop of data that needs to be inserted into a mongodb database.
before inserting i need to query the database to see if a similar record exists so that i can give it the same code else i need to find the max code of the record and give the inserted method the next highest code
the output i need is Code, 0, 2, insert for first record then Code, 1, 2, insert but the output i am receiving is code,0 code, 0 code, 0 code, 0 2,2,2,2 which tells me that the each action is running the amount of times in the loop one after each other and not in the sequence that i need it
//First Promise
const BatchCheckPromise = new Promise((resolve) => {
const Code = "";
var query = {
BatchCode: {
$eq: Row.BatchCode
}
}
//Mongo Database Query To Get Code From The Batch
var BatchRow = db.collection("ap_transaction_line").find(query).toArray();
BatchRow.then(function(db_data){
console.log("Code");
console.log(db_data.length);
//Get code if in database
if (db_data.length > 0) {
Code = db_data[0].Code;
}
resolve(Code)
});
});
//Second Promise
async function MaxCheckPromise(Code) {
return new Promise(
(resolve, reject) => {
//If code is still null after checking the database
if (Code == "" || Code == null) {
var Code = "";
var query = {
Prefix: {
$eq: Row.Prefix
}
}
var sort = {
Code: -1
};
//Mongo Database query for max code in the database
var MaxRow = db.collection("ap_transaction_line").find(query).sort(sort).limit(1).toArray();
MaxRow.then(function(db_data){
Code = db_data[0].Code;
Code++;
//Increment by 1 for new code
resolve(Code);
/////////
});
}
else {
resolve(Code);
}
}
)
}
//Insert function
async function InsertInToDataBase() {
try {
//first promise to query the batchcode
let BatchCode = await BatchCheckPromise;
//second promise to query the max code if no batchcode
let MaxCode = await MaxCheckPromise(BatchCode);
console.log(MaxCode);
//Insert into Database with new Code
if (Row.TimeStamp == "U") {
//vars
//db query
var db_collection = "ap_transaction_line";
var db_query = {
LocalID: Row.LocalID
};
var db_data = {
TimeStamp: Row.TimeStamp,
Error: Row.Error,
SyncID: Row.SyncID,
DateCreated: Row.DateCreated,
BatchCode: Row.BatchCode,
TransCode: Row.TransCode,
ConsCode: Row.ConsCode,
DebitCode: Row.DebitCode,
Prefix: Row.Prefix,
Code: MaxCode,
ToAcc: Row.ToAcc,
FromAcc: Row.FromAcc,
Vendor_Client: Row.Vendor_Client,
Date: Row.Date,
Description: Row.Description,
Qty_Calls: Row.Qty_Calls,
Price_Rate: Row.Price_Rate,
TotalEX: Row.TotalEX,
Ref: Row.Ref,
Detail: Row.Detail,
Username: Row.Username,
PaidStatus: Row.PaidStatus,
Period: Row.Period,
PeriodAuth: Row.PeriodAuth,
BankRecon: Row.BankRecon,
PDFName: Row.PDFName,
Auth: Row.Auth,
InvItem: Row.InvItem,
InvPicName: Row.InvPicName,
EpsNum: Row.EpsNum,
BatchGroup: Row.BatchGroup
};
m_connect("updateOne", DbName.DBname, db_collection, db_query, "", db_data, "", function (db_connect) {
//console.log('db_connect');
//console.log(db_connect);
});
} else if (Row.TimeStamp == "") {
//db query
var db_collection = "ap_transaction_line";
var db_query = {
SyncID: Row.SyncID
};
var db_data = {
TimeStamp: Row.TimeStamp,
Error: Row.Error,
SyncID: Row.SyncID,
DateCreated: Row.DateCreated,
BatchCode: Row.BatchCode,
TransCode: Row.TransCode,
ConsCode: Row.ConsCode,
DebitCode: Row.DebitCode,
Prefix: Row.Prefix,
Code: MaxCode,
ToAcc: Row.ToAcc,
FromAcc: Row.FromAcc,
Vendor_Client: Row.Vendor_Client,
Date: Row.Date,
Description: Row.Description,
Qty_Calls: Row.Qty_Calls,
Price_Rate: Row.Price_Rate,
TotalEX: Row.TotalEX,
Ref: Row.Ref,
Detail: Row.Detail,
Username: Row.Username,
PaidStatus: Row.PaidStatus,
Period: Row.Period,
PeriodAuth: Row.PeriodAuth,
BankRecon: Row.BankRecon,
PDFName: Row.PDFName,
Auth: Row.Auth,
InvItem: Row.InvItem,
InvPicName: Row.InvPicName,
EpsNum: Row.EpsNum,
BatchGroup: Row.BatchGroup
};
//m_connect("queryAll", db_collection, "", "", function(db_connect){
m_connect("insertone", DbName.DBname, db_collection, db_query, "", db_data, "", function (db_connect) {
//console.log('db_connect');
//console.log(db_connect);
console.log("Insert");
});
}
}
catch (error) {
console.log(error.message);
}
}
//Run the functions async
(async () => {
await InsertInToDataBase();
})();
I suggest you to rely on libraries like Axios to manage ajax call with promises, because it adds nice feature like serial calls (the one you need) and parallels calls.

Field args rejected when return a function not object

I want ask about GraphQL
This code will be failed, and shows error
Error: Mutation.addUser args must be an object with argument names as keys.
here is the code
const Schema = new GraphQLObjectType({
name: "Mutation",
description: "Mutation schema",
fields() {
return {
// Add user
addUser: {
type: UserSchema,
args: () => {
return {
firstName: {
type: GraphQLString
}
};
},
resolve(_, args){
return Db.models.user.update( () => {
return _.mapValues(args, (v, k) => {
return args[k];
});
}, {
returning: true
});
}
}
};
}
});
But, this code work perfectly
const Schema = new GraphQLObjectType({
name: "Mutation",
description: "Mutation schema",
fields() {
return {
// Add user
addUser: {
type: UserSchema,
args: {
firstName: {
type: GraphQLString
},
lastName: {
type: GraphQLString
}
},
resolve(_, args){
return Db.models.user.update( () => {
return _.mapValues(args, (v, k) => {
return args[k];
});
}, {
returning: true
});
}
}
};
}
});
Why args can't return object from function?
The fields itself can be a function, so having another function inside it to define args is kind of redundant.
The purpose of having them as functions is to be able to define types that need to refer to each other, or types that need to refer to themselves in a field.
So having only fields as a function will do the trick.

Categories

Resources