import 'dart:async'; import 'dart:convert'; import 'package:angular2/core.dart'; import 'package:http/browser_client.dart'; import 'product_category.dart'; @Injectable() class ProductCategoryService { static const _server='http://10.8.0.1:5984'; static const _db='tavern'; static const _viewname='_design/product_categories/_view/byname'; static const _getnameurl=_server+'/'+_db+'/'+_viewname; static const _posturl=_server+'/'+_db; final BrowserClient _http; ProductCategoryService(this._http); Future> getAll() async { try { List prodcats=[]; final response = await _http.get(_getnameurl); for(var item in JSON.decode(response.body)['rows']) { prodcats.add(new ProductCategory( item['id'], item['value']['name'], item['value']['type'])); } return prodcats; } catch(e) { throw _handleError(e); } } Future createProdCategory(String name) async { try { var res = await _http.post( _posturl, headers: {'Content-Type': 'application/json'}, body: JSON.encode({ 'name': name, 'type': 'product_category' }) ); return(JSON.decode(res.body)['id']); } catch(e) { throw _handleError(e); } } Future getById(String id) async { try { ProductCategory prodcat; String url=_server+'/'+_db+'/'+id; final response = await _http.get(url); var item=JSON.decode(response.body); prodcat = new ProductCategory( item['_id'], item['name'], item['type'] ); return prodcat; } catch(e) { throw _handleError(e); } } Future updateProdCategory(String id,String name) async { try { String url=_server+'/'+_db+'/'+id; final response = await _http.get(url); var resbody=JSON.decode(response.body); resbody['name']=name; await _http.put( _posturl+'/'+id, headers: {'Content-Type': 'application/json'}, body: JSON.encode(resbody) ); } catch(e) { throw _handleError(e); } } Future deleteProdCategory(String id) async { try { var url=_server+'/'+_db+'/'+id; var response = await _http.get(url); var reso=JSON.decode(response.body); url=_server+'/'+_db+'/_purge/'; final respurge = await _http.post( url, headers: {'Content-Type': 'application/json'}, body: JSON.encode({ reso['_id']: [reso['_rev']] }) ); print('Debug: '+respurge.body); } catch(e) { throw _handleError(e); } } Exception _handleError(dynamic e) { print(e); return new Exception('Server error; cause: $e'); } }