Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Usage with non-persisted entities #20

Closed
aribouius opened this issue Oct 13, 2017 · 2 comments
Closed

Usage with non-persisted entities #20

aribouius opened this issue Oct 13, 2017 · 2 comments

Comments

@aribouius
Copy link
Contributor

Does this library support rendering resources that are not backed by a database model?

For example, how would one go about creating an endpoint (in rails) that handled exchanging access tokens (e.g. a short lived token for an extended one) for Facebooks OpenGraph API?

It looks like I can access the POST data via deserialized_params.attributes (bad idea?), but I am unsure how to render the results. Creating a custom resource adapter seems like it might get me there, but also does not seems appropriate for this use case.

@richmolj
Copy link
Contributor

Does this library support rendering resources that are not backed by a database model?

Absolutely. Here's some pseudo code:

# some unpersisted object
class Credentials
  attr_accessor :email, :password

  def initialize(attrs)
    attrs.each_pair { |k,v| send("#{k}=", v)
  end

    # this is the only code related to lack of persistence
  def id
    @id ||= SecureRandom.uuid
  end

  def token
    # your logic to mint the token
  end
end

# app/resources/credential_resource.rb
class CredentialResource < ApplicationResource
  type :credentials
  model Credential

  # require this in an initializer
  # we're setting a pass-through adapter bc we'll handle it ourselves
  use_adapter JsonapiCompliable::Adapters::Null

  # these attrs will be whitelisted from strong_resources
  def create(attrs)
    credentials = Credential.new(attrs)
    raise "nope!" unless credentials.valid?
    credentials
  end
end

Further reading:

Let me know if you have any trouble. Also feel free to email richmolj@gmail.com for a slack invite where you can get help for stuff like this.

@aribouius
Copy link
Contributor Author

Fantastic, thanks @richmolj!

richmolj added a commit that referenced this issue Jan 6, 2019
richmolj added a commit that referenced this issue Jan 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants