2.0.0 • Published 4 years ago

@zthun/dal v2.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

Description

This package is an abstraction around the data access layer for @zthun scoped server projects.

Installation

npm install @zthun/dal --save

Usage

// app.ts
import { Module } from '@nestjs/common';
import { ZDatabaseMongo } from '@zthun/dal';

@Module({
  providers: [
    {
      provide: 'AnimalsDatabase',
      useValue: ZDatabaseMongo.connect('animals', 'localhost', 9995)
    }
  ]
})
export class ApplicationModule { }
// animals.controller.ts
import { Controller } from '@nextjs/common';
import { IZDatabase } from '@zthun/dal';

@Controller('cats')
export class AnimalsController {
  public constructor(
    @Inject('AnimalsDatabase')
    private readonly _dal: IZDatabase) { }

  @Get()
  public async list() {
    return await this._dal.read('cats')
      // Build sorts
      // .sort('type', SortAscending)
      // .sort('name', SortAscending)
      // 1st page
      // .page(0)
      // defaults to infinite if not set.
      // .size(200)
      .run();
  }

  @Get(':id')
  public async get(@Param() params: any) {
    const cats = await this._dal.read('cats')
      .filter({_id: {$eq: params.id}})
      .run();
    // Assert.found(cats, `Could not find a cat with id: ${params.id}`);
    return cats[0];
  }
}

Testing

WARNING: In memory databases are mostly used for mocks and testing. Don't use this in production.

describe('AnimalsController', () => {
  let dal: IZDatabase;
  let cats: ICat[];

  function createTestTarget() {
    return new AnimalsController(dal);
  }

  beforeAll(async () => {
    // Not required, but can speed up tests.
    await ZDatabaseMemory.start();
    dal = ZDatabaseMemory.connect('animals');
  });

  beforeEach(() => {
    cats = ....whatever;
  });

  afterEach(async () => {
    await dal.delete('cats').run();
  });

  afterAll(async () => {
    await ZDatabaseMemory.kill();
  });

  it('returns all cats.', async () => {
    // Arrange
    const target = createTestTarget();
    await dal.create(cats).run();
    // Act
    const actual = await target.list();
    // Assert
    expect(actual).toEqual(cats);
  });

  it('returns one cat.', async () => {
    // Arrange
    const target = createTestTarget();
    await dal.create(cats).run();
    // Act
    const actual = await target.get({id: 2});
    // Assert
    expect(actual.id).toEqual(2);
  });
});

Contributions

git clone https://github.com/zthun/zdal
cd zdal
npm install
npm run make