Destroy And Object , Client Side - javascript

I can't delete an object on the client side, using the destroy function, I created an admin role and gave it all the necessary rights, but unfortunately I am always sent object not found when I want to delete an object. Voila Mon code.
`
user = getCurrentParseUser();
sessionToken = user.getSessionToken();
query = new Parse.Query(BillingPackage);
billingPackage = await query.get(billingPackageId);
console.log("billingPackage",billingPackage); //the object is retrieve here
if(billingPackage){
await billingPackage.destroy({sessionToken:sessionToken});
return {status: true, message: "The Billing Package Has Been Deleted"}
}else{
return {status: false, message: "The Billing Package Already Deleted"}
}`
The CLP Where Set True For All the action (create, read, delete, find)

You're not passing the session token to the query to find it.
billingPackage = await query.get(billingPackageId, {sessionToken:sessionTokne});

If you are logged in as the current user (user = getCurrentParseUser()), then you don't need to pass the sessionToken to the destroy method. If you are not logged in as the currentUser, you will not be allowed to get the other users sessionToken.
Assuming that you are logged in as the current user or you are a user who can delete the object, I have corrected your code bellow. Hope to be used as a reference for others too.
try {
const billingPackage = await new Parse.Query(BillingPackage).get(billingPackageId);
if (billingPackage) {
try {
await billingPackage.destroy();
return {
status: true,
message: "The Billing Package Has Been Deleted"
}
} catch (parseError) {
return {
{
status: false,
message: parseError.message
}
}
}
}
} catch (parseError) {
console.log(parseError.message);
}

Related

Quickblox WebRTC issue: onCallListener is not working inside my react app

So, basically I'm trying to receive a call from provider to my app. For that purpose Quickblox gives us a listener to receive the upcoming calls onCallListener. So here is my code snippet that should work but doesn't.
const calleesIds = [4104]
const sessionType = QB.webrtc.CallType.VIDEO
const additionalOptions = {}
let callSession = QB.webrtc.createNewSession(calleesIds, sessionType, null, additionalOptions)
console.log(callSession, "SESSION")
const mediaParams = {
audio: true,
video: true,
options: {
muted: true,
mirror: true,
},
elemId: "myVideoStream"
}
QB.webrtc.onCallListener = function(session: any, extension: object) {
callSession = session
console.log('asdasd')
// if you are going to take a call
session.getUserMedia(mediaParams, function (error: object, stream: object) {
if (error) {
console.error(error)
} else {
session.accept(extension)
session.attachMediaStream("videoStream", stream)
}
})
}
P.S. I also integrated chat which works perfect!
Found the solution by myself! Whenever you create a user and dialog id, search that user in the quickblox dashboard by the dialogId and change its settings: you will see that userId and providerId is the same which is wrong. So put your userId in the userId field and save that. After that you video calling listeners will work fine!)
P. S. also in the backend replace provider token with user token.

Trigger won't return the proper user object in Realm/MongoDB

With Realm sync of MongoDB, I'm trying to launch a trigger when a realm user is created to insert his newly created ID into my cluster. Here's the javascript function I made that is being called by the trigger :
exports = async function createNewUserDocument({ user }) {
const users = context.services
.get("mongodb-atlas")
.db("BD")
.collection("patients");
const query = { email: context.user.data.email };
const update = {
$set: {
patientId: context.user.id
}
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };
console.log(context.user.data.email);
return users.findOneAndUpdate(query, update, options)
.then(updatedDocument => {
if(updatedDocument) {
console.log(`Successfully updated document: ${updatedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return updatedDocument
})
.catch(err => console.error(`Failed to find and update document: ${err}`))
};
When running from the embed editor, while specifying the proper user manually, it's working perfectly. However, when launched by the trigger, it looks like the user is the system user and not the created user, because the error I get in the logs is the same I get when I run from the editor by specifying System user, which is Failed to find and update document: FunctionError: cannot compare to undefined. This makes sense because the System user is not a user per se, so the context.user is undefined.
I find it weird since I specify in the function settings that it should be executed with the permissions of the user calling the function. So my question is, is it possible to access the user.context of a user on his creation, and if so, how would I do it ?

Updating Stripe accounts returns "Error: Stripe: "id" must be a string, but got: object"

I am trying to update a Stripe account to add an external account token to be charged later as shown in the example here.
var stripe = require("stripe")("sk_test_xxxxxxxxxxxxx"),
knex = require("knex")(config);
router.post("/paymentcardinfo",middleware.isLoggedIn,function(req,res){
knex("users.stripe").select("stripe_id_key")
.then((stripeID) => {
stripeID = stripeID[0].stripe_id_key;
console.log("My Stripe ID: "stripeID);
console.log("stripeID var type:", typeof stripeID);
stripe.accounts.update({
stripeID,
external_account: req.body.stripeToken,
}, function(err,acct) {
if(err){
console.log(err);
} else {
console.log("SUCCESS ********",acct);
// asynchronously called
}})
})
.catch((e) => {
console.log(e);
res.redirect("/paymentcardinfo")
});
});
Which returns the following
My Stripe ID: acct_xxxxxxxxxxxxx
stripeID var type: string
[Error: Stripe: "id" must be a string, but got: object (on API request to `POST /accounts/{id}`)]
where acct_xxxxxxxxxxx is the user's stored account ID. Based on the first console.log value, it would appear that stripeID is a string and not an object, which makes me unsure of how to proceed with this error.
Although the documentation specifies
stripe.accounts.update({
{CONNECTED_STRIPE_ACCOUNT_ID},
metadata: {internal_id: 42},
}).then(function(acct) {
// asynchronously called
});`
The following worked for me
stripe.accounts.update(
CONNECTED_STRIPE_ACCOUNT_ID,
{
metadata: {internal_id:42},
}
).then((account) => {
// response to successful action

Quickblox one to one chat history not working

I am using Javascript SDK for 1-1 chat in Quickblox, but somehow I am not able to store the chat history.
I am following this link.
var message = {
body: text,
type: 'chat',
extension: {
nick: chatUser.email,
// token from session is set on window object
token: window.token,
// MyChat is a custom class_name
class_name: 'MyChat'
}
};
I am passing the class_name and token since I saw the android sdk following the same pattern.
private Message createMsgWithAdditionalInfo(int userId, String body, Map<?, ?> addinfoParams){
Message message = new Message(QBChatUtils.getChatLoginFull(userId), Message.Type.chat);
String addInfo = ToStringHelper.toString(addinfoParams, "", Consts.ESCAPED_AMPERSAND);
//
MessageExtension messageExtension = new MessageExtension(Consts.QB_INFO, "");
try {
messageExtension.setValue("token", QBAuth.getBaseService().getToken());
messageExtension.setValue("class_name", "ChatMessage");
messageExtension.setValue("additional", addInfo);
} catch (BaseServiceException e) {
e.printStackTrace();
}
message.addExtension(messageExtension);
message.setBody(body);
return message;
}
Also in instructions I see this.
<message id="123" type="chat" to="291-92#chat.quickblox.com" from="292-92#chat.quickblox.com"><body>Hi there</body><quickblox xmlns=""><token>848d4bf336d99532deff6bf7c8bb4b7e7b1a71f9</token><class_name>ChatMessage</class_name></quickblox></message>
Here also I see token & class passed so I am guessing how to I structure in my message object so that I get it to work.
The way I have created chatService is this.
chatService = new QBChat(params);
// to send message I am using sendMessage function
// message object is same as defined above.
chatService.sendMessage(recipientID, message);
This is an old and deprecated method to store chat history
Look at this guide http://quickblox.com/developers/Chat#Server-side_chat_history
var msg = {
body: "Hey",
extension: {
save_to_history: 1
},
senderId: currentUser.id,
};
You have to use 'save_to_history' to store a message
You can use this branch as a basis
https://github.com/QuickBlox/quickblox-javascript-sdk/tree/develop.chat/samples/chat

Meteor - How to find out if Meteor.user() can be used without raising an error?

I'm looking for a way to determine if Meteor.user() is set in a function that can be called both from the server and client side, without raising an error when it is not.
In my specific case I use Meteor server's startup function to create some dummy data if none is set. Furthermore I use the Collection2-package's autoValue -functions to create some default attributes based on the currently logged in user's profile, if they are available.
So I have this in server-only code:
Meteor.startup(function() {
if (Tags.find().fetch().length === 0) {
Tags.insert({name: "Default tag"});
}
});
And in Tags-collection's schema:
creatorName: {
type: String,
optional: true,
autoValue: function() {
if (Meteor.user() && Meteor.user().profile.name)
return Meteor.user().profile.name;
return undefined;
}
}
Now when starting the server, if no tags exist, an error is thrown: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
So in other words calling Meteor.user() on the server startup throws an error instead of returning undefined or null or something. Is there a way to determine whether it will do so prior to calling it?
I cannot solve this simply by wrapping the call with if (Meteor.isServer) within the autoValue function, as the autoValue functions are normally called from server side even when invoked by the user, and in these cases everything in my code works fine.
Note that this is related to How to get Meteor.user() to return on the server side?, but that does not address checking if Meteor.user() is available in cases where calling it might or might not result in an error.
On the server, Meteor.users can only be invoked within the context of a method. So it makes sense that it won't work in Meteor.startup. The warning message is, unfortunately, not very helpful. You have two options:
try/catch
You can modify your autoValue to catch the error if it's called from the wrong context:
autoValue: function() {
try {
var name = Meteor.user().profile.name;
return name;
} catch (_error) {
return undefined;
}
}
I suppose this makes sense if undefined is an acceptable name in your dummy data.
Skip generating automatic values
Because you know this autoValue will always fail (and even if it didn't, it won't add a useful value), you could skip generating automatic values for those inserts. If you need a real name for the creator, you could pick a random value from your existing database (assuming you had already populated some users).
Been stuck with this for two days, this is what finally got mine working:
Solution: Use a server-side session to get the userId to prevent
"Meteor.userId can only be invoked in method calls. Use this.userId in publish functions."
error since using this.userId returns null.
lib/schemas/schema_doc.js
//automatically appended to other schemas to prevent repetition
Schemas.Doc = new SimpleSchema({
createdBy: {
type: String,
autoValue: function () {
var userId = '';
try {
userId = Meteor.userId();
} catch (error) {
if (is.existy(ServerSession.get('documentOwner'))) {
userId = ServerSession.get('documentOwner');
} else {
userId = 'undefined';
}
}
if (this.isInsert) {
return userId;
} else if (this.isUpsert) {
return {$setOnInsert: userId};
} else {
this.unset();
}
},
denyUpdate: true
},
// Force value to be current date (on server) upon insert
// and prevent updates thereafter.
createdAt: {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
},
denyUpdate: true
},
//other fields here...
});
server/methods.js
Meteor.methods({
createPlant: function () {
ServerSession.set('documentOwner', documentOwner);
var insertFieldOptions = {
'name' : name,
'type' : type
};
Plants.insert(insertFieldOptions);
},
//other methods here...
});
Note that I'm using the ff:
https://github.com/matteodem/meteor-server-session/ (for
ServerSession)
http://arasatasaygin.github.io/is.js/ (for is.existy)

Categories