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 _viewid='_design/product_categories/_view/byid'; static const _getnameurl=_server+'/'+_db+'/'+_viewname; static const _getidurl=_server+'/'+_db+'/'+_viewid; 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']['id'], item['value']['type'])); } return prodcats; } catch(e) { throw _handleError(e); } } Future createProdCategory(String name,String id) async { try { await _http.post( _posturl, headers: {'Content-Type': 'application/json'}, body: JSON.encode({ 'name': name, 'id': id, 'type': 'product_category' }) ); } catch(e) { throw _handleError(e); } } Future getById(String id) async { try { ProductCategory prodcat; String url=_getidurl+'?key="'+id+'"'; final response = await _http.get(url); var item=JSON.decode(response.body); prodcat = new ProductCategory( item['rows'][0]['value']['_id'], item['rows'][0]['value']['name'], item['rows'][0]['value']['id'], item['rows'][0]['value']['type'] ); return prodcat; } catch(e) { throw _handleError(e); } } Future updateProdCategory(String oldid,String name, String id) async { try { String url=_getidurl+'?key="'+oldid+'"'; final response = await _http.get(url); print('Debug UPDATE GET URL: '+url); print('Debug UPDATE GET response: '+response.body); var resbody=JSON.decode(response.body); resbody['rows'][0]['value']['name']=name; resbody['rows'][0]['value']['id']=id; final response_put = await _http.put( _posturl+'/'+resbody['rows'][0]['id'], headers: {'Content-Type': 'application/json'}, body: JSON.encode(resbody['rows'][0]['value']) ); print('Debug UPDATE PUT response: '+response_put.body); } catch(e) { throw _handleError(e); } } Future deleteProdCategory(String doc_id) async { try { var url=_server+'/'+_db+'/'+doc_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'); } }