ember.jspromiseasync-awaitaws-amplifyamplifyjs

Ember promise aware headers in Adapter


Looking for a way to set header in Ember ADAPTER LATER with the value returned from an async call.

Trying to set the idToken returend from Amplify's Auth.currentSession(), which is a promise function which internally handles refreshing the token on expiration.

Something like this to await the response -

headers: computed(async function() {
        return {
          'Authorization': await Auth.currentSession().getIdToken();
        };
      })

.

.

I see that we can't make a promise aware computed property too for headers.

Also I am not looking for a solution using ember-simple-auth / ember-cognito or any other addons, I need to achieve this just with plain amplify library and Ember adapters header 😟.


Solution

  • A possible solution is to override the adapter's ajax method.

    import DS from 'ember-data';
    
    export default DS.RESTAdapter.extend({
        async ajax(...args) {
            // Store the parent call, so it can be called after getting the current session.
            const _super = this._super.bind(this);
    
            // Sorry, I'm unfamiliar with how you're accessing amplify
            const headers = await amplify.currentSession();
    
            this.set('headers', {
                'Authentication': headers.auth
            });
    
            return _super(...args);
        }
    });