Angular JS – HttpService to cache $http calls between different apps

angular.module("common.services")
    .service("httpCachingService", ["$http", '$q', "$window",
        function ($http, $q, $window) {
            var _self = this;

            var _ns = $window.httpCachingService = $window.httpCachingService || {
                    items: []
                };

            _self.get = function (uri) {
                return $q(function (resolve, reject) {
                    var filteredItems = _ns.items.filter(function (item) {
                        return item.uri == uri;
                    });

                    var item = filteredItems.length > 0 ? filteredItems[0] : null;

                    if (!!item) {
                        if (item.ready) {
                            resolve(item);
                        } else {
                            item.listeners.push(function () {
                                resolve(item);
                            });
                        }
                    } else {
                        item = {
                            uri: uri,
                            ready: false,
                            data: null,
                            listeners: []
                        };

                        _ns.items.push(item);

                        $http.get(uri)
                            .then(function (result) {
                                item.data = result.data;
                                item.ready = true;

                                item.listeners.forEach(function (listener) {
                                    listener();
                                });

                                item.listeners = [];
                                resolve(item);
                            })
                            .catch(function (error) {
                                reject(error);
                            });
                    }
                });
            };

            _self.invalidate = function (uri) {
                _ns.items = _ns.items.filter(function (item) {
                    return (!!uri && item.uri != uri) || !item.ready;
                });
            };
        }]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s