-
Notifications
You must be signed in to change notification settings - Fork 0
/
productsService.js
102 lines (82 loc) · 2.5 KB
/
productsService.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
app.service('ProductsService', function ($q, ProductRepo, WsApi) {
var service = this;
var products = [];
var remoteProducts = {};
var defer = $q.defer();
var process = function (response) {
var apiRes = angular.fromJson(response.body);
if (apiRes.meta.status === 'SUCCESS') {
products.length = 0;
angular.extend(products, apiRes.payload['ArrayList<Product>']);
defer.notify();
} else {
console.error(apiRes.meta);
throw "Unable to retrieve products";
}
};
var processRemoteProduct = function (response, productId, deferRefresh) {
var apiRes = angular.fromJson(response.body);
if (apiRes.meta.status === 'SUCCESS') {
if (angular.isDefined(remoteProducts[productId])) {
for (var key in remoteProducts[productId]) {
remoteProducts[productId][key] = undefined;
}
} else {
remoteProducts[productId] = {};
}
angular.extend(remoteProducts[productId], apiRes.payload.HashMap);
deferRefresh.notify();
} else {
throw "Unable to retrieve remote products for product " + productId;
}
};
WsApi.listen(apiMapping.Product.listen).then(null, null, function (response) {
process(response);
});
service.refreshProducts = function () {
WsApi.fetch(apiMapping.Product.all).then(function (response) {
process(response);
for (var productId in remoteProducts) {
service.refreshRemoteProducts(productId);
}
});
};
service.refreshRemoteProducts = function (productId) {
var deferRefresh = $q.defer();
var options = {
pathValues: {
productId: productId
}
};
WsApi.fetch(apiMapping.RemoteProducts.byProduct, options).then(function (response) {
processRemoteProduct(response, productId, deferRefresh);
});
return deferRefresh.promise;
};
service.getRemoteProducts = function () {
return remoteProducts;
};
service.getProducts = function () {
return products;
};
service.getRemoteProductInfo = function (productId) {
for (var i in products) {
if (products[i].id == productId) {
return products[i].remoteProducts;
}
}
};
service.getById = function (id) {
return $q(function (resolve, reject) {
service.ready.then(function () {
for (var i in products) {
if (products[i].id == id) {
resolve(products[i]);
}
}
});
}.bind(service));
};
service.refreshProducts();
service.ready = defer.promise;
});