All files / src payload.ts

100% Statements 24/24
100% Branches 12/12
100% Functions 8/8
100% Lines 17/17
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    3x 40x             3x       4x 3x 6x         3x 12x   30x 30x   30x   30x     3x 7x   3x 5x   3x  
import { IAuthPayload, StringAnyMap, StringStringMap } from './interfaces';
 
export const isEmpty = (value: any) =>
  value === undefined ||
  value === null ||
  (typeof value === 'object' && Object.keys(value).length === 0) ||
  (typeof value === 'string' && value.trim().length === 0);
 
export type PayloadEntry = [string, string];
 
export default class AuthPayload implements IAuthPayload {
  private PAYLOAD: PayloadEntry[];
  private REVERSE_PAYLOAD: PayloadEntry[];
 
  constructor(payload: StringStringMap = {}) {
    this.PAYLOAD = Object.entries(payload);
    this.REVERSE_PAYLOAD = this.PAYLOAD.map(([pk, k]): PayloadEntry => [k, pk]);
  }
  /**
   * Replaces the keys of a payload
   */
  public reverse(keys: PayloadEntry[], payload: StringAnyMap): StringAnyMap {
    if (!keys.length) return payload;
 
    return keys.reduce((p: StringAnyMap, [k, pk]) => {
      const v = payload[k];
 
      if (!isEmpty(v)) p[pk] = v;
 
      return p;
    }, {});
  }
  public create(payload: StringAnyMap) {
    return this.reverse(this.REVERSE_PAYLOAD, payload);
  }
  public parse(payload: StringAnyMap) {
    return this.reverse(this.PAYLOAD, payload);
  }
}