TramwayJS

Factory

The factory facilitates the creation of standardized Entity and Collection objects and is primarily used by the Repository. Based on different use cases, it can be extended to support common formats like HATEAOS and decorate entities.

Definition

Create

tramway create:factory ProductFactory --add-dependency-injection --key factory.product

Locations

  • Implementation: src/factories
  • Dependency Injection: src/config/services/factories.js

API

FunctionUsage
create(item: Object): EntityCreates entity from object
createCollection(items: Object[]): CollectionReturns collection of entities from array of objects.

To create a factory, extend the class.

import { Factory } from 'tramway-core-connection';

Example

import { Factory } from 'tramway-core-connection';
import { Product } from '../entities';
/**
* @abstract
* @export
* @class ProductFactory
*/
export default class ProductFactory extends Factory {
/**
* @param {Object} item
* @returns {Entity}
*
* @memberOf ProductFactory
*/
create(item) {
const {
id,
width,
height,
price,
} = item;
return new Product()
.setId(id)
.setWidth(width)
.setHeight(height)
.setPrice(price)
;
}
}

Dependency Injection

import { ProductFactory } from '../../factories';
export default {
"factory.product": {
"class": ProductFactory,
"constructor": []
}
}