Persisting a backbone model and the id - backbone.js

Let's assume we create a new model class an instanciate a person using it:
var User = Backbone.Model.extend({
urlRoot: '/user'
});
var nou = new User({
name: "nourdine"
});
Now, of course, we want to persist it. Not having added an id backbone will create a POST request and communicate the server the intention to create an entity under /user containing the data {name: "nourdine"}. Here's how we do it:
nou.save(null, {
success: function (model, response, options) {
// ... what do I do here?
}
})
The server will now create a record in the db containing the JSON data rearranged in some form and assign an ID to it. NOW:
1 - What is the server suppose to return in the HTTP response? A JSON containing the JSON provided by the clinet + the newly created fields, namely the ID of the new record?
2 - who is going to update the model in the client with these data? Me? Matter of fact I would like to tell the model in the client that a new ID has been assign to it by the server so that the next time I do user.save() I will obtain a PUT rather than a POST. But who is supposed to update the model in the client?
Thanks

so this is my work flow for this
client -> create model and populate with data
client -> save model (model.save())
server -> create server side version of model using data, assign an id
server -> respond with success and the id of the newly created model
client -> in the success set the id to the one passed back
now the only potential issue i have with my work flow is if something did not get set in the server successfully but the model was still created, my client model would not reflect that of the server anymore, but i minimize this by returning error if the model could not be created exactly as passed.
And now i am able to call model.save() again this time having the id so initiating a PUT request

From the documentation to a Backbone.Model
After a successful server-side save, the client is (optionally) updated with the server-side state.
So if you return a valid JSON your model will be updated automatically

Related

Meteor - How safe it is?

I'm actually creating my first app using meteor, in particular using angular 2. I've experience with Angular 1 and 2, so based on it. I've some points of concern...
Let's imagine this scenario...My data stored on MongoDb:
Collection: clients
{
name : "Happy client",
password : "Something non encrypted",
fullCrediCardNumber : "0000 0000 0000 0000"
}
Now, on my meteor client folder, I've this struncture...
collection clients.ts (server folder)
export var Clients = new Mongo.Collection('clients');
component client.ts (not server folder)
import {Clients} from '../collections/clients.ts';
class MyClients {
clients: Array<Object>;
constructor(zone: NgZone) {
this.clients = Clients.find();
}
}
..and for last: the html page to render it, but just display the name of the clients:
<li *ngFor="#item of clients">
{{client.name}}
</li>
Ok so far. but my concern is: In angular 1 & 2 applications the component or controller or directive runs on the client side, not server side.
I set my html just to show the name of the client. but since it's ah html rendering, probably with some skill is pretty easy to inject some code into the HTML render on angular to display all my fields.
Or could be easy to go to the console and type some commands to display the entire object from the database collection.
So, my question is: How safe meteor is in this sense ? Does my concerns correct ? Is meteor capable to protect my data , protect the name of the collections ? I know that I can specify on the find() to not bring me those sensitive data, but since the find() could be running not on the server side, it could be easy to modify it on the fly, no ?
Anyway...I will appreciate explanations about how meteor is safe (or not) in this sense.
ty !
You can protect data by simply not publishing any sensitive data on the server side.
Meteor.publish("my-clients", function () {
return Clients.find({
contractorId: this.userId // Publish only the current user's clients
}, {
name: 1, // Publish only the fields you want the browser to know of
phoneNumber: 1
});
});
This example only publishes the name and address fields of the currently logged in user's clients, but not their password or fullCreditCardNumber.
Another good example is the Meteor.users collection. On the server it contains all user data, login credentials, profiles etc. for all users. But it's also accessible on the client side. Meteor does two important things to protect this very sensitive collection:
By default it only publishes one document: the user that's logged in. If you type Meteor.users.find().fetch() into the browser console, you'll only see the currently logged in user's data, and there's no way on the client side to get the entire MongoDB users collection. The correct way to do this is to restrict the amount of published documents in your Meteor.publish function. See my example above, or 10.9 in the Meteor publish and subscribe tutorial.
Not the entire user document gets published. For example OAuth login credentials and password hashes aren't, you won't find them in the client-side collection. You can always choose which part of a document gets published, a simple way to do that is using MongoDB projections, like in the example above.

Not getting a notification when trying to use real-time database communications

I'm trying to use web sockets to add a new notification to my app. I'm using Backand as my server, and can't seem to get a grasp on responding to the new event. Here's my server side code to send the event:
//Action: Update - After data saved and committed
function backandCallback(userInput, dbRow, parameters, userProfile) {
//Send to array of users
socket.emitUsers("new_notification",userInput, ["admins"]);
return {};
}
And my client code to receive it:
//Wait for server updates on 'items' object
Backand.on('new_notification', function (data) {
//Get the 'items' object that have changed
console.log(data);
});
But when I try to receive the event in my app code, I never see a notification of type "new_notification". Can someone please let me know what's going on?
Make sure you are using emitRole instead of emitUsers. The code above emits to a user array, but it looks like you want to send a notification to the "admins" role. Change this to emitRole() and you should be ok.
For role you want to keep it case sensitive so it will be:
socket.emitRole("items_updated",userInput, "Admin");
For users the syntax is:
socket.emitUsers("items_updated",userInput, ["user2#gmail.com","user1#gmail.com"]);

How to store and load the connections of jsplumb (Using AngularJS and jsPlumb)

Can pls anyone help me out how to store and load the connections, and anchor placements jsplumb and anjular js.
pls check the below image link
(http://i.stack.imgur.com/YC1PR.jpg).
1st one is the image without connections, second one with connections.
when i reload the page, still i need to get the connections in same places
Whenever a connection is established, "connection"(SOURCE) event is triggered. You need to store the connection endpoints details in that triggered function so that you can retrieve them later.
First make sure that you have set proper id for your endpoints. You can manually set at time of endpoint creation as:
var e0 = jsPlumb.addEndpoint("div1",{uuid:"div1_ep1"}), // You can also set uuid based on element it is placed on
e1 = jsPlumb.addEndpoint("div2",{uuid:"div2_ep1"});
Now bind the connection event where you will store the established connections info:
var uuid, index=0; // Array to store the endpoint sets.
jsPlumb.bind("connection", function(ci) {
var eps = ci.connection.endpoints;
console.log(eps[0].getUuid() +"->"+ eps[1].getUuid()); // store this information in 2d-Array or any other format you wish
uuid[index][0]=eps[0].getUuid(); // source endpoint id
uuid[index++][1]=eps[1].getUuid(); // target endpoint id
}
});
You can convert the array information to JSON format and store at the server side. When page is refreshed you need to retrieve the JSON data and restore the connection. For connecting the endpoints based on uuid make use of:
jsPlumb.connect({ uuids:["div1_ep1","div2_ep1"] });
Here is the jsFiddle for making connections based on endpoints.

Act upon response of AutoSync insert operation

I have a Store with autosync:true.
When loading the store, I'm getting complete models:
[{"id":11,"active":true,"name":"ABC","sens":7,"details":119,"type":13,"acl":false,"create":true,"delete":true,"owner":"alexander","members":"gustave\njerome"}]
When syncing a new model to the server, I'll send it with "id":0, so the server knows it has to create a new one. The server will then respond {"success":true,"data":[12],"debug":[]}, where 12 is the id of the newly created entry.
Now I have to add a callback function for the autoSync operation to patch the ids I receive back into the store.
If I had synced manually, this would have been easy:
Ext.getStore("RightsStore").sync({
success:function() {
}
})
But how can I get a special success or a callback function for insert syncs into a store that works with autoSync?
If the server sent {"success":true, "data"[{"id":12, ....}]} then you do not need to do anything. Best is if server sends back complete records it received for CRUD operation with the updated data (in same order). Ext takes care of the rest.
If you're unable to change the server output as #Saki had mentioned, you can just listen to the load event and update the records with the new id there.
store.on('load', me.loaded, me);
loaded: function(store, records) {
}
More details here - http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store-event-load

Get UserId from the Session Id and Server URL

I have a requirement, where I will be getting the Session Id and Server URL(parameters of a webservice method).
Say like this:
Session ID : 00D900000xxxxxx!ARUAQOb4VVoQR1UXlY_Hvuy1DdKdN6nSfnNJKYwPTF9R3tYuA2jzBsWXHIGDQUFL13iebnYSDKKC45H98TzVxxxxxxxxxx
Server URL :
https://ap1.salesforce.com/services/Soap/u/12.0/00D900000xxxxxx
Now i need to get the User Id(or any other user details) from these two.
Thanks in Advance!!
Nitin
You could use the SOAP API, which has a GetUserInfo method. Calling this method will return a GetUserInfoResult object, which will contain the user ID associated to the session.
Adam, GetUserInfo method requires existing connection object which we can create by calling method, so I applied the following code and now everything works fine!
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint("https://login.salesforce.com/services/Soap/c/24.0/");
config.setServiceEndpoint("https://na14.salesforce.com/services/Soap/c/24.0/00DXXXXXXXXXXXX");
config.setSessionId("00DXXXXXXXXXXXX!1AQ4AQO980Fmu25SOFQxxOlQN8zAaHOlnfdk._rZU2Vkf_CV0HJREqKavMLaPg9jtA9N517MNHLdLeF.aVkoZtnk2eu7u.XNn");
connection = new EnterpriseConnection(config); GetUserInfoResult
userInfo = connection.getUserInfo();
I used the same server URL and sessionId that I have received from query parameter string.

Resources