pouch-service.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { Injectable } from "@angular/core";
  2. import { Observable } from "rxjs/Observable";
  3. import { Observer } from "rxjs/Observer";
  4. import PouchDB from "pouchdb";
  5. import * as PouchFind from "pouchdb-find";
  6. import "rxjs/add/observable/throw";
  7. import "rxjs/add/observable/fromPromise";
  8. import "rxjs/add/observable/from";
  9. import "rxjs/add/operator/concatMap";
  10. PouchDB.plugin(PouchFind);
  11. @Injectable()
  12. export class PouchService {
  13. pouchDB: any;
  14. constructor() {
  15. this.initialize();
  16. }
  17. /**
  18. *
  19. */
  20. private initialize(): Observable<any> {
  21. this.pouchDB = new PouchDB("odoo", {
  22. auto_compaction: true
  23. });
  24. return Observable.fromPromise(this.pouchDB.createIndex({
  25. index: {
  26. fields: ['type']
  27. }
  28. }));
  29. }
  30. /**
  31. *
  32. */
  33. save(data: any): Observable<any> {
  34. if (!data.type) {
  35. return Observable.throw("Error: Cannot save data without type");
  36. }
  37. delete data.__last_update;
  38. return Observable.fromPromise(this.pouchDB.post(data));
  39. }
  40. /**
  41. *
  42. */
  43. remove(data: any): Observable<any> {
  44. if (!data._id || !data._rev) {
  45. return Observable.throw("Error: Cannot remove data without id or rev");
  46. }
  47. return Observable.fromPromise(this.pouchDB.remove(data));
  48. }
  49. /**
  50. *
  51. */
  52. removeAll(type: string): Observable<any> {
  53. return this.getAll(type).concatMap(result => Observable.from(result.docs)).concatMap(doc => this.remove(Object.assign(doc, { _deleted: true })));
  54. }
  55. /**
  56. *
  57. */
  58. get(data: any): Observable<any> {
  59. if (!data._id) {
  60. return Observable.throw("Error: Cannot get data without id");
  61. }
  62. return Observable.fromPromise(this.pouchDB.get(data._id));
  63. }
  64. /**
  65. *
  66. */
  67. getAll(type: string): Observable<any> {
  68. return Observable.fromPromise(this.pouchDB.find({
  69. selector: {
  70. type: {
  71. $eq: type
  72. }
  73. }
  74. }));
  75. }
  76. /**
  77. *
  78. */
  79. destroy(): Observable<any> {
  80. return Observable.fromPromise(this.pouchDB.destroy());
  81. }
  82. /**
  83. *
  84. */
  85. destroyAndInitialize() {
  86. return this.destroy().concat(this.initialize());
  87. }
  88. }