All files PouchDbActiveRecord.ts

100% Statements 40/40
100% Branches 4/4
100% Functions 5/5
100% Lines 33/33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x 1x   1x 1x   1x               1x   1x 1x 1x         1x 1x   1x           1x 5x 1x 1x     5x 5x 5x 5x     1x 23x 23x 23x 23x     1x 9x 13x 13x 6x   13x   9x   1x  
import { ActiveRecord, ModelAttribute } from "@hke/activerecord";
import { PouchDbActiveQuery } from "./PouchDbActiveQuery";
 
import * as PouchDB from 'pouchdb';
import * as PouchDBFind from 'pouchdb-find';
 
let PouchDb = PouchDB
  .plugin(PouchDBFind);
 
export interface PouchDbInstance {
  get: (id: string) => Promise<any>
  find: (condition: any) => Promise<any>
}
 
export class PouchDbActiveRecord extends ActiveRecord {
 
  static _identifier = '_id';
  static _tableName = 'PouchDbActiveRecord';
  static _queryClass = PouchDbActiveQuery;
 
  public _id: string;
  public _rev: string;
 
  static dbConfig: any = {};
  protected static _db: { [model: string]: PouchDbInstance; } = {};
 
  protected static _attributes = [
    // add internal pouchdb properties
    new ModelAttribute('_id'),
    new ModelAttribute('_rev')
  ];
 
  static _dbInit() {
    if (this.dbConfig.plugins) {
      this.dbConfig.plugins.forEach((plugin) => {
        PouchDb = PouchDb.plugin(plugin);
      });
    }
    delete this.dbConfig.plugins;
    this._db[this.config.tableName] = new PouchDb('.db/' + this.config.tableName, this.dbConfig);
    super.initialized(this.config.tableName);
    return Promise.resolve(true);
  }
 
  public async save(): Promise<this> {
    const res = await this.class.db.post(this.attributes);
    this.setAttribute('_id', res.id);
    this.setAttribute('_rev', res.rev);
    return this;
  }
 
  static async save(objects): Promise<any[]> {
    let result = [];
    for (let object of objects) {
      if (!(object instanceof this)) {
        object = new this(object);
      }
      result.push(await object.save());
    }
    return result;
  }
}