A Repository
represents a specialized Service
interface that providesstrong-typed data access (for example, CRUD) operations of a domain modelagainst the underlying database or service.
Note:Repositories are adding behavior to Models. Models describe the shape of data, Repositories provide behavior like CRUD operations. This is different from LoopBack 3.x where models implement behavior too.
Tip: A single model can be used with multiple different Repositories.
A Repository
can be defined and implemented by application developers.LoopBack ships a few predefined Repository
interfaces for typical CRUD and KVoperations. These Repository
implementations leverage Model
definition andDataSource
configuration to fulfill the logic for data access.
interface Repository<T extends Model> {}
interface CustomerRepository extends Repository<Customer> {
find(filter?: Filter<Customer>, options?: Options): Promise<Customer[]>;
findByEmail(email: string): Promise<Customer>;
// ...
}
See more examples at:
Installation
Legacy juggler support has been enabled in loopback-next
and can be importedfrom the @loopback/repository
package. In order to do this, save@loopback/repository
as a dependency in your application.
You can then install your favorite connector by saving it as part of yourapplication dependencies.
Repository Mixin
@loopback/repository
provides a mixin for your Application that enablesconvenience methods that automatically bind repository classes for you.Repositories declared by components are also bound automatically.
Repositories are bound to repositories.${ClassName}
. See example below forusage.
import {Application} from '@loopback/core';
import {RepositoryMixin} from '@loopback/repository';
import {AccountRepository, CategoryRepository} from './repositories';
// Using the Mixin
class MyApplication extends RepositoryMixin(Application) {}
const app = new MyApplication();
// AccountRepository will be bound to key `repositories.AccountRepository`
app.repository(AccountRepository);
// CategoryRepository will be bound to key `repositories.CategoryRepository`
app.repository(CategoryRepository);
Configure datasources
DataSource
is a named configuration of a connector. The configurationproperties vary by connectors. For example, a datasource for MySQL
needs toset the connector
property to loopback-connector-mysql
with settings asfollows:
{
"host": "localhost",
"port": 3306,
"user": "my-user",
"password": "my-password",
"database": "demo"
}
Connector
is a provider that implements data access or api calls with aspecific backend system, such as a database, a REST service, a SOAP Web Service,or a gRPC micro-service. It abstracts such interactions as a list of operationsin the form of Node.js methods.
Typically, a connector translates LoopBack query and mutation requests intonative api calls supported by the underlying Node.js driver for the givenbackend. For example, a connector for MySQL
will map create
method to SQLINSERT statement, which can be executed through MySQL driver for Node.js.
When a DataSource
is instantiated, the configuration properties will be usedto initialize the connector to connect to the backend system. You can define aDataSource using legacy Juggler in your LoopBack 4 app as follows:
src/datsources/db.datasource.ts
import {juggler} from '@loopback/repository';
// this is just an example, 'test' database doesn't actually exist
export const db = new juggler.DataSource({
connector: 'mysql',
host: 'localhost',
port: 3306,
database: 'test',
password: 'pass',
user: 'root',
});
Define models
Models are defined as regular JavaScript classes. If you want your model to bepersisted in a database, your model must have an id
property and inherit fromEntity
base class.
TypeScript version:
import {Entity, model, property} from '@loopback/repository';
@model()
export class Account extends Entity {
@property({id: true})
id: number;
@property({required: true})
name: string;
}
JavaScript version:
import {Entity, ModelDefinition} from '@loopback/repository';
export class Account extends Entity {}
Account.definition = new ModelDefinition({
name: 'Account',
properties: {
id: {type: 'number', id: true},
name: {type: 'string', required: true},
},
});
Define repositories
Use DefaultCrudRepository
class to create a repository leveraging the legacyjuggler bridge and binding your Entity-based class with a datasource you haveconfigured earlier. It’s recommended that you useDependency Injection to retrieve your datasource.
TypeScript version:
import {DefaultCrudRepository, juggler} from '@loopback/repository';
import {Account, AccountRelations} from '../models';
import {DbDataSource} from '../datasources';
import {inject} from '@loopback/context';
export class AccountRepository extends DefaultCrudRepository<
Account,
typeof Account.prototype.id,
AccountRelations
> {
constructor(@inject('datasources.db') dataSource: DbDataSource) {
super(Account, dataSource);
}
}
JavaScript version:
import {DefaultCrudRepository} from '@loopback/repository';
import {Account} from '../models/account.model';
import {db} from '../datasources/db.datasource';
export class AccountRepository extends DefaultCrudRepository {
constructor() {
super(Account, db);
}
}
Controller Configuration
Once your DataSource is defined for your repository, all the CRUD methods youcall in your repository will use the Juggler and your connector’s methods unlessyou overwrite them. In your controller, you will need to define a repositoryproperty and create a new instance of the repository you configured yourDataSource for in the constructor of your controller class as follows:
export class AccountController {
constructor(
@repository(AccountRepository) public repository: AccountRepository,
) {}
}
Defining CRUD methods for your application
When you want to define new CRUD methods for your application, you will need tomodify the API Definitions and their corresponding methods in your controller.Here are examples of some basic CRUD methods:
- Create API Definition:
{
"/accounts/create": {
"post": {
"x-operation-name": "createAccount",
"requestBody": {
"description": "The account instance to create.",
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"description": "Account instance created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Account"
}
}
}
}
}
}
}
}
Create Controller method:
async createAccount(accountInstance: Account) {
return this.repository.create(accountInstance);
}
- Find API Definition:
{
"/accounts": {
"get": {
"x-operation-name": "getAccount",
"responses": {
"200": {
"description": "List of accounts",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Account"
}
}
}
}
}
}
}
}
}
Find Controller method:
async getAccount() {
return this.repository.find();
}
Don’t forget to register the complete version of your OpenAPI spec throughapp.api()
.
Please See Testing Your Application section inorder to set up and write unit, acceptance, and integration tests for yourapplication.
Access KeyValue Stores
We can now access key-value stores such as Redis using theKeyValueRepository.
Define a KeyValue Datasource
We first need to define a datasource to configure the key-value store. Forbetter flexibility, we split the datasource definition into two files. The jsonfile captures the configuration properties and it can be possibly overridden bydependency injection.
- redis.datasource.json
{
"name": "redis",
"connector": "kv-redis",
"host": "127.0.0.1",
"port": 6379,
"password": "",
"db": 0
}
- redis.datasource.tsThe class uses a configuration object to set up a datasource for the Redisinstance. By default, the configuration is loaded from
redis.datasource.json
.We can override it by binding a new object todatasources.config.redis
for acontext.
import {inject} from '@loopback/core';
import {juggler, AnyObject} from '@loopback/repository';
import * as config from './redis.datasource.json';
export class RedisDataSource extends juggler.DataSource {
static dataSourceName = 'redis';
constructor(
@inject('datasources.config.redis', {optional: true})
dsConfig: AnyObject = config,
) {
super(dsConfig);
}
}
To generate the datasource automatically, use lb4 datasource
command andselect Redis key-value connector (supported by StrongLoop)
.
Define a KeyValueRepository
The KeyValueRepository binds a model such as ShoppingCart
to theRedisDataSource
. The base DefaultKeyValueRepository
class provides animplementation based on loopback-datasource-juggler
.
import {DefaultKeyValueRepository} from '@loopback/repository';
import {ShoppingCart} from '../models/shopping-cart.model';
import {RedisDataSource} from '../datasources/redis.datasource';
import {inject} from '@loopback/context';
export class ShoppingCartRepository extends DefaultKeyValueRepository<
ShoppingCart
> {
constructor(@inject('datasources.redis') ds: RedisDataSource) {
super(ShoppingCart, ds);
}
}
Perform Key Value Operations
The KeyValueRepository provides a set of key based operations, such as set
,get
, delete
, expire
, ttl
, and keys
. SeeKeyValueRepositoryfor a complete list.
// Please note the ShoppingCartRepository can be instantiated using Dependency
// Injection
const repo: ShoppingCartRepository =
new ShoppingCartRepository(new RedisDataSource());
const cart1: ShoppingCart = givenShoppingCart1();
const cart2: ShoppingCart = givenShoppingCart2();
async function testKV() {
// Store carts using userId as the key
await repo.set(cart1.userId, cart1);
await repo.set(cart2.userId, cart2);
// Retrieve a cart by its key
const result = await repo.get(cart1.userId);
console.log(result);
});
testKV();
Persist Data without Juggler [Using MySQL database]
Important: This section has not been updated and codeexamples may not work out of the box.
LoopBack 4 gives you the flexibility to create your own custom Datasources whichutilize your own custom connector for your favorite back end database. You canthen fine tune your CRUD methods to your liking.
Example Application
You can look atthe account-without-juggler application as an example.
Implement the
CrudConnector
interface from@loopback/repository
package.Here is one way to do itImplement the
DataSource
interface from@loopback/repository
. Toimplement theDataSource
interface, you must give it a name, supply yourcustom connector class created in the previous step, and instantiate it:
export class MySQLDs implements DataSource {
name: 'mysqlDs';
connector: MySqlConn;
settings: Object;
constructor() {
this.settings = require('./mysql.json'); // connection configuration
this.connector = new MySqlConn(this.settings);
}
}
- Extend
CrudRepositoryImpl
class from@loopback/repository
and supplyyour custom DataSource and model to it:
import {CrudRepositoryImpl} from '@loopback/repository';
import {MySQLDs} from './datasources/mysqlds.datasource';
import {Account} from './models/account.model';
export class NewRepository extends CrudRepositoryImpl<Account, string> {
constructor() {
const ds = new MySQLDs();
super(ds, Account);
}
}
You can override the functions it provides, which ultimately call on yourconnector’s implementation of them, or write new ones.
Configure Controller
The next step is to wire your new DataSource to your controller. This step isessentially the same as above, but can also be done as follows using DependencyInjection:
- Bind instance of your repository to a certain key in your application class
class AccountMicroservice extends Application {
private _startTime: Date;
constructor() {
super();
const app = this;
app.controller(AccountController);
app.bind('repositories.NewRepository').toClass(NewRepository);
}
- Inject the bound instance into the repository property of your controller.
inject
can be imported from@loopback/context
.
export class AccountController {
@repository(NewRepository)
private repository: NewRepository;
}
Example custom connector CRUD methods
Here is an example of a find
function which uses the node-js mysql
driver toretrieve all the rows that match a particular filter for a model instance.
public find(
modelClass: Class<Account>,
filter: Filter<Account>,
options: Options
): Promise<Account[]> {
let self = this;
let sqlStmt = "SELECT * FROM " + modelClass.name;
if (filter.where) {
let sql = "?? = ?";
let formattedSql = "";
for (var key in filter.where) {
formattedSql = mysql.format(sql, [key, filter.where[key]]);
}
sqlStmt += " WHERE " + formattedSql;
}
debug("Find ", sqlStmt);
return new Promise<Account[]>(function(resolve, reject) {
self.connection.query(sqlStmt, function(err: any, results: Account[]) {
if (err !== null) return reject(err);
resolve(results);
});
});
}
Example Application
You can look atthe account application as an example.