TramwayJS

Repository

A class that knows how to model information returned or sent to a data source.

Repositories allow you to interact with a given connection specifically for the purposes of handling a given entity. This usually implies persisting to a database but with the flexibility of Tramway, it can also mean local storage or via an API connection. The default Repository already links to a connection and utilizes the existing methods that were implemented when the Provider was implemented or imported. The following demonstrates how a Repository could be used with a Provider and Entity.

Definition

Create

tramway create:repository ProductRepository --add-dependency-injection --connection provider.mysql --key repository.product

Locations

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

API

Summary of Repository Spec

FunctionUsage
constructor(Provider, Factory, collection)Constructor takes a Provider, Factory, and the name of the collection

Exposed methods to use

All of these methods rely on the Provider's implementation and will just interact with the Provider.

FunctionUsage
exists(id: string/int): booleanCalls Provider's exist function
getOne(id: string/int): EntityGets entity with id
get(): CollectionGets collection of all objects from the entity's set
create(entity: Entity)Sends the entity to the provider to be created and returns the persisted result.
update(entity: Entity)Updates the entity via the provider and returns the persisted result.
delete(id: string/int)Deletes the item with the Model's set id.
find(condtions: string/Object): CollectionFinds a collection of objects in the entity's set with given conditions
getMany(ids: any[]): CollectionGets objects tied to a list of ids
count(conditions): numberGets a count of objects for given conditons
setup()Handles programatic initialization of the data source

To create a repository, extend the class.

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

Example

import { Repository } from 'tramway-core-connection';
export default class ProductRepository extends Repository {
constructor(provider, factory) {
super(provider, factory, 'products');
}
}

Dependency Injection

import { ProductRepository } from '../../repositories';
export default {
"repository.product": {
"class": ProductRepository,
"constructor": [
{"type": "service", "key": "provider.mysql"},
{"type": "service", "key": "factory.product"},
]
}
}