Falcor Router set method - falcor

In my Router I have a set route like:
{
route: 'profile.["language"]',
async set(jsonGraph) {
console.log(jsonGraph);
// do async stuff w/database
return {
path: ['profile', 'language'],
value: 'test'
};
}
}
The general idea with this route is to set the profile of a user.
For testing purposes I just want to return the value 'test' on profile.language
The problem is I get a 500 internal server error with model.setValue('profile.language', 'english').then(done => console.log(done))
What's wrong with my route code? I can't find the problem...
ps: the async set(jsonGraph) is es7 await/async syntax.

After wasting a few hours on this, I found the solution:
In my server.js
import bodyParser from 'body-parser';
app.use(bodyParser.urlencoded({extended: true}));
Express couldn't parse the incoming request, that's why I got a 500 internal server error.
Gotta love the fragility of javascript :)

Related

laravel jetstream request api route middleware protected api:sanctum return unauthenticated response

I have a problem with 'domain' => env ('SESSION_DOMAIN', null) in the session.php file. When set SESSION_DOMAIN value in .env file, for example
SESSION_DOMAIN=mysite.test
login don't works and there seems to be a middlaware.
If not set this parameter, login work fine, therefore when I call api protected route with sanctum maiddleware ex.
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/myroute', function () {
return 'hello world!';
});
});
I have unauthenticated response.
If use web.php file route and insert the same function:
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/api/myroute', function () {
return 'hello world!';
});
});
with api prefix, its works fines.
I followed laravel 8.x sanctum documentation https://laravel.com/docs/8.x/sanctum. In laravel projects 7.* without jetstream I had no problem.
There's any suggest or explaination for this phenomenon.
Any explanation would be helpful for me! Many Thanks.
I ran into a similar issue where I could not authenticate any API request from my frontend. Turns out the generated Kernel.php did not include the Sanctum middleware for session cookies by default - you have to add it manually in your app/Http/Kernel.php:
'api' => [
EnsureFrontendRequestsAreStateful::class, // <- Add and import this middleware
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
After doing this API requests from my frontend are working again. Maybe this resolves your issue as well.

How do I get Laravel to listen to private Pusher channels?

I read a few other questions similar to this but wasn't able to find a satisfactory answer, so just asking again with what I have done in my code so far.
in resources/assets/bootstrap.js I have
window.Echo = new Echo({
broadcaster: 'pusher',
key: '8c5cc1d9fe77464ac2df',
cluster: 'us2',
encrypted: true,
authEndpoint: '/chat4/public/authenticate-broadcasting',
});
and in my routes/web.php I have:
Route::post('/authenticate-broadcasting', function () {
return true;
});
but when I load the application page, in console I get:
POST http://laraveldemo-one.com/chat4/public/authenticate-broadcasting 500 (Internal Server Error)
Pusher : Couldn't get auth info from your webapp : 500
I installed Laravel Echo and Pusher correctly because if I use public channels, my application works perfectly, but I'm failing miserably using private channels, I'm not sure what else I can try as I have read thru the documentation a few times and can't find anything I'm missing. Help me please! :)
You must send csrf_token
You can send via meta tags or in Echo json parameter with
auth: {
headers: {
'X-CSRF-Token': 'some_csrf_token'
}
}
https://pusher.com/docs/client_api_guide/client_connect

EmberJS getting user profile information

In my Rails API I am using JSONAPI structure which Ember expects by default.
I have a Rails route http://localhost:3000/profile which will return the currently logged in user JSON.
How do I make an arbitary request to this /profile endpoint in Emberjs so I can get my logged in user's JSON in my router's model() hook?
I tried following this guide here:
https://guides.emberjs.com/v2.10.0/models/finding-records/
And have this code:
return this.get('store').query('user', {
filter: {
email: 'jim#gmail.com'
}
}).then(function(users) {
return users.get("firstObject");
});
It is returning the incorrect user however. It also seems like it doesn't matter what the value of 'email' is, I can pass it 'mud' and it will return all users in my database.
Is there no way for me to make a simple GET request to /profile in my model() hook of my profile route in Ember?
Update
It has come to my attention that the filter thing in Ember is actually just appending a query parameter onto the end of the request URL.
So having my above filter, it would be like making a request:
GET http://localhost:3000/users?filter['email']=jim#gmail.com
Which doesn't help because my Rails doesn't know anything about filter query parameter.
I was hoping Ember will automatically find the user and do some black magic to filter the user to match email address for me, not me having to manually build extra logic in my Rails API to find a single record.
Hurrmmmmmmm...sure feels like I'm fighting against the conventions of Ember at the moment.
Update
Thanks to Lux, I finally got it working with the following approach:
Step 1 - Generate the User adapter:
ember generate adapter user
Step 2 - write the AJAX request in the queryRecord method override for User adapter
import ApplicationAdapter from './application';
import Ember from 'ember';
export default ApplicationAdapter.extend({
apiManager: Ember.inject.service(),
queryRecord: function(store, type, query) {
if(query.profile) {
return Ember.RSVP.resolve(
Ember.$.ajax({
type: "GET",
url: this.get('apiManager').requestURL('profile'),
dataType: 'json',
headers: {"Authorization": "Bearer " + localStorage.jwt}
})
);
}
}
});
Step 3 - make the model() hook request like so:
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.get('store').queryRecord('user', {profile: true});
}
});
Well, query is for server side filtering. If you want it client-side use something like store.findAll('user').then(users => users.findBy('email', 'bla#bla.bla'));.
But this is not what you want. You have your server side filter. It's just under /profile. Not under /user.
However interesting is what /profile actually responds. A single-record-response or a multi-record-response. The best would probably a single-record-response since you only want to return one user. So how can we do this with ember? Well, we use store.queryRecord().
And because ember does not know anything about /profile we have to tell it ember in the user-adapter with something like this:
queryRecord: function(store, type, query) {
if(query.profile) {
return Ember.RSVP.resolve(Ember.$.getJSON('/profile'));
}
}
And then you can just return store.queryRecord('user', { profile: true })

Dart Restful Server doesnt show response data

I was not 100% sure on how to create a Restful Dart API I can make calls to, but i wanted to try. I wrote the following code:
import "package:rpc/rpc.dart";
import "dart:io";
final ApiServer _apiServer = new ApiServer(prettyPrint:true);
main() async{
_apiServer.addApi(new TestServer());
HttpServer server = await HttpServer.bind(InternetAddress.ANY_IP_V4, 8088);
server.listen(_apiServer.httpRequestHandler);
print('Server listening on http://${server.address.host}:'
'${server.port}');
}
#ApiClass(name:'test_server', version: 'v1', description: 'This is a test server api to ping for some quick sample data.')
class TestServer {
#ApiMethod(method:'GET', path: 'users')
List<User> getUsers(){
List<User> users = new List<User>();
return users;
}
#ApiMethod(method: 'GET', path: 'users/{id}')
User getUser(int id){
User u;
///TODO: Guts of User.
u = new User(id, "f_test_$id", "f_test_$id");
return u;
}
#ApiMethod(method:'POST', path: 'users/user/{id}/add')
User postUser(int id, UserData usr){
User u;
///TODO: Post the user.
u = User.fromUsrData(usr);
return u;
}
}
It is a pretty simple, small one which isnt actually doing anything.
When I run the dart file it will say something like:
Observatory listening on http://127.0.0.1:64969
Server listening on http://0.0.0.0:8088
So it makes me believe that i should be able to ping the server in localhost. I make a call in my browser to http://localhost:8088/test_server/v1/users
and it says: {"error":{"code":400,"message":"Invalid request, missing API name and/or version: http://localhost:8088/."}} which confuses me.
Did i do something wrong somewhere in my definition or how to access the localhost API?
EDIT It seems that when I go to that URL, it sits in a perpetual state of pending. It doesnt do do anything other than that.
After a deeper understanding of the issue, changing the name around etc, It seems that my server was having some issues so i needed to end the Dart execution, and restart the server.
When trying to go to the link again: http://localhost:8088/test/v1/users
it worked exactly as it should.

Restangular PUT not appending the id in the request

I've got an AngularJS App using Restangular for persistence on top of a Rails 4 API. I've run into a problem with my updates not working.
My code in the routeProvider:
when('/course/edit/:courseId', {
controller: 'CourseEdit',
templateUrl: '/assets/templates/course/form.html',
resolve: {
course: function(Restangular, $route) {
return Restangular.one('courses', $route.current.params.courseId).get();
}
}
})
My controller function:
function CourseEdit($scope, $location, course) {
$scope.course = course;
$scope.save = function() {
$scope.course.put().then(function() {
$location.path('/course/view/' + $scope.course.id);
});
};
}
The request for the PUT is being made to http://mysite.com/courses rather than http://mysite.com/courses/id
like I expected it to be, and I can't seem to figure out why.
The error that rails throws out is 'No route matches [PUT] "/courses".
Any help would be greatly appreciated.
I managed to figure it out by poking around at my set up a bit more. I had copied some config for Restangular from a tutorial that I'd found, without really examining whether or not all pieces were necessary.
In my config()
RestangularProvider.setRestangularFields({
id: '_id.$oid'
});
That doesn't match what my fields are in my API, and was the culprit for the problems that I was having. I ended up removing that, leaving only the config for setBaseUrl and it started working again.
Hopefully this will help someone else out who's struggling from the same blindness that I was.

Resources