4 import 'package:angular2/core.dart';
5 import 'package:http/browser_client.dart';
10 class ProductService {
11 final BrowserClient _http;
13 static const _server='http://10.8.0.1:5984';
14 static const _db='tavern';
15 static const _byname='_design/products/_view/byname';
16 static const _bycategory='_design/products/_view/bycategory';
18 ProductService(this._http);
20 Future<List<Product>> getAll() async {
22 var url=_server+'/'+_db+'/'+_byname;
23 List<Product> prods=[];
24 final response = await _http.get(url);
25 for(var item in JSON.decode(response.body)['rows']) {
26 prods.add(new Product(item['id'],
27 item['value']['name'],
28 item['value']['price'],
29 item['value']['type'],
30 item['value']['category']
36 throw _handleError(e);
40 Future<List<Product>> getByCategory(String id) async {
42 var url=_server+'/'+_db+'/'+_bycategory+'?key="'+id+'"';
43 List<Product> prods=[];
44 final response = await _http.get(url);
45 for(var item in JSON.decode(response.body)['rows']) {
46 prods.add(new Product(item['id'],
47 item['value']['name'],
48 item['value']['price'],
49 item['value']['type'],
50 item['value']['category']
56 throw _handleError(e);
60 Future<Null> createProduct(String name,double price,String cat) async {
62 var url=_server+'/'+_db;
63 var response = await _http.post(
65 headers: {'Content-Type': 'application/json'},
73 return(JSON.decode(response.body)['id']);
76 throw _handleError(e);
80 Future<Null> deleteProduct(String id) async {
82 var url=_server+'/'+_db+'/'+id;
83 var resp = await _http.get(url);
84 var reso=JSON.decode(resp.body);
85 url=_server+'/'+_db+'/_purge/';
88 headers: {'Content-Type': 'application/json'},
90 reso['_id']: [reso['_rev']]
95 throw _handleError(e);
99 Future<Product> getById(String id) async {
101 var url=_server+'/'+_db+'/'+id;
103 final response = await _http.get(url);
104 var item=JSON.decode(response.body);
105 prod=(new Product(item['_id'],item['name'],
106 item['price'],item['type'],
111 throw _handleError(e);
115 Future<Null> updateProd(String id,String name,double price,
116 String category) async {
118 var url=_server+'/'+_db+'/'+id;
119 var resp = await _http.get(url);
120 var reso=JSON.decode(resp.body);
123 reso['category']=category;
126 headers: {'Content-Type': 'application/json'},
127 body: JSON.encode(reso)
131 throw _handleError(e);
135 Exception _handleError(dynamic e) {
137 return new Exception('Server error; cause: $e');