Loopback 4 Extension That Provides Sequelize Crud Repository Compatible With Default Loopback Models.
npm install @loopback/sequelizeThis is a loopback4 extension that provides Sequelize's query builder at
repository level in any loopback 4 application. It has zero learning curve as it
follows similar interface as DefaultCrudRepository. For relational databases,
Sequelize is a popular ORM of choice.
For pending features, refer to the Limitations section below.
> Experimental packages provide early access to advanced or experimental
> functionality to get community feedback. Such modules are published to npm
> using 0.x.y versions. Their APIs and functionality may be subject to
> breaking changes in future releases.
To install this extension in your Loopback 4 project, run the following command:
``sh`
npm install @loopback/sequelize
You'll also need to install the driver for your preferred database:
`sh`One of the following:
npm install --save pg pg-hstore # Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious # Microsoft SQL Server
npm install --save oracledb # Oracle Database
> You can watch a video overview of this extension by
> clicking here.
Both newly developed and existing projects can benefit from the extension by
simply changing the parent classes in the target Data Source and Repositories.
Change the parent class from juggler.DataSource to SequelizeDataSource like
below.
`ts
// ...
import {SequelizeDataSource} from '@loopback/sequelize';
// ...
export class PgDataSource
extends SequelizeDataSource
implements LifeCycleObserver {
// ...
}
`
SequelizeDataSource accepts commonly used config in the same way as LoopBacksequelizeOptions
did. So in most cases you won't need to change your existing configuration. But
if you want to use sequelize specific options pass them in
like below:
`ts`
let config = {
name: 'db',
connector: 'postgresql',
sequelizeOptions: {
username: 'postgres',
password: 'secret',
dialectOptions: {
ssl: {
rejectUnauthorized: false,
ca: fs.readFileSync('/path/to/root.crt').toString(),
},
},
},
};
> Note: Options provided in sequelizeOptions will take priority over others,config.password
> For example, if you have password specified in both andconfig.password.sequelizeOptions
> the latter one will be used.
Change the parent class from DefaultCrudRepository toSequelizeCrudRepository like below.
`ts
// ...
import {SequelizeCrudRepository} from '@loopback/sequelize';
export class YourRepository extends SequelizeCrudRepository<
YourModel,
typeof YourModel.prototype.id,
YourModelRelations
> {
// ...
}
`
With SequelizeCrudRepository, you can utilize following relations without any
additional configuration:
1. HasMany Relation
2. BelongsTo Relation
3. HasOne Relation
4. HasManyThrough Relation
5. ReferencesMany Relation
The default relation configuration, generated using the
lb4 relation command
(i.e. inclusion resolvers in the repository and property decorators in the
model), remain unchanged.
> Check the demo video of using inner joins here:
> https://youtu.be/ZrUxIk63oRc?t=76
When using SequelizeCrudRepository, the find(), findOne(), andfindById() methods accept a new option called required in the includetrue
filter. Setting this option to will result in an inner join query that
explicitly requires the specified condition for the child model. If the row does
not meet this condition, it will not be fetched and returned.
An example of the filter object might look like this to fetch the books who
contains "Art" in their title, which belongs to category "Programming":
`json`
{
"where": {"title": {"like": "%Art%"}},
"include": [
{
"relation": "category",
"scope": {
"where": {
"name": "Programming"
}
},
"required": true // 👈
}
]
}
A Sequelize repository can perform operations in a transaction using the
beginTransaction() method.
When you call beginTransaction(), you can optionally specify a transaction
isolation level. It support the following isolation levels:
- Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED (default)Transaction.ISOLATION_LEVELS.READ_COMMITTED
- Transaction.ISOLATION_LEVELS.REPEATABLE_READ
- Transaction.ISOLATION_LEVELS.SERIALIZABLE
-
Following are the supported options:
`ts`
{
autocommit?: boolean;
isolationLevel?: Transaction.ISOLATION_LEVELS;
type?: Transaction.TYPES;
deferrable?: string | Deferrable;
/**
* Parent transaction.
*/
transaction?: Transaction | null;
}
`ts@repository
// Get repository instances. In a typical application, instances are injected
// via dependency injection using decorator.
const userRepo = await app.getRepository(UserRepository);
// Begin a new transaction.
// It's also possible to call userRepo.dataSource.beginTransaction instead.
const tx = await userRepo.beginTransaction({
isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
});
try {
// Then, we do some calls passing this transaction as an option:
const user = await userRepo.create(
{
firstName: 'Jon',
lastName: 'Doe',
},
{transaction: tx},
);
await userRepo.updateById(
user.id,
{
firstName: 'John',
},
{transaction: tx},
);
// If the execution reaches this line, no errors were thrown.
// We commit the transaction.
await tx.commit();
} catch (error) {
// If the execution reaches this line, an error was thrown.
// We rollback the transaction.
await tx.rollback();
}
`
Switching from loopback defaults to sequelize transaction is as simple as
this commit
in
loopback4-sequelize-transaction-example.
There are three built-in debug strings available in this extension to aid in
debugging. To learn more about how to use them, see
this page.
| String | Description |
|---|---|
| Datasource | |
| loopback:sequelize:datasource | Database Connections logs |
| loopback:sequelize:queries | Logs Executed SQL Queries and Parameters |
| Repository | |
| loopback:sequelize:modelbuilder | Logs Translation of Loopback Models Into Sequelize Supported Definitions. Helpful When Debugging Datatype Issues |
Please note, the current implementation does not support the following:
1. Loopback Migrations (via default migrate.ts). Though you're good if usingdb-migrate
external packages like
.
Community contribution is welcome.
Run npm test` from the root folder.
See
all contributors.