TypeScript EntityService extension for @ts-awesome/orm
npm install @ts-awesome/entityTypeScript EntityService extension for @ts-awesome/orm
Key features:
* @injectable via inversify
* strict type checks and definitions
* thin wrapper over base @ts-awesome/orm
* UnitOfWork and transaction management made easier
``ts
import {dbTable, dbField} from '@ts-awesome/orm';
import {serviceSymbolFor, IEntityService} from '@ts-awesome/entity';
@dbTable('some_table')
class SomeModel {
@dbField({
primaryKey: true
})
public id!: number;
@dbField
public title!: string;
@dbField({
model: Number,
nullable: true,
})
public authorId?: number | null;
@dbField({
readonly: true
})
public readonly createdAt!: Date;
}
// for more details on model definition, please check @ts-awesome/orm
// typically used with IoC containers
export const SomeModelEntityServiceSymbol = serviceSymbolFor(SomeModel);
export interface ISomeModelEntityService extends IEntityService
'id' | 'createdAt', // readonly fields
'authorId' // optional fields
> {}
`
`ts
const entityService: ISomeModelEntityService;
// find entity by primary key
const a = entityService.getOne({id: 1});
// find entities by some author
const list = entityService.get({authorId: 1});
// lets add new entity
const added = entityService.addOne({
title: 'New book'
})
// lets update some
const updated = entityService.updateOne({
id: added.id,
authorId: 5,
});
// and delete
const deleted = entityService.deleteOne({
id: added.id,
});
// also all operations support where builder
const since = new Date(Date.now() - 3600 * 1000); // an hour ago
// lets select recently created entities
const recent = entityService.get(({createdAt}) => createdAt.gte(since));
// or find total number of such
const total = entityService.count(({createdAt}) => createdAt.gte(since));
// we can build complex logic as well
const baseQuery = entityService.select().where(({createdAt}) => createdAt.gte(since));
const count = await baseQuery.count();
const first10 = await baseQuery.limit(10).fetch();
`
For more details on query builder, please check @ts-awesome/orm
`ts
import {EntityService, UnitOfWork} from "@ts-awesome/entity";
import {IBuildableQueryCompiler, IQueryExecutor, IQueryExecutorProvider} from "@ts-awesome/orm";
const driver: IQueryExecutor; // specific to orm driver
const compiler: IBuildableQueryCompiler; // specific to orm driver
const executorProvider: IQueryExecutorProvider = new UnitOfWork(driver);
const entityService: ISomeModelEntityService = new EntityService(
SomeModel,
executorProvider, // typically current UnitOfWork or orm driver executor provider
compiler, // buildable query compiler
);
`
Dynamicly create EntityService instance when requested
`ts
import {Container} from "inversify";
import {
IBuildableQueryCompiler,
IQueryExecutorProvider,
SqlQueryExecutorProviderSymbol
} from "@ts-awesome/orm";
const container: Container;
const compiler: IBuildableQueryCompiler; // specific to orm driver
container.bind
.toDynamicValue((context) => {
const executorProvider = context.get
return new EntityService
})
`
Or define explicit SomeModelEntityService class
`ts
import {Container, injectable, inject} from "inversify";
import {
IBuildableQueryCompiler,
IQueryExecutorProvider,
SqlQueryExecutorProviderSymbol,
SqlQueryBuildableQueryCompilerSymbol
} from "@ts-awesome/orm";
@injectable
class SomeModelEntityService
extends EntityService
implements ISomeModelEntityService {
constructor(
@inject(SqlQueryExecutorProviderSymbol) executorProvider: IQueryExecutorProvider,
@inject(SqlQueryBuildableQueryCompilerSymbol) compiler: IBuildableQueryCompiler,
) {
super(SomeModel, executorProvider, compiler);
}
}
const container: Container;
container.bind
.to(SomeModelEntityService)
`
UnitOfWork is used when transaction management is required. Best way to use it on
the highest level possible. For example within request handler.
Other option is to rebind IQueryExecutorProvider within IoC to UoW when needed
Sample usage
`ts
import {Container} from "inversify";
import {UnitOfWork, IUnitOfWork, UnitOfWorkSymbol} from "@ts-awesome/entity";
import {IBuildableQueryCompiler, IQueryExecutor, IQueryExecutorProvider, SqlQueryExecutorProviderSymbol} from "@ts-awesome/orm";
const driver: IQueryExecutor; // specific to orm driver
const container: Container;
container
.bind
.toDynamicValue(({context}) => new UnitOfWork(driver));
container
.rebind
.toDynamicValue(({context}) => context.get
`
Auto managed transaction
`ts
const entityService = container.get
const uow = container.get
const result = await uow.auto(async () => {
await entityService.updateOne({id: 1, authorId: null});
await entityService.deleteOne({id: 2});
return await entityService.addOne({title: 'New'});
});
auto() throws if called with invalid arguments.`
Manual managed transactions
`ts
const entityService = container.get
const uow = container.get
let result;
await uow.begin();
try {
await entityService.updateOne({id: 1, authorId: null});
await entityService.deleteOne({id: 2});
result = await entityService.addOne({title: 'New'});
await uow.commit();
} catch (e) {
await uow.rollback();
throw e;
}
`
* add() executes inserts in parallel and returns results in input order.upsertOne(values, uniqueIndex)
* uses the index fields for the WHERE clause and throws if index is unknown or values are missing.get
* , update, and delete reject empty objects and unknown fields in value-based where clauses.fetchScalar()
* and count() throw if the scalar result is not numeric.UnitOfWork.begin()` throws if a transaction is already active.
*
Copyright (c) 2022 Volodymyr Iatsyshyn and other contributors