VasilioRuzanni / angular-modelizer

Simple and lightweight yet feature-rich models to use with AngularJS apps.
MIT License
26 stars 4 forks source link

Suggestion for a way to set global base URL or URL prefix #3

Closed tsak closed 3 years ago

tsak commented 10 years ago

I think it would be helpful to have a modelizeProvider.setGlobalUrlPrefix (or similarly named function) that would allow one to prefix all request URLs.

This would allow a more elegant solution for APIs that carry the version number in the URL, e.g. /api/v1 or APIs from a different host (CORS, I know), the latter currently not possible as far as I have tested.

angular.module('app')

  .config(function(modelizeProvider) {
    // Make all requests relative to `/api/v1`
    modelizeProvider.setGlobalUrlPrefix('/api/v1');
  });

  .run(['modelize', function (modelize) {
    modelize.defineModel('post', {
      baseUrl: '/posts' // would resolve to `/api/v1/posts` thanks to `setGlobalUrlPrefix` from above
    });
  });

Let me know if you think this makes sense. Happy to create a pull request.

VasilioRuzanni commented 10 years ago

@tsak Well, thats pretty common need and it is simple to build that into modelizer but its not there intentionally, because you can use Angular $http interceptors directly, e.g.:

angular.module('app')

  .factory('apiUrlHttpInterceptor', function () {

    // Can be an injected constant, value, or taken from some service
    var apiUrl = '/api/v1'; 

    var shouldPrependApiUrl = function (reqConfig) {
      if (!apiUrl) return false;
      return !(/[\s\S]*.html/.test(reqConfig.url) ||
              (reqConfig.url && reqConfig.url.indexOf(apiUrl) === 0));
    };

    return {
      request: function (reqConfig) {
        // Filter out requests for .html templates, etc
        if (apiUrl && shouldPrependApiUrl(reqConfig)) {
          reqConfig.url = apiUrl + reqConfig.url;
        }

        return reqConfig;
      }
    };
  })

  .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('apiUrlHttpInterceptor');
  }]);

Makes sense?

There is another feature being discussed though, which is will allow to define multiple "contexts" for modelizer, for example, to work with different APIs - it would make sense for each context to have its own global prefix then.

tsak commented 10 years ago

I would think that it would make sense to implement this as part of the library itself instead of using an interceptor that might affect other services consuming $http. As you've mentioned contexts it sounds to me that this functionality might be part of that.