Skip to main content

Datastores & Connections

@DataStore(name)

Every entity must declare which configured datastore it belongs to:

import { PersistenceDecorators } from '@rapidrest/service-core';
const { DataStore } = PersistenceDecorators;

@DataStore('mongo')
export class Pet extends BaseMongoEntity {}

name refers to a key under the datastores section of your configuration:

conf.defaults({
datastores: {
mongo: {type: 'mongodb', host: 'localhost', database: 'my_api'},
},
});

MongoDB, PostgreSQL, and SQLite are supported for entity storage (SQL datastores go through TypeORM under the hood); Redis is used separately for caching (see Base Entities & Caching).

Required

Forgetting @DataStore(...) on an entity fails fast at startup with an explicit error naming the offending class, rather than a confusing runtime failure later.

Direct repository and connection injection

Most of the time you won't need this. Auto CRUD Routes and the base entity classes handle datastore access for you. But you can inject a repository or connection directly into a service when you need to:

import { DatabaseDecorators } from '@rapidrest/service-core';
const { Repository, MongoRepository, RedisConnection } = DatabaseDecorators;

export class PetService {
@MongoRepository(Pet)
private repo!: MongoRepository<Pet>;
}
import { DatabaseDecorators } from '@rapidrest/service-core';
import type {Redis} from 'ioredis';
const { Repository, MongoRepository, RedisConnection } = DatabaseDecorators;

export class SessionService {
@RedisConnection('cache')
private redis?: Redis;
}

@Repository injects a TypeORM Repository for SQL-backed entities; @MongoRepository injects a MongoDB-flavored equivalent; @RedisConnection(name) injects the named ioredis connection directly, most commonly used for the connection named "cache".

RepoUtils

More commonly when you need to access a persisted entity from the datastore you will use RepoUtils. The RepoUtils utility class offers common functionality for working with a SQL and NoSQL databases.

It is easy to inject RepoUtils into any managed class instance using the @Inject decorator (shown below).

import { ObjectDecorators } from '@rapidrest/core';
import { RepoUtils } from '@rapidrest/service-core';
const { Inject } = ObjectDecorators;

export class PetService {
@Inject(RepoUtils, { name: Pet.name, args: [Pet] })
private petUtils?: RepoUtils<Pet>;
}