Skip to content
Snippets Groups Projects
CrudCollectionResource.mjs 1.73 KiB
Newer Older
Paul Erickson's avatar
Paul Erickson committed
import uuidv4 from 'uuid/v4.js'
import winston from 'winston'

import CollectionResource from './CollectionResource.mjs'
import CrudService from '../../service/abstract/CrudService.mjs'
import CrudEntityResource from './CrudEntityResource.mjs'

export default class CrudCollectionResource extends CollectionResource {

  /**
   * Delegates to an EntityResource for creating entities (i.e. handling POST request)
   *
   * If entityResource is provided, then service must be also!
   *
   * @param {class} CollectionClass
   * @param {CrudService} [service]
   * @param {CrudEntityResource} [entityResource]
   */
  constructor(CollectionClass, service, entityResource) {
    super();
    this.CollectionClass = CollectionClass;
    this.EntityClass = CollectionClass.EntityClass;
    this.pathSegment = `/${CollectionClass.EntityClass.name}s?`;
    this.service = service || new CrudService(CollectionClass.constructor.EntityClass);
    this.entityResource = entityResource || new CrudEntityResource(this.service);
    this.resources = [ this.entityResource ];
  }

  /**
   * Query is treated as an example/matcher object, in order to search against its properties
   *
   * @param query
   * @returns {Promise<Array<EntityClass>>}
   */
  async retrieveAll(query) {
    winston.info(`Retrieving ${this.EntityClass.name}s with query ${JSON.stringify(query)}`);
    const collection = await this.service.retrieveAll(new this.EntityClass(query));
    return new this.CollectionClass(collection);
  }

  /**
   * Returns ID of created source, creating one if needed
   *
   * @param object
   * @returns {Promise<string>}
   */
  async createEntity(object) {
    const id = object.id || uuidv4();
    await this.entityResource.createEntity(object, id);
    return id;
  }

}