All files / blog/adapters/database blog.repository.ts

30.43% Statements 7/23
25% Branches 1/4
42.85% Functions 3/7
23.8% Lines 5/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                    1x     3x   3x                                                         1x                 1x                          
import { IBlogRepository } from '../../domain/blog.repository';
import { BlogPrincipal, BlogRecord } from '../../domain/models/blog.model';
import { EntityManager } from '@mikro-orm/core';
import { BlogDataMapper } from './blog.mapper';
import { Inject, Injectable } from '@nestjs/common';
import { contexts } from '../../../constants';
import { InjectEntityManager } from '@mikro-orm/nestjs';
import { BlogEntity } from './entities/main/blog.entity';
 
@Injectable()
class BlogRepository implements IBlogRepository {
  constructor(
    @InjectEntityManager(contexts.MAIN)
    private readonly db: EntityManager,
    @Inject(BlogDataMapper)
    private readonly mapper: BlogDataMapper,
  ) {}
 
  async create(blog: BlogRecord): Promise<BlogPrincipal> {
    const data = this.mapper.fromRecord(blog);
    this.db.create(BlogEntity, data);
    this.db.persist(data);
    await this.db.flush();
    return this.mapper.toPrincipal(data);
  }
 
  async delete(id: string): Promise<void> {
    const blog = this.db.getReference(BlogEntity, id);
    await this.db.remove(blog).flush();
  }
 
  async get(id: string): Promise<BlogPrincipal | null> {
    const blog = await this.db.findOne(BlogEntity, id);
    if (!blog) {
      return null;
    }
    return this.mapper.toPrincipal(blog);
  }
 
  async search(
    search?: string,
    limit?: number,
    skip?: number,
  ): Promise<BlogPrincipal[]> {
    const r = await this.db.find(
      BlogEntity,
      search == null
        ? {}
        : {
            text: { $like: `%${search}%` },
          },
      { limit, offset: skip },
    );
    return r.map(x => this.mapper.toPrincipal(x));
  }
 
  async update(id: string, blog: BlogRecord): Promise<BlogPrincipal> {
    const v2 = this.mapper.fromRecord(blog);
    const v1 = this.db.getReference(BlogEntity, id);
    Object.assign(v1, v2);
    await this.db.flush();
    return this.mapper.toPrincipal(v1);
  }
}
 
export { BlogRepository };