How to fire a get request between rails and ember - javascript

I am new to frontend development,I am using rails and ember to built a sample app .
in rails , i have a function as below
def get_id
first_id = User.first.id
render json: { id: first_id , type: "master"}
end
I want to fire a GET request from ember side to call the get_id in ember side which will return the required response . thanks .

Assuming you have your User models defined in both your Rails and Ember apps, you have a Rails DB seeded with User objects, and you're using Ember Data within your Ember application, to actually make a GET http request you would theoretically need to make this call:
this.store.findRecord('User', id);
Where id is the id of the User you'd like to retrieve.
If you need more guidance on setting up your models, etc. this guide would be a great place to start: https://emberigniter.com/modern-bridge-ember-and-rails-5-with-json-api/

Related

How to get connection count to a specific stream within ActionCable?

Background: I'm working on an app that has a JS frontend, and a Rails backend. I've been able to successfully create a vanilla JS websocket client, that properly connects to and receives broadcasts from a Rails Actioncable-enabled websocket server.
The Problem and TLDR:
I'm trying to get the total count of clients that connected and passed in specific data upon connecting.
Details:
For example, say I have something like this:
//Client waves to server, says where they are from by passing in country to say_hi method on backend
const wave = {
command: 'message',
identifier: JSON.stringify({
channel: 'CountryChannel',
}),
data: JSON.stringify({
action: 'say_hi',
country: "USA",
}),
};
socket.send(JSON.stringify(wave));
Respectively, on the backend I have a say_hi method that is able to get my passed in country value.
class CountryChannel< ApplicationCable::Channel
def subscribed
stream_from 'country'
end
def say_hi(data)
#country = data['country'] ##country = "USA"
end
end
So I now want to be able to somehow see the amount of waves from "USA".
I'm a complete beginner in Rails, and have been going down the ActionCable docs rabbit-hole. I tried searching SO for anything like this online and found:
ActionCable - how to display number of connected users?
My problem with this is the approved answer (along with its caveats) would show the count of "all" the connection on that stream, whereas I want to segment that based on the data.
On the same link, I also saw an answer where you could use the :identified_by param in Connection object. My issue with that is I just can't figure out anywhere how to set that from my client. Again, I'm a noob at all this so it's probably straightfoward, but I've just been unable to connect the dots.
I know that I could approach this by creating specific streams based on a parameter and have something like:
stream_from "country#{#country}" # streams country#USA
But I'm lost as to see the amount of clients that are currently receiving broadcasts on this stream, or something like that. Specifically, I just don't know what to use from ActionCable to be able to do this.
Any ideas? I'd love to further specify or provide any more info if needed. Just feel free to ask. Thanks!

What is the right way to upload images to server (or S3) in Ember.js?

I have application built on Ember.js (2.13). I have User model and at this moment I work on avatar upload feature. When I modify model and save it then Ember makes PATCH request to my API during it Ember serializer builds nice json-api object and I like it.
When I need to upload image to server I need to make some PUT request to my API with file data I could use jQuery ajax for this. Server will resize and crop image and save it on disk or push it to S3 bucket. But I do not like this way because this request will be created bypassing Ember's serializer and without references to model. So I need to set uploaded filename to User model and save it then I'll have redundant request to server.
I have an idea to transform file to base64 string in Ember.js app and set this string to User model and save it. In this case I'll have one request to server. Is this good way to upload file?
Please advice best practice of uploading files in Ember.js application.
But I do not like this way because this request will be created
bypassing Ember's serializer and without references to model.
There is nothing you can do about this - ember data does not support files. And in many situations ED is not good enough (for example - nested resource URIs, partial updates). I suggest to not be bothered about it too much - if your can't perform some request using ember data, just use Ember.$.ajax.
So I need to set uploaded filename to User model and save it then I'll
have redundant request to server.
No, you don't. Just configure your backend to return full user model (as you do for other get/post/update requests which use ED), and pass result (if request was successful, of course) to pushPayload method of the store. Store will be updated with actual data without additional requests. Example:
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
const headers = {};
headers[headerName] = headerValue;
/*Instead of data object, you will create a formData*/
const data = {
/*Some data*/
};
Ember.$.ajax(
{
url: '/path-to-resource/id-of-resource',
headers,
type: "PUT",
data
}
)
.then(
(payload) => {
this.store.pushPayload(payload);
},
(response) => {
this.set('errorMessage', stringifyError(response));
}
)
.always(() => {
this.set('isLoading', false);
});
});
UPD: There is an addon, ember-cli-form-data which claims to add support of file upload to ember data. I didn't try it myself, so can't say if it works and how good.
You can give it try using popular ember addon for this.
ember-plupload and ember-uploader addon

How to set Backbone.js to include model name in JSON post?

I've been working on a Backbone.js project that syncs to a Google App Engine REST server I've also put together. I'm using the Appengine-Rest-Server project code to enable the REST interface. IT works really well, but there is one problem. When I post a new model to it, it expects a JSON post in the form of:
{ 'modelname' : {'attribute1':'attribute','attribute2':'attribute'}}
When I use python and the requests library to POST this data to my REST server... it works fine.
Backbone.js appears to be sending POST requests without the model name a la
{'attribute1':'attribute','attribute2':'attribute'}
Now, not being an expert on what formats are 100% RESTful, I'm not sure whether my REST server is improperly configured (in which case I don't expect you guys to be able to help with the code), whether Backbone.js is improperly configured, or whether both formats are potentially RESTful and I just need to figure out how to get backbone to add in the model name.
So, to close, is one or both of these formats compatible with a truly RESTful API? If requiring the model name in the JSON is not a gross violation of making a RESTful API, does anyone know how I can make Backbone send out post requests in the proper format?
Thanks!
Most elegant way:
YourModel = Backbone.Model.extend({
name: 'modelName',
toJSON: function () {
var data = {};
data[this.name] = _.clone(this.attributes); // or Backbone.Model.prototype.toJSON.apply(this)
return data;
}
});
Or you can directly pass data to the options
model.save(null, {
data: {
// custom format
}
});

Access Devise user from AngularJS?

I have a Rails application which uses AngularJS on the front-end. I also have a route in the format "/api/:user_id/submissions/:id" to access specific submissions from a user. On the front-end I'd like to display each post from the Devise user that is currently logged in, and only their posts. I have created both an Angular factory:
var brainDB = angular.module('brainDB',['ngResource']).factory('userSubmission', function($resource){
var service = $resource('/api/:user_id/submissions/:id', {user_id: '#user'}, {id: '#id'} );
return service;
And have it scoped to my controller:
brainDB.controller('SubmissionsCtrl',['$scope', 'Submission', 'userSubmission',
function($scope, Submission, userSubmission){
$scope.submissions = Submission.query();
$scope.userSubmissions = userSubmission.query();
}]);
The only problem is that the factory at the top doesn't work. I can output every single submission in my database, but I don't know how to tell Angular what the user_id of the current_user is. I have a submissions.rb controller with an action which successfully pulls all of the posts for the specific user from my route, "/api/:user_id/submissions/" but like I said I don't know how to tell Angular what the current_user.id is because current_user can only be accessed from Rails.
I've been trying to solve this for a week now and haven't found much help through Google searches. Any advice is greatly appreciated.
My own app has another server endpoint call defaults & angular service Metadata that gets initialized in an angular .run() block. This block pulls a currentUser object back (with other metadata) to initialize $rootScope variables. From there, I can call other angular services with: userSubmission.query({user_id: $rootScope.currentUser.id}); etc. in my angular controllers.
Another option would be to generate metadata content in a javascript file with all your metadata (i.e. metadata.js.erb in which you let rails populate variables (using <%= =>) that are available to your whole angular app.
Hope that helps.

Ember.js ember-data findAll objects on the remote server

Folks! Are there any examples of how ember-data and remote back-end server works together (separate applications - client-side with ember.js and abstractive back-end server, Rails for example)?
And the second question here - how to make array attribute (array of objects) with ember-data model?
There is a guide on the Ember site, which provides a great explanation;
http://emberjs.com/guides/models/finding-models/
If you're using Rails you will probably be using the REST Adapter
http://emberjs.com/guides/models/the-rest-adapter/
This is a fully-functioning Ember app that uses ember-data and Rails:
https://github.com/dgeb/ember_data_example/
The last example may look like the application is integrated, but the client-side and back-end are completely separate. To change where the adapter expects to be sending data you can define a namespace and /or a url in your adapter:
App.Adapter = DS.RESTAdapter.extend({
url: "http://www.domain.com/path/to/remote_app/",
namespace: "api/v1"
});

Categories

Resources