How to only use a certain dict from a get request with Backbone? - javascript

I have exposed to Backbone an API that returns user profiles with this structure:
{id: 1, following: {...}}. I only want to use the dictionary inside of the "following" attribute. How would I do that? Right now, I have a model with a URL to the API. I have a collection that uses this model. I do a fetch() on the collection, but I only want to use the dictionary inside of "following".

You should use parse to extract what you want from the the response:
parse model.parse(response)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
So you'd want something like this in your model:
parse: function(response) {
return response.following;
}

Related

How to parse node js response of mongodb data in angular?

I've an http server in node [not express]. On button click I've a get method, which then pulls documents from mongodb (using mongoose) and displays it on angular page.
on button click:
$http.get('/get').success(function(response){
console.log(response);
//logic to store JSON response of database and perform repeat to display each document returned on UI
});
In Node code where server is created using http.createServer instead of express:
if(req.url==="/get"){
res.writeHead(200,{'content-type':'text/plain'});
modelName.find({}, 'property1 prop2 prop3', function(err,docs){
res.write('response...: '+docs);
});
}
Here is my issue:
I'm able to send response from node js to angular js but how to parse it? If I don't add 'response...:' before docs then I get an error msg 'first argument should be a string or buffer'. On angular I get response like:->
response...:{_id:....1, prop1: 'a',prop2: 'b',prop3: 'c'},
{_id:....2, prop1: 'ab',prop2: 'bc',prop3: 'cd'}
I want to display documents as a tabular format
I don't know your exact setup, but I think you should transfer application/json instead of text/plain.
You cannot simply concatenate a string to docs, you need to return either only just docs (to transfer as an array) or write res.write({'response':docs}) (to transfer as an object).
Consider moving from $http to a resource service. In your resource service, you need to set isArray to false if you want to transfer as an object or to true if you transfer as an array: https://docs.angularjs.org/api/ngResource/service/$resource

Ember data - One model, two endpoints

In ember data, if you want to fetch the collection of a model, it's convention to use this:
this.store.findAll('order');
or with a filter, this:
this.store.find('order', {shopId: 63});
So you pass the model name, and Ember-data will build the URL for you, which would look something like (depending on your adapter):
GET /api/orders
GET /api/orders?shopId=63
So this does two things
Build the URL to fetch data from the api
Map the collection as JavaScript objects, using the model that you passed as 1st argument
But what if I want to fetch orders from two URLs; /api/orders and /api/new_orders ?
The first one will work as usual: this.store.findAll('order'), but is there a way to override the api path that you fetch from?
Maybe something like this.store.find('order', {path: '/new_orders'})?
So that I can end up with a collection of objects modelled with my order model, but fetched from a different route
You need to have a rest adapter for this store and override the findAll method. The default implementation is as such
findAll: function(store, type, sinceToken) {
var query, url;
if (sinceToken) {
query = { since: sinceToken };
}
url = this.buildURL(type.modelName, null, null, 'findAll');
return this.ajax(url, 'GET', { data: query });
}
buildUrl will return a proper endpoint for your first url. you could then parse this url and modify it to make a second request with the same data, but with to your second endpoint. Than you could merge the responses or use them separately.
Reference: https://github.com/emberjs/data/blob/v1.13.5/packages/ember-data/lib/adapters/rest-adapter.js#L398

Send javascript array object to ashx

I have an array of objects in javascript and I like to send this object to the server in a post request to ashx handler
I'm sending the information with this script:
var filtersArray = [{id:1, val:"filter1"}, {id:2, val:"filter2"}];
var object = {filters: filtersArray, id: 123, name: "object"};
$.post('handler.ashx', jQuery.param(object), function () {
//do some stuff
});
I can see in the chrome console the network params
Form Data
filters[0][id]:1
filters[0][val]:filter1
filters[1][id]:2
filters[1][val]:filter2
id:123
name:object
And in the handler I want to retrieve the parameter filter as an array, list or something.
I tried to do this: context.Request("filters[]") but the response is Nothing to retrieve the value I have to context.Request("filters[0][id]")
But this is not useful because the size of the list could be different in each request and with this solution I should have to add a parameter with the size and iterate parameters with this number.
Another option will be transfor to a JSON object and later deserialize the object in the server. But I prefer to not do that.
There is any other way to do this?

Fetch Backbone Collection by Model IDs list

I have a REST API serving a few URLs:
/rest/messages
provides all messages. A message is a JSON/Backbone Model
{
title: 'foo',
body : 'bar'
}
To get a single message I have:
/rest/messages/:id
Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.
I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this.
Thanks
According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.
For example (when doing fetch),
collection.fetch({
data : {
message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
}
})
This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.
You can use any data structure instead of array to send message_ids.
The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:
var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();
You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3
Hope this helps!

How to get the id when I create a save a new model

In my Marionette.CompositeView it will be possible to create a new model making a put request to the server(1).
The put request is ok, but when I add the new model to the collection, the new model misses the id which is created by the server.
How should I fix this issue?
Should
1) the POST request send the id to the client or
2) I have to make another request from the client to get the id?
(1)
return Marionette.CompositeView.extend({
submitForm: function (event) {
this.textAreaElement = this.$el.find('[data-tid="announcement"]');
this.messageModel = new MessageModel();
this.messageModel.save({
message: this.textAreaElement.val()
}, {
wait: true,
success: this.onSuccess,
error: this.onError
});
},
onSuccess: function () {
console.log(this.messageModel.get('id')); // undefined
this.collection.add(this.messageModel); // I need to get also the id of the following model
// which is created by the server
}
});
Your server needs to respond to the POST with JSON representing the saved model, including the ID (or just the the ID). For example, return {"id": "123"} and backbone will update the model for you.
In the options you pass to save() add wait:true. The attributes of the model (including id) will then be set to whatever json object the server returns for this request.
Backbone->Create and of course, like #Robert said, you can add wait:true so that your view is not updated until the server sends back your model (including the ID)

Categories

Resources