All files / lib/stack/api base.js

100% Statements 24/24
100% Branches 15/15
100% Functions 8/8
100% Lines 20/20
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 63 64          36x 32x       4x                 146x 144x 144x 144x 144x 144x       36x         2x 2x       4x 2x   2x       2x       34x               34x 34x 34x        
import Query from './query.js';
import { transform, addParam } from '../utils.js';
 
 
function onData(data) {
  if (typeof (data.data) === 'string') { return Promise.reject(data.data); }
  return Promise.resolve(data.data);
}
 
function onError(error) {
  return Promise.reject(error);
}
/**
 * This is Base class, it holds all the methods required for Modle instance,
 *  eg ContentType('uid').delete() or Asset('uid').update({...})
 *  @ignore
 */
export default class Base {
  constructor(uid) {
    if (!uid) { throw new Error('uid is required'); }
    this.uid = uid;
    this._query = {};
    this.only = transform('only');
    this.except = transform('except');
    this.addParam = addParam;
  }
 
  static Query() {
    return new Query(this.connection, this.module(true), this.contentTypeUid);
  }
 
 
  static create(payload) {
    const options = { payload, content_type_uid: this.contentTypeUid, action: `create${this.module()}` };
    return this.connection.sendToParent('stackQuery', options).then(onData).catch(onError);
  }
 
  update(payload) {
    if (!payload || (typeof payload !== 'object') || (payload instanceof Array)) {
      return Promise.reject(new Error('Kindly provide valid parameters'));
    }
    return this.fetch(`update${this.constructor.module()}`, payload);
  }
 
  delete() {
    return this.fetch(`delete${this.constructor.module()}`);
  }
 
  fetch(action, payload) {
    const options = {
      payload,
      content_type_uid: this.constructor.contentTypeUid,
      uid: this.uid,
      params: this._query,
      action: action || `get${this.constructor.module()}`
    };
 
    if (!payload) { delete options.payload; }
    if (!this.constructor.contentTypeUid) { delete options.content_type_uid; }
    return this.constructor.connection.sendToParent('stackQuery', options)
      .then(onData).catch(onError);
  }
}