all files / app/main/apps/chat/services/ chats.service.js

19.05% Statements 4/21
0% Branches 0/4
14.29% Functions 1/7
19.05% Lines 4/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                                                                                                                                                                      
(function ()
{
    'use strict';
 
    angular
        .module('app.chat')
        .factory('ChatsService', ChatsService);
 
    /** @ngInject */
    function ChatsService($q, msApi)
    {
        
        var service = {
            chats         : {},
            contacts      : [],
            getContactChat: getContactChat
        };
 
        /**
         * Get contact chat from the server
         *
         * @param contactId
         * @returns {*}
         */
        function getContactChat(contactId)
        {
 
            // Create a new deferred object
            var deferred = $q.defer();
 
            // If contact doesn't have lastMessage, create a new chat
            if ( !service.contacts.getById(contactId).lastMessage)
            {
                service.chats[contactId] = [];
 
                deferred.resolve(service.chats[contactId]);
            }
 
            // If the chat exist in the service data, do not request
            if ( service.chats[contactId] )
            {
                deferred.resolve(service.chats[contactId]);
                
                return deferred.promise;
            }
 
            // Request the chat with the contactId
            msApi.request('chat.chats@get', {id: contactId},
 
                // SUCCESS
                function (response)
                {
                    // Attach the chats
                    service.chats[contactId] = response.data;
 
                    // Resolve the promise
                    deferred.resolve(service.chats[contactId]);
                },
 
                // ERROR
                function (response)
                {
                    deferred.reject(response);
                }
            );
 
            return deferred.promise;
        }
 
        /**
         * Array prototype
         *
         * Get by id
         *
         * @param value
         * @returns {T}
         */
        Array.prototype.getById = function (value)
        {
            return this.filter(function (x)
            {
                return x.id === value;
            })[0];
        };
        return service;
    }
})();