Frage

I have a Rails 4 based API that uses Devise for authentication and requires a user_token and user_email for each api call to be authenticated. The credentials sent are based on the user using the app at the time.

I am using Spine.js for my front end and would like some advice on what the best way would be to include these additional params into each AJAX call made by the client-side.

Within Spine, i have a Session model which is persisting (to local storage) the required details returned by my API when a user signs in.

A couple of approaches have crossed my mind…

Via the @url property, but i'd need to fix this up to work in each model, like so…

class User extends Spine.Model
  @configure 'User', 'name', 'email', 'image_url' 
  @extend Spine.Model.Ajax

  @url: '#{Spine.model.host}/users/?user_token=foo&user_email=bar'

…maybe a more suitable method would be to create a base model which extends the @url method and appends these params each time. Each of my other models could then inherit from this base model to DRY things up a bit.

Similar to above, i could extend each of the model functions i use to append these additional params each time an API call is made. For example, i could look at extending the @fetch() function. Something like this…

class User extends Spine.Model
  @configure 'User', 'name', 'email', 'image_url'
  @extend Spine.Model.Ajax

  @fetch (params) ->
    params or= 
      data: {user_token: 'foo', user_email: 'bar'}
      processData: true

    super(params)

Or my 3rd thought was whether i could extend Spine.Model.Ajax to append my additional params to the end of each api call, abstracting it away from the Models completely so i don't need to extend any of the model functions or even use the @url property because by default it works how i need it to, except for these additional credentials i need to send.

Alternatively my approach might be completely wrong and i might be overlooking something far simpler (i hope so).

Disclaimer: i've not tested any of the above code, just jotted it down during my thought process.

An example of one of my HTTP calls (in dev for the time being) is: http://dev.myapp.com:5000/api/v1/posts?user_token=foobar&user_email=foo@bar.com

War es hilfreich?

Lösung

I've approached this problem using the jQuery $.ajaxSetup() function that i stumbled upon the other day. My code looks like so:

settings =
        data:
          user_email:'foo@bar.com'
          user_token:'foobar'

$.ajaxSetup settings

I have bound this to the 'create' event on my Session model in Spine so it's invoked as soon as a Session has been saved to Local Storage. That way my proceeding AJAX calls are all appended with the additional data params i needed to send through.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top