All files / src/classes ValidatedTopic.ts

100% Statements 80/80
100% Branches 25/25
100% Functions 30/30
100% Lines 79/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 5581x 1x 1x         1x                                                                                                                                                                             1x 1x     1x                                   3x                       1x                                         28x 21x 1x     20x   7x     27x 27x 27x   25x                                           18x 18x 18x 1x     17x                                                     11x   11x           11x 4x     7x                                                 2x 1x     2x   2x                                           4x 4x   4x       4x   4x 3x 1x     2x 2x   2x     4x                                                                                       1x   1x       1x                                             1x   1x         1x                       126x   126x 29x                   24x                     216x                               24x                     97x 97x 97x   97x 97x     97x   97x 5x           92x                   19x             124x                         5x                 2x 1x                 6x 5x                 2x 1x             1x             24x 24x 8x               11x   11x                
import * as classTransformer from 'class-transformer'
import * as classValidator from 'class-validator'
import isObject = require('isobject')
 
import { archivist } from 'mage'
import * as mage from 'mage'
 
import { ValidationError } from '../errors'
 
// tslint:disable:completed-docs
type Key = string | number | symbol
 
export type Diff<T extends Key, U extends Key> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
 
// tslint:disable:completed-docs
export type Omit<T, K extends keyof T> = Pick<Partial<T>, Diff<keyof T, K>>
 
/**
 * Anonymous object representation of a validated topic
 *
 * Generally passed to Topic.create()
 */
export type TopicData<T extends ValidatedTopic> = Omit<T, keyof ValidatedTopic>
/**
 * Partial index type
 */
export type PartialIndex<I> = {
  [K in keyof I]?: string
}
 
/**
 * The IStaticThis interface is required
 * for us to be able to create static factory functions
 * that return a properly typed output.
 */
export interface IStaticThis<I, T> {
  // Todo: any should be I!
  indexType: { new(): any },
 
  new (): T,
 
  getClassName(): string,
 
  execute<I, T, R>(
    this: IStaticThis<I, T>,
    state: any,
    method: any,
    args: any[],
    run: (data: any) => any): Promise<R>,
 
  create<T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    index: I,
    data?: any): Promise<T>,
 
  get<T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    index: I,
    options?: archivist.IArchivistGetOptions): Promise<T>
 
  mget<T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    indexes: I[],
    options?: archivist.IArchivistGetOptions): Promise<T[]>
}
 
/**
 * Validated topic
 *
 * Please note that you should import the default
 * of this module, not this class directly.
 *
 * Good:
 *
 * ```typescript
 * import ValidatedTopic from 'mage-validator'
 * ```
 *
 * Bad:
 *
 * ```typescript
 * import { ValidatedTopic } from 'mage-validator'
 * ```
 *
 * While the second line will work, it will provide you with
 * less type safety than the first import example.
 *
 * @export
 * @abstract
 * @class ValidatedTopic
 */
export default class ValidatedTopic {
  public static readonly mediaType: string = 'application/json'
  public static readonly index: string[]
  public static readonly indexType: any
  public static readonly vaults = {}
 
  private static _className: string
 
  /**
   * Return the current class name
   *
   * @static
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static getClassName(): string {
    /* istanbul ignore next */
    if (!this._className) {
      return this.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1]
    }
 
    return this._className
  }
 
  /**
   * Explicitly set the name of this class
   *
   * @static
   * @param {string} name
   *
   * @memberof ValidatedTopic
   */
  public static setClassName(name: string): void {
    this._className = name
  }
 
  /**
   * Create an instance from a generic object
   *
   * @static
   * @param {mage.core.IState} state
   * @param {*} data
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async create<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    index: I,
    data?: TopicData<T>): Promise<T> {
 
    let instance
 
    if (data) {
      if (!isObject(data)) {
        throw new Error(`Received data is not an object (received ${JSON.stringify(data)})`)
      }
 
      instance = classTransformer.plainToClass<T, object>(this, data)
    } else {
      instance = new this()
    }
 
    instance.setTopic(this.getClassName())
    instance.setState(state)
    await instance.setIndex(index)
 
    return instance
  }
 
  /**
   * Utility method used to promisify archivist calls
   *
   * @static
   * @param {*} state
   * @param {*} method
   * @param {any[]} args
   * @param {Function} run
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async execute<I, T, R>(
    this: IStaticThis<I, T>,
    state: any,
    method: any,
    args: any[],
    run: (data: any) => any): Promise<R> {
 
    return new Promise<R>((resolve, reject) => {
      state.archivist[method](...args, (error: Error, data: T) => {
        if (error) {
          return reject(error)
        }
 
        resolve(run(data))
      })
    })
  }
 
  /**
   * Get a topic instance from backend vault(s)
   *
   * Mostly a wrapper around state.archivist.get. Note that
   * instead of using the `optional` option directly with this call,
   * you should consider using `tryGet` instead, which will trigger a
   * compile error if you do not check for an undefined return value.
   *
   * @static
   * @param {mage.core.IState} state
   * @param {archivist.IArchivistIndex} index
   * @param {archivist.IArchivistGetOptions} [options]
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async get<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    index: I,
    options?: archivist.IArchivistGetOptions): Promise<T> {
 
    const topicName = this.getClassName()
 
    return this.execute<I, T, T>(state, 'get', [
      topicName,
      index,
      options
    ], async (data: any) => {
      // If optional: true, and no data was found
      if (options && options.optional && !data) {
        return undefined
      }
 
      return this.create(state, index, data)
    })
  }
 
  /**
   * Try to get a topic instance from backend vault(s)
   *
   * Same as `get`, but is also states that `undefined' might be returned instead.
   * You should consider using this method instead of calling `get` directly
   * with the `optional: true` option.
   *
   * @static
   * @param {mage.core.IState} state
   * @param {archivist.IArchivistIndex} index
   * @param {archivist.IArchivistGetOptions} [options]
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async tryGet<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    index: I,
    options?: archivist.IArchivistGetOptions): Promise<T | undefined> {
 
    if (!options) {
      options = {}
    }
 
    options.optional = true
 
    return this.get(state, index, options)
  }
 
  /**
   * Get instances from backend vault(s)
   *
   * Mostly a wrapper around state.archivist.mget.
   *
   * @static
   * @param {mage.core.IState} state
   * @param {archivist.IArchivistQuery[]} queries
   * @param {archivist.IArchivistGetOptions} [options]
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async mget<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    indexes: I[],
    options?: archivist.IArchivistGetOptions): Promise<T[]> {
 
    const topic = this.getClassName()
    const queries: archivist.IArchivistQuery[] = indexes.map((index) => ({ topic, index }))
 
    return this.execute<I, T, T[]>(state, 'mget', [
      queries,
      options
    ], async (list: any) => {
      const instances: ValidatedTopic[] = []
 
      for (const [i, data] of list.entries()) {
        if (!data) {
          continue
        }
 
        const index = queries[i].index
        const instance = await this.create(state, index as I, data)
 
        instances.push(instance)
      }
 
      return instances
    })
  }
 
  //
  // Todo:
  //
  // public static async mget(state: mage.core.IState, queries: archivist.INamedArchivistQuery, options?: archivist.IArchivistGetOptions) {
  //   return new Promise((resolve, reject) => {
  //     state.archivist.mget(queries, options, async (error, list) => {
  //       if (error) {
  //         return reject(error)
  //       }
 
  //       const instances = Object.keys(list).reduce((instances, name) => {
  //         if (list[name]) {
  //           instances[name] = this.create(state, queries[name], list[name])
  //         }
 
  //         return instances
  //       }, {})
 
  //       resolve(instances)
  //     })
  //   })
  // }
 
  /**
   * List all keys
   *
   * @static
   * @param {mage.core.IState} state
   * @param {archivist.IArchivistIndex} partialIndex
   * @param {archivist.IArchivistGetOptions} [options]
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async list<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    partialIndex: PartialIndex<I>,
    options?: archivist.IArchivistListOptions): Promise<archivist.IArchivistIndex[]> {
 
    const topicName = this.getClassName()
 
    return this.execute<I, T, I[]>(state, 'list', [
      topicName,
      partialIndex,
      options,
    ], (indexes: archivist.IArchivistIndex[]) => indexes)
  }
 
  /**
   * Query data by partial index
   *
   * Essentially wraps state.archivist.list, then fetches the data
   * for each keys using state.archivist.mget.
   *
   * @static
   * @param {mage.core.IState} state
   * @param {archivist.IArchivistIndex} partialIndex
   * @param {archivist.IArchivistGetOptions} [options]
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public static async query<I extends archivist.IArchivistIndex, T extends ValidatedTopic>(
    this: IStaticThis<I, T>,
    state: mage.core.IState,
    partialIndex: PartialIndex<I>,
    options?: archivist.IArchivistGetOptions | archivist.IArchivistListOptions): Promise<T[]> {
 
    const topicName = this.getClassName()
 
    return this.execute<I, T, T[]>(state, 'list', [
      topicName,
      partialIndex,
      options
    ], async (indexes: I[]) => {
      return this.mget<T>(state, indexes, options as archivist.IArchivistGetOptions)
    })
  }
 
  /**
   * Creates an instance of ValidatedTopic.
   *
   * @param {mage.core.IState} state
   *
   * @memberof ValidatedTopic
   */
  constructor(state?: mage.core.IState) {
    this.setTopic(this.constructor.name)
 
    if (state) {
      this.setState(state)
    }
  }
 
  /**
   * Get the topic for this instance
   *
   * @memberof ValidatedTopic
   */
  public getTopic() {
    return <string> (<any> this)._topic
  }
 
  /**
   * Set the topic name for this instance
   *
   * @param {string} topicName
   *
   * @memberof ValidatedTopic
   */
  public setTopic(topicName: string) {
    Object.defineProperty(this, '_topic', {
      value: topicName,
      configurable: true
    })
  }
 
  /**
   * Get the topic of that instance
   *
   * Should always return the class name of the instance.
   *
   * @returns
   *
   * @memberof ValidatedTopic
   */
  public getIndex() {
    return <archivist.IArchivistIndex> (<any> this)._index
  }
 
  /**
   * Set the index of this topic instance
   *
   * @param {archivist.IArchivistIndex} index
   *
   * @memberof ValidatedTopic
   */
  public async setIndex(indexData: archivist.IArchivistIndex) {
    const Class: any = this.constructor
    const Index = Class.indexType
    const index = new Index()
 
    for (const field of Class.index) {
      index[field] = indexData[field]
    }
 
    const errors = await classValidator.validate(index)
 
    if (errors.length > 0) {
      throw new ValidationError('Index validation failed', 'server', {
        topic: this.getTopic(),
        index: this.getIndex()
      }, errors)
    }
 
    Object.defineProperty(this, '_index', {
      value: index,
      configurable: true
    })
  }
 
  /**
   * Retrieve the state object attached to the instance
   */
  public getState() {
    return <mage.core.IState> (<any> this)._state
  }
 
  /**
   * Set the state this topic instance will be using.
   */
  public setState(state: mage.core.IState) {
    Object.defineProperty(this, '_state', {
      value: state,
      configurable: true
    })
  }
 
  /**
   * Retrieve the actual data for this instance
   *
   * This should essentially be the same as simply accessing data on the
   * instance itself.
   */
  public getData() {
    return this
  }
 
  /**
   * Record an add operation on the instance's state
   *
   * Essentially a wrapper for state.archivist.add
   */
  public async add(mediaType?: archivist.ArchivistMediaType, encoding?: archivist.ArchivistEncoding, expirationTime?: number) {
    await this.validate('Validation failed on add')
    return this.getState().archivist.add(this.getTopic(), this.getIndex(), this.getData(), mediaType, encoding, expirationTime)
  }
 
  /**
   * Record a set operation on the instance's state
   *
   * Essentially a wrapper for state.archivist.set.
   */
  public async set(mediaType?: archivist.ArchivistMediaType, encoding?: archivist.ArchivistEncoding, expirationTime?: number) {
    await this.validate('Validation failed on set')
    return this.getState().archivist.set(this.getTopic(), this.getIndex(), this.getData(), mediaType, encoding, expirationTime)
  }
 
  /**
   * Record a touch operation on the instance's state
   *
   * Essentially a wrapper for state.archivist.touch.
   */
  public async touch(expirationTime?: number) {
    await this.validate('Validation failed on touch')
    return this.getState().archivist.touch(this.getTopic(), this.getIndex(), expirationTime)
  }
 
  /**
   * Record a delete operation on the instance's state
   */
  public del() {
    return this.getState().archivist.del(this.getTopic(), this.getIndex())
  }
 
  /**
   * Validate the current instance
   */
  public async validate(errorMessage?: string, code?: string): Promise<void> {
    const errors = await classValidator.validate(this)
    if (errors.length > 0) {
      this.raiseValidationError(errors, errorMessage, code)
    }
  }
 
  /**
   * Throw a ValidateError including relevant details
   */
  public raiseValidationError(errors: any[], errorMessage?: string, code?: string) {
    const state = <any> this.getState()
 
    throw new ValidationError(errorMessage || 'Validation failed', code || 'server', {
      actorId: state.actorId,
      userCommand: state.description,
      topic: this.getTopic(),
      index: this.getIndex()
    }, errors)
  }
}