npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ts-awesome/entity

v1.5.12

Published

TypeScript EntityService extension for @ts-awesome/orm

Downloads

448

Readme

ts-awesome/entity

TypeScript EntityService extension for @ts-awesome/orm

Key features:

  • @injectable via invesify
  • strict type checks and definitions
  • thin wrapper over base @ts-awesome/orm
  • UnitOfWork and transaction management made easier

Basic model and interfaces

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

// typicly used with IoC containers 
export const SomeModelEntityServiceSymbol = serviceSymbolFor(SomeModel);

export interface ISomeModelEntityService extends IEntityService<SomeModel, 
  'id', // primary key fields 
  'id' | 'createdAt',  // readonly fields
  'authorId' // optional fields
> {}

Simple operations


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(({createAd}) => authorId.gte(since));

// or find total number of such
const total = entityService.count(({createAd}) => authorId.gte(since));

// we can build complex logic as well

const baseQuery = entityService.select().where(({createAd}) => authorId.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

Bare use


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, // typicly current UnitOfWork or orm driver executor provider
  compiler, // buildable query compiler
);

Use with IoC container

Dynamicly create EntityService instance when requested

import {Container} from "inversify";
import {
  IBuildableQueryCompiler,
  IQueryExecutorProvider,
  SqlQueryExecutorProviderSymbol
} from "@ts-awesome/orm";

const container: Container;
const compiler: IBuildableQueryCompiler;  // specific to orm driver

container.bind<ISomeModelEntityService>(SomeModelEntityServiceSymbol)
  .toDynamicValue((context) => {
    const executorProvider = context.get<IQueryExecutorProvider>(SqlQueryExecutorProviderSymbol);
    return new EntityService<SomeModel,never,never,never>(SomeModel, executorProvider, compiler);
  })

Or define explicit SomeModelEntityService class

import {Container, injectable, inject} from "inversify";
import {
  IBuildableQueryCompiler, 
  IQueryExecutorProvider, 
  SqlQueryExecutorProviderSymbol, 
  SqlQueryBuildableQueryCompilerSymbol
} from "@ts-awesome/orm";

@injectable
class SomeModelEntityService
  extends EntityService<SomeModel, 'id', 'id' | 'createdAt', 'authorId'>
  implements ISomeModelEntityService {

  constructor(
    @inject(SqlQueryExecutorProviderSymbol) executorProvider: IQueryExecutorProvider,
    @inject(SqlQueryBuildableQueryCompilerSymbol) compiler: IBuildableQueryCompiler,
  ) {
    super(SomeModel, executorProvider, compiler);
  }
}

const container: Container;
container.bind<ISomeModelEntityService>(SomeModelEntityServiceSymbol)
  .to(SomeModelEntityService)

UnitOfWork and transactions

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

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<IUnitOfWork>(UnitOfWorkSymbol)
  .toDynamicValue(({context}) => new UnitOfWork(driver));

container
  .rebind<IQueryExecutorProvider>(SqlQueryExecutorProviderSymbol)
  .toDynamicValue(({context}) => context.get<IUnitOfWork>(UnitOfWorkSymbol));

Auto managed transaction

const entityService = container.get<SomeModelEntityServiceSymbol>();
const uow = container.get<IUnitOfWork>(UnitOfWorkSymbol);

const result = await uow.auto(async () => {
  await entityService.updateOne({id: 1, authorId: null});
  await entityService.deleteOne({id: 2});
  return await entityService.addOne({title: 'New'});
});

Manual managed transactions

const entityService = container.get<SomeModelEntityServiceSymbol>();
const uow = container.get<IUnitOfWork>(UnitOfWorkSymbol);

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;
}

License

May be freely distributed under the MIT license.

Copyright (c) 2022 Volodymyr Iatsyshyn and other contributors