Newer
Older
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
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;
}
}