BlairAllegroTech / js-data-jsonapi

JsonApi Adapter for js-data
MIT License
15 stars 5 forks source link

Allow HttpAdapter To Be Injected Rather Than Creating Internally #13

Closed BlairAllegroTech closed 8 years ago

BlairAllegroTech commented 8 years ago

This feature would be useful for say:

rgant commented 8 years ago

That would be great.

I've tried to create a Provider for DSJsonApiAdapter in AngularJS using $http:

angular.module('js-data').provider('DSJsonApiAdapter', function () {
    var _this = this;
    _this.defaults = {};
    _this.$get = ['$http',function ($http) {
        _this.defaults.http = $http;
        return new DSJsonApiAdapter.JsonApiAdapter(_this.defaults);
    }];
});

But I had difficulties and I ended up not using $http:

angular.module('js-data').provider('DSJsonApiAdapter', function () {
    var _this = this;
    _this.defaults = {};
    _this.$get = [function () {
        return new DSJsonApiAdapter.JsonApiAdapter(_this.defaults);
    }];
});

So that later on I could specify which endpoints urls to use in the config:

.config(function(DSJsonApiAdapterProvider) {
    angular.extend(DSJsonApiAdapterProvider.defaults, {
        basePath: '/v3',
        httpConfig: {
            baseURL: 'https://stage-api.trueimpact.com'
        }
    });
})
BlairAllegroTech commented 8 years ago

This has actually been implemented since 0.0.0-alpha.9

.run(function(DS, DSHttpAdapter) {

    var options = {adapter:DSHttpAdapter};
    var adapter = new DSJsonApiAdapter.JsonApiAdapter(options);
    DS.registerAdapter('jsonApi', adapter, { default: true });
}

But there are still some things i'm not quite happy with, the main point being that it alters the DSHttpAdapter's behaviour!

// Override default get path implementation
        this.adapterGetPath = this.adapter.getPath;
        this.adapterHTTP = this.adapter.HTTP;

        // Override Get Path
        this.adapter.getPath = (method: string, resourceConfig: JSData.DSResourceDefinition<any>, id: Object, options: JSData.DSConfiguration): string => {
            return this.getPath(method, resourceConfig, id, options);
        };

        // Override HTTP
        this.adapter.HTTP = (options: Object): JSData.JSDataPromise<JSData.DSHttpAdapterPromiseResolveType> => {
            return this.HTTP(options);
        };