3

I'm implementing this API and the first thing I did was the login with access token. I'm using the jsonapi-resources gem https://github.com/cerebris/jsonapi-resources

I have two problems now. I want to return a user AND the generated access token in case of success and a failure message otherwise.

Now I got two problems:

1- The first one is, how can I return this kind of data (the User record PLUS the access token). Reading the JSONAPI specification I believe a compound document would be the way to go, but how can I do it with this gem

2- How can I respond, with this gem, to a non-CRUD route like login? Do I have to make something in the controller? And how can I handle a resource object in this case?

Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120
  • Two questions - 1.) why do you want to return the access token when you're querying for users (you should have that stored somewhere client-side) and 2.) what are you using for authentication (i.e. Devise, OAuth, etc.)? – jeffdill2 Jul 10 '16 at 02:06

1 Answers1

1

There is no such thing as non-resource data. You can model pretty much everything in terms of resources.

Those resources do not have to map directly to tables or even exist as identifiable entities in your persistence layer. From an api consumer's perspective it is mostly irrelevant whether or not the resource representation is an actual database row or document or a entirely abstract entity conjured on demand.

Implementing Abstract resources using JR is straightforward and is supported out of the box:

Abstract Resources

Resources that are not backed by a model (purely used as base classes for other resources) should be declared as abstract.

Because abstract resources do not expect to be backed by a model, they won't attempt to discover the model class or any of its relationships.

Now, coming back to your use cases:

  1. This can be modelled as an AuthToken resource (with a single attribute) that is related to (many-to-one association) a User resource. And in your case it may happen that your user resource is included along with the AuthToken resource in the same API response.

  2. Again, if you model your entire domain around resources, any and all actions can be modelled as CRUD actions. Login is just creation of a UserSession resource.

JSON:API specification allows inclusion of related resources:

Inclusion of Related Resources

An endpoint MAY return resources related to the primary data by default.

An endpoint MAY also support an include request parameter to allow the client to customize which related resources should be returned.

And this feature is fully supported by JR as well.

lorefnon
  • 12,875
  • 6
  • 61
  • 93