exclude entity variable from PUT request - javascript

I am sending an entity to the database through a put request, but one of the variables is giving me trouble. I would like to know if there's a way to exclude a single variable from the request.
I am using axios for the db connection.
This is the entity being sent.
$this->id = 0;
$this->user = '';
$this->type = '';
$this->status = null;
$this->signatureList = new ArrayCollection();
//this is the array i want to exclude
$this->amendmentList = new ArrayCollection();
$this->draft = true;
$this->archived = false;
$this->canceled = false;
$this->finished = false;
$this->signed = false;
$this->subject = null;
$this->content = '';
$this->createdAt = new \DateTime();
parent::__construct();
This is the put request.
//it gets the entity through the id and sends it whole
update: (id, data) => {
window.httpMessage = { show: true, success: `Documento <b>#${id}</b> Atualizado`, error: "Documento <b>não Atualizado</b>" }
return http.put(`/eletronic-documents/${id}`, data).then(res => res.data)
}

As suggested by user steadweb, a delete on the client side did the trick.

Related

Get specifics ids in IndexedDB [duplicate]

I want to execute this query
select * from properties where propertyCode IN ("field1", "field2", "field3")
How can I achieve this in IndexedDB
I tried this thing
getData : function (indexName, params, objectStoreName) {
var defer = $q.defer(),
db, transaction, index, cursorRequest, request, objectStore, resultSet, dataList = [];
request = indexedDB.open('test');
request.onsuccess = function (event) {
db = request.result;
transaction = db.transaction(objectStoreName);
objectStore = transaction.objectStore(objectStoreName);
index = objectStore.index(indexName);
cursorRequest = index.openCursor(IDBKeyRange.only(params));
cursorRequest.onsuccess = function () {
resultSet = cursorRequest.result;
if(resultSet){
dataList.push(resultSet.value);
resultSet.continue();
}
else{
console.log(dataList);
defer.resolve(dataList);
}
};
cursorRequest.onerror = function (event) {
console.log('Error while opening cursor');
}
}
request.onerror = function (event) {
console.log('Not able to get access to DB in executeQuery');
}
return defer.promise;
But didn't worked. I tried google but couldn't find exact answer.
If you consider that IN is essentially equivalent to field1 == propertyCode OR field2 == propertyCode, then you could say that IN is just another way of using OR.
IndexedDB cannot do OR (unions) from a single request.
Generally, your only recourse is to do separate requests, then merge them in memory. Generally, this will not have great performance. If you are dealing with a lot of objects, you might want to consider giving up altogether on this approach and thinking of how to avoid such an approach.
Another approach is to iterate over all objects in memory, and then filter those that don't meet your conditions. Again, terrible performance.
Here is a gimmicky hack that might give you decent performance, but it requires some extra work and a tiny bit of storage overhead:
Store an extra field in your objects. For example, plan to use a property named hasPropertyCodeX.
Whenever any of the 3 properties are true (has the right code), set the field (as in, just make it a property of the object, its value is irrelevant).
When none of the 3 properties are true, delete the property from the object.
Whenever the object is modified, update the derived property (set or unset it as appropriate).
Create an index on this derived property in indexedDB.
Open a cursor over the index. Only objects with a property present will appear in the cursor results.
Example for 3rd approach
var request = indexedDB.open(...);
request.onupgradeneeded = upgrade;
function upgrade(event) {
var db = event.target.result;
var store = db.createObjectStore('store', ...);
// Create another index for the special property
var index = store.createIndex('hasPropCodeX', 'hasPropCodeX');
}
function putThing(db, thing) {
// Before storing the thing, secretly update the hasPropCodeX value
// which is derived from the thing's other properties
if(thing.field1 === 'propCode' || thing.field2 === 'propCode' ||
thing.field3 === 'propCode') {
thing.hasPropCodeX = 1;
} else {
delete thing.hasPropCodeX;
}
var tx = db.transaction('store', 'readwrite');
var store = tx.objectStore('store');
store.put(thing);
}
function getThingsWherePropCodeXInAnyof3Fields(db, callback) {
var things = [];
var tx = db.transaction('store');
var store = tx.objectStore('store');
var index = store.index('hasPropCodeX');
var request = index.openCursor();
request.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var thing = cursor.value;
things.push(thing);
cursor.continue();
} else {
callback(things);
}
};
request.onerror = function(event) {
console.error(event.target.error);
callback(things);
};
}
// Now that you have an api, here is some example calling code
// Not bothering to promisify it
function getData() {
var request = indexedDB.open(...);
request.onsuccess = function(event) {
var db = event.target.result;
getThingsWherePropCodeXInAnyof3Fields(db, function(things) {
console.log('Got %s things', things.length);
for(let thing of things) {
console.log('Thing', thing);
}
});
};
}

ES6: "TyperError: X is not a function"

I am trying to add a function to a class in my Express/Node server, but I keep getting TypeError: req.session.user.bills[0].getFormattedDueDate is not a function. I have other classes whose member functions work, including in the same method that throws this error. I checked the type of the objects in req.session.user.bills and it was object. The project is built with Webpack and Babel.
If I take all of the properties in req.session.user.bills[0] and put them in a new object, then the functions work. The data flow for this object works like this. The name of the main file is server2.js.
The user logs in by hitting and endpoint in server2.js.
An object name userDao gets the user from the database and returns a User object with an array of Bills. Both UserDao and User are required at the top of server2.js.
Another endpoint is hit to show the bills. This passes the User object to an EJS file. It is here that I try to use the function and it doesn't work.
server.js:
const User = require('babel-loader!./src/model/user.js');
const UserDao = require('babel-loader!./src/model/userDao.js');
const Bill = require('babel-loader!./src/model/bill.js');
const userDao = new UserDao(pool);
...
app.all('/bills', function(req, res) {
const temp1 = req.session.user.bills[0].getFormattedDueDate();
res.render('bills.ejs', {
URL: config.URL,
user: req.session.user
})
});
But if I instantiate a new object, it works:
app.all('/bills', function(req, res) {
const temp = new Bill(
req.session.user.bills[0].id,
req.session.user.bills[0].userId,
req.session.user.bills[0].periodId,
req.session.user.bills[0].accountId,
null,
req.session.user.bills[0].name,
req.session.user.bills[0].amount,
req.session.user.bills[0].autoPay,
req.session.user.bills[0].weekDay,
req.session.user.bills[0].dueDate,
req.session.user.bills[0].dueDate2,
req.session.user.bills[0].paid
);
const temp1 = temp.getFormattedDueDate();
res.render('bills.ejs', {
URL: config.URL,
user: req.session.user
})
});
userDao.js:
//Lots of other data is put in user...
//Bills
for (let i = 0; i < rows[BILLS_INDEX].length; i++) {
user.bills.push(new Bill(
rows[BILLS_INDEX][i].id,
rows[BILLS_INDEX][i].userId,
rows[BILLS_INDEX][i].periodId,
rows[BILLS_INDEX][i].accountId,
new Tag(rows[BILLS_INDEX][i].tagId, rows[BILLS_INDEX][i].userId, rows[BILLS_INDEX][i].name),
rows[BILLS_INDEX][i].name,
rows[BILLS_INDEX][i].amount,
rows[BILLS_INDEX][i].autoPay === 1,
rows[BILLS_INDEX][i].weekDay === 1,
rows[BILLS_INDEX][i].startDate,
rows[BILLS_INDEX][i].startDate2,
rows[BILLS_INDEX][i].paid === 1
));
}
resolve(user);
user.js:
module.exports = class User {
constructor(id, firstName, lastName, imageUrl, email, tags, items, budgetItems, piggyBanks, bills) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.imageUrl = imageUrl;
this.email = email;
this.tags = tags || new Array();
this.items = items || new Array();
this.budgetItems = budgetItems || new Array();
this.piggyBanks = piggyBanks || new Array();
this.bills = bills || new Array();
}
}
bill.js:
const moment = require('moment');
module.exports = class Bill {
constructor(pId, pUserId, pPeriodId, pAccountId, pTag, pName, pAmount, pAutoPay, pWeekDay, pdueDate, pdueDate2, pPaid) {
this.id = pId;
this.userId = pUserId,
this.periodId = pPeriodId,
this.accountId = pAccountId,
this.tag = pTag,
this.name = pName,
this.amount = pAmount,
this.autoPay = pAutoPay,
this.weekDay = pWeekDay,
this.dueDate = pdueDate,
this.dueDate2 = pdueDate2,
this.paid = pPaid
}
getFormattedDueDate() {
return moment(this.dueDate).format('MMM DD, YYYY');
}
getFormattedDueDate2() {
return moment(this.dueDate2).format('MMM DD, YYYY');
}
}
I would expect the method to work, since the methods in userDao.js work, but I get the undefined method error.
EDIT: I checked req.session.user.bills[0] instanceof Bill and it returned false.
When you store an object in session, it is serialized as JSON. And when you retrieve it, it is parsed again, as a plain object. So any original prototype information is lost in this process. As stated in the documentation of the express-session module:
To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store [...]
To restore the prototype information, you could do:
req.session.user.bills.forEach(bill => Object.setPrototypeOf(bill, Bill.prototype));
And then this should work:
const temp1 = req.session.user.bills[0].getFormattedDueDate();
Alternatively, if you just want to be able to call the method once, you can use .call:
const temp1 = Bill.prototype.getFormattedDueDate.call(req.session.user.bills[0]);

Working example for signal protocol in js

Hi there i try to make i clientside message exchange with the signal protocol (only for tests). But i have trouble to the proccessPreKey.
Here is the test code
<script src="javascripts/libsignal-protocol.js"></script>
<script src="javascripts/InMemorySignalProtocolStore.js"></script>
<script>
var KeyHelperUser1 = libsignal.KeyHelper;
var KeyHelperUser2 = libsignal.KeyHelper;
var registrationId_User1 = KeyHelperUser1.generateRegistrationId();
var registrationId_User2 = KeyHelperUser2.generateRegistrationId();
// Store registrationId somewhere durable and safe.
var identityKeyPair_User1, identityKeyPair_User2;
var SignedPreKey_User1, SignedPreKey_User2;
// Test Store
var store_User1 = new SignalProtocolStore();
var store_User2 = new SignalProtocolStore();
var PreKey_User1, PreKey_User2;
// Build the session
var address_User1 = new libsignal.SignalProtocolAddress(1002, 0);
var address_User2 = new libsignal.SignalProtocolAddress(1001, 0);
var sessionBuilder_User1 = new libsignal.SessionBuilder(store_User1, address_User1);
var sessionBuilder_User2 = new libsignal.SessionBuilder(store_User2, address_User2);
KeyHelperUser1.generateIdentityKeyPair().then(function(identityKeyPair) {
// keyPair -> { pubKey: ArrayBuffer, privKey: ArrayBuffer }
// Store identityKeyPair somewhere durable and safe.
identityKeyPair_User1 = identityKeyPair;
KeyHelperUser1.generatePreKey(1001).then(function(preKey) {
//store.storePreKey(preKey.keyId, preKey.keyPair);
PreKey_User1 = preKey;
KeyHelperUser2.generatePreKey(1002).then(function(preKey) {
//store.storePreKey(preKey.keyId, preKey.keyPair);
PreKey_User2 = preKey;
KeyHelperUser1.generateSignedPreKey(identityKeyPair_User1, 1001).then(function(signedPreKey) {
store_User1.storeSignedPreKey(signedPreKey.keyId, signedPreKey.keyPair);
SignedPreKey_User1 = signedPreKey;
KeyHelperUser2.generateIdentityKeyPair().then(function(identityKeyPair) {
// keyPair -> { pubKey: ArrayBuffer, privKey: ArrayBuffer }
// Store identityKeyPair somewhere durable and safe.
identityKeyPair_User2 = identityKeyPair;
KeyHelperUser2.generateSignedPreKey(identityKeyPair_User2, 1002).then(function(signedPreKey) {
store_User2.storeSignedPreKey(signedPreKey.keyId, signedPreKey.keyPair);
SignedPreKey_User2 = signedPreKey;
var promise_User1 = sessionBuilder_User1.processPreKey({
registrationId: registrationId_User2,
identityKey: identityKeyPair_User2.pubKey,
signedPreKey: {
keyId : 1002,
publicKey : SignedPreKey_User2.pubKey,
signature : SignedPreKey_User2.signature
},
preKey: {
keyId : 1002,
publicKey : PreKey_User1.pubKey
}
});
promise_User1.catch(function onerror(error) {
// handle identity key conflict
//console.log(error);
});
});
});
});
});
});
});
</script>
I don't really know which parameters the processPreKey wanted. Can someone help?
Hey so this is something i put together, hope it helps.
var KeyHelper = libsignal.KeyHelper;
function generateIdentity(store) {
return Promise.all([
KeyHelper.generateIdentityKeyPair(),
KeyHelper.generateRegistrationId(),
]).then(function(result) {
store.put('identityKey', result[0]);
store.put('registrationId', result[1]);
});
}
function generatePreKeyBundle(store, preKeyId, signedPreKeyId) {
return Promise.all([
store.getIdentityKeyPair(),
store.getLocalRegistrationId()
]).then(function(result) {
var identity = result[0];
var registrationId = result[1];
return Promise.all([
KeyHelper.generatePreKey(preKeyId),
KeyHelper.generateSignedPreKey(identity, signedPreKeyId),
]).then(function(keys) {
var preKey = keys[0]
var signedPreKey = keys[1];
store.storePreKey(preKeyId, preKey.keyPair);
store.storeSignedPreKey(signedPreKeyId, signedPreKey.keyPair);
return {
identityKey: identity.pubKey,
registrationId : registrationId,
preKey: {
keyId : preKeyId,
publicKey : preKey.keyPair.pubKey
},
signedPreKey: {
keyId : signedPreKeyId,
publicKey : signedPreKey.keyPair.pubKey,
signature : signedPreKey.signature
}
};
});
});
}
var ALICE_ADDRESS = new libsignal.SignalProtocolAddress("xxxxxxxxx", 1);
var BOB_ADDRESS = new libsignal.SignalProtocolAddress("yyyyyyyyyyyyy", 1);
var aliceStore = new libsignal.SignalProtocolStore();
var bobStore = new libsignal.SignalProtocolStore();
var bobPreKeyId = 1337;
var bobSignedKeyId = 1;
var Curve = libsignal.Curve;
Promise.all([
generateIdentity(aliceStore),
generateIdentity(bobStore),
]).then(function() {
return generatePreKeyBundle(bobStore, bobPreKeyId, bobSignedKeyId);
}).then(function(preKeyBundle) {
var builder = new libsignal.SessionBuilder(aliceStore, BOB_ADDRESS);
return builder.processPreKey(preKeyBundle).then(function() {
var originalMessage = util.toArrayBuffer("my message ......");
var aliceSessionCipher = new libsignal.SessionCipher(aliceStore, BOB_ADDRESS);
var bobSessionCipher = new libsignal.SessionCipher(bobStore, ALICE_ADDRESS);
aliceSessionCipher.encrypt(originalMessage).then(function(ciphertext) {
// check for ciphertext.type to be 3 which includes the PREKEY_BUNDLE
return bobSessionCipher.decryptPreKeyWhisperMessage(ciphertext.body, 'binary');
}).then(function(plaintext) {
alert(plaintext);
});
bobSessionCipher.encrypt(originalMessage).then(function(ciphertext) {
return aliceSessionCipher.decryptWhisperMessage(ciphertext.body, 'binary');
}).then(function(plaintext) {
assertEqualArrayBuffers(plaintext, originalMessage);
});
});
});
Not enough rep to comment; just addressing the comments below the answer.
#Niczem Olaske, the util.toArrayBuffer([message]) can be removed. The returned ciphertext is already an arrayBuffer, and converting the message to an arrayBuffer prior to encryption creates the need to convert it back to a string at the end anyway. However, a global 'util' object must be declared in order for libsignal to work (at least in JavaScript). So you can just put: const util = {}; somewhere outside function bodies, or alternatively: Object.assign(window, { util: {} }); before using libsignal.
#Hasib Mahmud, this error is from Bob trying to encrypt a message to Alice when a session has not yet been established. If you use async/await instead of .then(() => etc...), you will avoid this problem. Bob must decrypt Alice's message first in order to establish a session with her, and then encrypt messages to her. Note that he needs to use the 'decryptPreKeyWhisperMessage' method in order to use her preKey to establish the session whilst calling the method. After the session has been established on both sides, he can use the 'decryptWhisperMessage' method.

How can I remove user from Hub?

I'm sending by ajax post request to a method in the controller a string 'userName' that I should kick.
Is it possible to remove the user from current hub calling the method in the controller?
public ActionResult Kick(string userName)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
var user = userService.GetUserByName(userName);
var room = chatRoomService.GetRoomById(user.ChatRoomId.Value);
user.IsKicked = true;
userService.LeaveRoom(user);
hubContext.Groups.Remove(user.ConnectionIdInHub, room.Name);
return Json(new {success = true});
}
Could i somewhere in this method disconnect user from hub?
Server Side-
You should store user's connection ID at the time of his connection.
Like this in server side-
public override Task OnConnected()
{
Boolean isFoundAnydevice = false;
if(receivedClientId.Length>0) //With Param
{
int noOfSelectedDevice = _context.TargatedDevice.Where(x => x.PhoneId == receivedClientId).Count();
if (noOfSelectedDevice > 0)
isFoundAnydevice = true;
}
else //With no Param
{
String deviceId = _context.Device.Where(d => d.ConnectionId == this.Context.ConnectionId).Select(d => d.ClientId).SingleOrDefault();
int noOfSelectedDevice = _context.TargatedDevice.Where(x => x.PhoneId == deviceId).Count();
if (noOfSelectedDevice > 0)
isFoundAnydevice = true;
}
if (isFoundAnydevice)
{
_logger.LogWarning(
receivedClientId + " added to Test group"
);
Groups.Add(this.Context.ConnectionId, testGroupName);
}
return base.OnConnected();
}
Then you can easily find the user's connection ID from DB.
Now you can easily stop the hub connection like this-
public Task Disconnect(string connectionId)
{
try
{
lock (_lock)
{
var connections = _registeredClients.Where(c => c.Value.Any(connection => connection == connectionId)).FirstOrDefault();
// if we are tracking a client with this connection
// remove it
if (!CollectionUtil.IsNullOrEmpty(connections.Value))
{
connections.Value.Remove(connectionId);
// if there are no connections for the client, remove the client from the tracking dictionary
if (CollectionUtil.IsNullOrEmpty(connections.Value))
{
_registeredClients.Remove(connections.Key);
}
}
}
}
catch (Exception ex)
{
Log.Error(this, "Error on disconnect in hub", ex);
}
return null;
}
More can be found in here.
Client Side-
If you like to do it from client side, you can do this-
$.connection.hub.stop();
Hope you have your answer

why object variable property did not work in nodejs

I have a utility function which pass parameters 'name page callback' to the function. Why not work as i tried so many times?
PLUS: seems 'query.tag_id = name' work for me but why query[name] = name did not work so that i can pass whatever name i like;That's, i want to pass the variable /name/ as the property name so that i can use whatever name i like. For example, i can find posts by user_id when i pass user_id variable as the name value. Also i can find posts by its tag_id when i pass tag_id variable as the name value so it's much more flexible than when i use 'query.user_id = name' to do it ,where the name can only be user_id variable or value
NO LIBRARY USED EXCEPT EXPRESS AND NODEJS WITH CONNECT-FLESH, MONGOOSE ETC.
// post_proxy/post.js
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTen: (name,page,callback)=>{
var query = {};
//name = query;
if(name){
query[name] = name;
console.log('query[name] is'+ Object.keys(query));
}
Post.count(query, ( err, count)=>{
if (err) {
return callback(err);
}else{
console.log( `Number of posts: ${count} . query is ${query}` );
Post.find(query).skip((page-1)*10).limit(10).sort({created_at: -1}).exec((err,posts)=>{
if (err) {
return callback(err);
}
console.log('Posts inthe getTen function is: '+posts);
const modifiedPosts = posts.map(post=>{
return post.processPost(post);
});
console.log('modifiedPosts: '+modifiedPosts);
callback(null, modifiedPosts, count);//provide the params(caluated values),and what to do? you need to figure it out yourself
});
}
});
}
// controller/post.js:
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTagsPost: (req,res)=>{
const tag_id = req.params.tag_id;
const page = req.query.p ? parseInt(req.query.p) : 1;
//let loginedUser;
console.log('entering into the tagpost');
postProxy.getTen(tag_id, page, (err, posts, count)=> {
if (err) {
console.log('some error with getting the 10 posts:'+ err);
//next(err);
posts = [];
}
// if(req.user){
// loginedUser = req.user.processUser(req.user);
// }
//userProxy.getUserById(user_id, theuser=>{
console.log('tag posts for'+ tag_id +posts);
res.render('post/tagPosts', {
title: 'specific tag page',
user: req.user ? req.user.processUser(req.user) : req.user,
//postUser: req.user ? (req.user._id == user_id ? loginedUser : theuser) : theuser,
posts: posts,
page: page,
isFirstPage: (page - 1) == 0,
isLastPage: ((page - 1) * 10 + posts.length) == count,
messages: {
error: req.flash('error'),
success: req.flash('success'),
info: req.flash('info'),
}, // get the user out of session and pass to template
});
});
},
...
}
//route:
router.get('/tag/:tag_id', post.getTagsPost);
UPDATE:
Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}
UPDATE: Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}

Categories