File

src/insight/insights.service.ts

Index

Methods

Constructor

constructor(insightRepository: Repository<DbInsight>, insightMemberRepository: Repository, workspaceInsightRepository: Repository, workspaceService: WorkspaceService)
Parameters :
Name Type Optional
insightRepository Repository<DbInsight> No
insightMemberRepository Repository<DbInsightMember> No
workspaceInsightRepository Repository<DbWorkspaceInsight> No
workspaceService WorkspaceService No

Methods

Async addInsight
addInsight(userId: number, workspaceId: string, insight: Partial<DbInsight>)
Parameters :
Name Type Optional
userId number No
workspaceId string No
insight Partial<DbInsight> No
Returns : unknown
baseQueryBuilder
baseQueryBuilder()
Async findAllByUserId
findAllByUserId(pageOptionsDto: InsightPageOptionsDto, userId: string)
Parameters :
Name Type Optional
pageOptionsDto InsightPageOptionsDto No
userId string No
Async findAllFeatured
findAllFeatured(pageOptionsDto: InsightPageOptionsDto)
Parameters :
Name Type Optional
pageOptionsDto InsightPageOptionsDto No
Async findOneById
findOneById(id: number, includeAll)
Parameters :
Name Type Optional Default value
id number No
includeAll No true
Returns : Promise<DbInsight>
Async findOneByIdAndUserId
findOneByIdAndUserId(id: number, userId: number)
Parameters :
Name Type Optional
id number No
userId number No
Returns : Promise<DbInsight>
Async removeInsight
removeInsight(id: number)
Parameters :
Name Type Optional
id number No
Returns : unknown
Async updateInsight
updateInsight(id: number, insight: Partial<DbInsight>)
Parameters :
Name Type Optional
id number No
insight Partial<DbInsight> No
Returns : unknown
import { Injectable, NotFoundException } from "@nestjs/common";
import { Repository, SelectQueryBuilder } from "typeorm";
import { InjectRepository } from "@nestjs/typeorm";

import { PageDto } from "../common/dtos/page.dto";
import { PageMetaDto } from "../common/dtos/page-meta.dto";

import { DbWorkspaceInsight } from "../workspace/entities/workspace-insights.entity";
import { WorkspaceService } from "../workspace/workspace.service";
import { DbInsight } from "./entities/insight.entity";
import { InsightPageOptionsDto } from "./dtos/insight-page-options.dto";
import { DbInsightMember } from "./entities/insight-member.entity";

@Injectable()
export class InsightsService {
  constructor(
    @InjectRepository(DbInsight, "ApiConnection")
    private insightRepository: Repository<DbInsight>,
    @InjectRepository(DbInsightMember, "ApiConnection")
    private insightMemberRepository: Repository<DbInsightMember>,
    @InjectRepository(DbWorkspaceInsight, "ApiConnection")
    private workspaceInsightRepository: Repository<DbWorkspaceInsight>,
    private workspaceService: WorkspaceService
  ) {}

  baseQueryBuilder(): SelectQueryBuilder<DbInsight> {
    const builder = this.insightRepository.createQueryBuilder("insights");

    return builder;
  }

  async findOneById(id: number, includeAll = true): Promise<DbInsight> {
    const queryBuilder = this.baseQueryBuilder();

    queryBuilder.leftJoin("insight_members", "insight_members").where("insights.id = :id", { id });

    if (includeAll) {
      queryBuilder.leftJoinAndSelect(`insights.repos`, `insight_repos`, `insights.id=insight_repos.insight_id`);
      queryBuilder.leftJoinAndSelect(`insights.members`, `members`, `insights.id=members.insight_id`);
    }

    queryBuilder.leftJoinAndSelect(`insights.workspaces`, `workspaces`, `insights.id=workspaces.insight_id`);

    const item: DbInsight | null = await queryBuilder.getOne();

    if (!item) {
      throw new NotFoundException();
    }

    return item;
  }

  async findOneByIdAndUserId(id: number, userId: number): Promise<DbInsight> {
    const queryBuilder = this.baseQueryBuilder();

    queryBuilder
      .leftJoin("insight_members", "insight_members", "insight_members.user_id = :userId", { userId })
      .where("insights.id = :id", { id })
      .leftJoinAndSelect(`insights.repos`, `insight_repos`, `insights.id=insight_repos.insight_id`)
      .leftJoinAndSelect(`insights.members`, `members`, `insights.id=members.insight_id`);

    const item: DbInsight | null = await queryBuilder.getOne();

    if (!item) {
      throw new NotFoundException();
    }

    return item;
  }

  async addInsight(userId: number, workspaceId: string, insight: Partial<DbInsight>) {
    let existingWorkspace;

    if (workspaceId === "") {
      existingWorkspace = await this.workspaceService.findPersonalWorkspaceByUserId(userId);
    } else {
      existingWorkspace = await this.workspaceService.findOneById(workspaceId);
    }

    const newInsight = await this.insightRepository.save(insight);

    await this.workspaceInsightRepository.save({
      insight_id: newInsight.id,
      workspace_id: existingWorkspace.id,
    });

    /* creators of insight pages are automatically an admin for them */
    await this.insightMemberRepository.save({
      user_id: userId,
      insight_id: insight.id,
      access: "admin",
    });

    return newInsight;
  }

  async updateInsight(id: number, insight: Partial<DbInsight>) {
    return this.insightRepository.update(id, insight);
  }

  async removeInsight(id: number) {
    const workspaceInsight = await this.workspaceInsightRepository.findOne({
      where: {
        insight_id: id,
      },
      withDeleted: false,
    });

    if (!workspaceInsight) {
      throw new NotFoundException("could not find workspace insight link for given insight");
    }

    await this.workspaceInsightRepository.softDelete(workspaceInsight.id);
    return this.insightRepository.softDelete(id);
  }

  async findAllByUserId(pageOptionsDto: InsightPageOptionsDto, userId: string): Promise<PageDto<DbInsight>> {
    const queryBuilder = this.insightRepository.createQueryBuilder("insights");

    queryBuilder
      .leftJoinAndSelect("insights.members", "insight_members", "insight_members.insight_id = insights.id")
      .where(
        `(
          ((SELECT COUNT(id) FROM insight_members where insight_members.user_id=:userId)=0)
          AND
          (insights.is_featured=true AND insights.deleted_at IS NULL)
        )
      `,
        { userId }
      )
      .orWhere(
        `:userId IN (
          SELECT user_id
          FROM insight_members
          WHERE insight_id = insights.id
          AND user_id = :userId
          AND access != 'pending'
          AND deleted_at IS NULL
        )
      `,
        { userId }
      )
      .leftJoinAndSelect(`insights.repos`, `insight_repos`, `insights.id=insight_repos.insight_id`)
      .orderBy("insights.updated_at", "DESC");

    queryBuilder.skip(pageOptionsDto.skip).take(pageOptionsDto.limit);

    const itemCount = await queryBuilder.getCount();
    const entities = await queryBuilder.getMany();

    const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

    return new PageDto(entities, pageMetaDto);
  }

  async findAllFeatured(pageOptionsDto: InsightPageOptionsDto): Promise<PageDto<DbInsight>> {
    const queryBuilder = this.insightRepository.createQueryBuilder("insights");

    queryBuilder
      .where("is_featured=true")
      .andWhere("is_public=true")
      .leftJoinAndSelect(`insights.repos`, `insight_repos`, `insights.id=insight_repos.insight_id`)
      .leftJoinAndSelect(`insights.members`, `members`, `insights.id=members.insight_id`)
      .orderBy("insights.updated_at", "DESC");

    queryBuilder.skip(pageOptionsDto.skip).take(pageOptionsDto.limit);

    const itemCount = await queryBuilder.getCount();
    const entities = await queryBuilder.getMany();

    const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

    return new PageDto(entities, pageMetaDto);
  }
}

results matching ""

    No results matching ""