import 'dart:async'; import 'dart:convert'; import 'package:angular2/core.dart'; import 'package:http/browser_client.dart'; import 'product.dart'; @Injectable() class ProductService { final BrowserClient _http; static const _server='http://10.8.0.1:5984'; static const _db='tavern'; static const _byname='_design/products/_view/byname'; static const _bycategory='_design/products/_view/bycategory'; ProductService(this._http); Future> getAll() async { try { var url=_server+'/'+_db+'/'+_byname; List prods=[]; final response = await _http.get(url); for(var item in JSON.decode(response.body)['rows']) { prods.add(new Product(item['id'], item['value']['name'], item['value']['price'], item['value']['type'], item['value']['category'] )); } return prods; } catch(e) { throw _handleError(e); } } Future> getByCategory(String id) async { try { var url=_server+'/'+_db+'/'+_bycategory+'?key="'+id+'"'; List prods=[]; final response = await _http.get(url); for(var item in JSON.decode(response.body)['rows']) { prods.add(new Product(item['id'], item['value']['name'], item['value']['price'], item['value']['type'], item['value']['category'] )); } return prods; } catch(e) { throw _handleError(e); } } Future createProduct(String name,double pri,String cat) async { try { var url=_server+'/'+_db; var response = await _http.post( url, headers: {'Content-Type': 'application/json'}, body: JSON.encode({ 'name': name, 'price': pri, 'type': 'product', 'category': cat }) ); return(JSON.decode(response.body)['id']); } catch(e) { throw _handleError(e); } } Future deleteProduct(String id) async { try { var url=_server+'/'+_db+'/'+id; var resp = await _http.get(url); var reso=JSON.decode(resp.body); url=_server+'/'+_db+'/_purge/'; await _http.post( url, headers: {'Content-Type': 'application/json'}, body: JSON.encode({ reso['_id']: [reso['_rev']] }) ); } catch(e) { throw _handleError(e); } } Future getById(String id) async { try { var url=_server+'/'+_db+'/'+id; Product prod; final response = await _http.get(url); var item=JSON.decode(response.body); prod=(new Product(item['_id'],item['name'], item['price'],item['type'], item['category'])); return prod; } catch(e) { throw _handleError(e); } } Future updateProd(String id,String name,double price, String category) async { try { var url=_server+'/'+_db+'/'+id; var resp = await _http.get(url); var reso=JSON.decode(resp.body); reso['name']=name; reso['price']=price; reso['category']=category; await _http.put( url, headers: {'Content-Type': 'application/json'}, body: JSON.encode(reso) ); } catch(e) { throw _handleError(e); } } Exception _handleError(dynamic e) { print(e); return new Exception('Server error; cause: $e'); } }