typeorm#Repository TypeScript Examples

The following examples show how to use typeorm#Repository. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: collections.utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
getCollectionData = async (
  sites: Site[],
  latestDataRepository: Repository<LatestData>,
): Promise<Record<number, CollectionDataDto>> => {
  const siteIds = sites.map((site) => site.id);

  if (!siteIds.length) {
    return {};
  }

  // Get latest data
  const latestData: LatestData[] = await latestDataRepository
    .createQueryBuilder('latest_data')
    .select('id')
    .addSelect('timestamp')
    .addSelect('value')
    .addSelect('site_id', 'siteId')
    .addSelect('survey_point_id', 'surveyPointId')
    .addSelect('metric')
    .addSelect('source')
    .where('site_id IN (:...siteIds)', { siteIds })
    .andWhere('source != :hoboSource', { hoboSource: SourceType.HOBO })
    .getRawMany();

  // Map data to each site and map each site's data to the CollectionDataDto
  return _(latestData)
    .groupBy((o) => o.siteId)
    .mapValues<CollectionDataDto>((data) =>
      data.reduce<CollectionDataDto>((acc, siteData): CollectionDataDto => {
        return {
          ...acc,
          [siteData.metric]: siteData.value,
        };
      }, {}),
    )
    .toJSON();
}
Example #2
Source File: card.repository.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@EntityRepository(Card)
export class CardRepository extends Repository<Card> {
  async useCard(id: number): Promise<Card> {
    const card = await this.findOne(id);
    if (!card) throw new NotFoundException();
    if (card.getStatus()) throw new BadRequestException();
    const usingCard = (
      await this.find({
        where: { using: true, type: card.getType() },
      })
    ).length;
    if (usingCard >= 150 && card.getType() == 0)
      throw new BadRequestException();
    if (usingCard >= 150 && card.getType() == 1)
      throw new BadRequestException();
    card.useCard();
    await this.save(card);
    return card;
  }

  async returnCard(card: Card): Promise<void> {
    if (!card.getStatus()) throw new BadRequestException();
    card.returnCard();
    await this.save(card);
  }
}
Example #3
Source File: TransactionsRepository.ts    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
@EntityRepository(Transaction)
class TransactionsRepository extends Repository<Transaction> {
  public async getBalance(): Promise<Balance> {
    const transactions = await this.find();

    const income = transactions.reduce((incomeIncrement, transaction) => {
      if (transaction.type === 'income') {
        return incomeIncrement + transaction.value;
      }

      return incomeIncrement + 0;
    }, 0);

    const outcome = transactions.reduce((outcomeIncrement, transaction) => {
      if (transaction.type === 'outcome') {
        return outcomeIncrement + transaction.value;
      }

      return outcomeIncrement + 0;
    }, 0);

    return {
      income,
      outcome,
      total: income - outcome,
    };
  }
}
Example #4
Source File: comments.entity.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
/**
   * Called before post insertion.
   */

  async afterInsert(event: InsertEvent<CommentEntity>) {
    const postRepo: Repository<PostEntity> = event.connection.manager.getRepository<
      PostEntity
    >('posts');
    const commentRepo: Repository<CommentEntity> = event.connection.manager.getRepository<
      CommentEntity
    >('comments');
    commentRepo
      .count({
        where: { post: { id: event.entity.post.id } },
      })
      .then((count: number) => {
        postRepo.update({ id: event.entity.post.id }, { comments_num: count });
      });
  }
Example #5
Source File: 1575943176180-Python27.ts    From barista with Apache License 2.0 6 votes vote down vote up
public async down(queryRunner: QueryRunner): Promise<any> {
    const repo: Repository<PackageManager> = this.connection.getRepository(PackageManager);

    await repo.delete({ code: 'python2_7-pip' });

    const python3 = await repo.findOne('python3-pip');

    delete python3.metaData;
    python3.description = 'Python3 + Pip';
    await repo.save(python3);
  }
Example #6
Source File: user.repository.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
constructor(
    @InjectRepository(UserOrmEntity)
    private readonly userRepository: Repository<UserOrmEntity>,
  ) {
    super(
      userRepository,
      new UserOrmMapper(UserEntity, UserOrmEntity),
      new Logger('UserRepository'),
    );
  }
Example #7
Source File: user.service.ts    From svvs with MIT License 6 votes vote down vote up
/**
   * Inject into UserService: userRepository
   *
   * @param userRepository
   */
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {
  }
Example #8
Source File: CashSplitSumRepository.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
@Service()
@EntityRepository(CashSplitSum)
export default class CashSplitSumRepository extends Repository<CashSplitSum> {
    async findCustom(parameters: TransactionDatabaseParameters): Promise<CashSplitSum[]> {
        let qb = this.createQueryBuilder('s');

        qb = QueryBuilderUtil.addDateFilter(
            qb,
            's',
            'createdDate',
            parameters.createdDateFrom,
            parameters.createdDateTo,
        );
        qb = QueryBuilderUtil.addDateFilter(
            qb,
            's',
            'updatedDate',
            parameters.updatedDateFrom,
            parameters.updatedDateTo,
        );

        if (parameters.accountIdList && parameters.accountIdList.length > 0) {
            qb = qb.andWhere(`s.accountId IN ( ${parameters.accountIdList.join(', ')} )`);
        }

        if (parameters.currencyIdList && parameters.currencyIdList.length > 0) {
            qb = qb.andWhere(`s.currencyId IN ( ${parameters.currencyIdList.join(', ')} )`);
        }

        return await qb.getMany();
    }

    async deleteAll(): Promise<DeleteResult> {
        return await this.createQueryBuilder().delete().execute();
    }
}
Example #9
Source File: ClassRepository.ts    From Project-template-TS with Apache License 2.0 6 votes vote down vote up
@EntityRepository(Class)
export default class ClassRepository extends Repository<Class> {
  public async findByName(name: string): Promise<Class[]> {
    return this.find({
      where: {
        name,
      },
    });
  }
}
Example #10
Source File: app.service.ts    From nest_transact with MIT License 6 votes vote down vote up
constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Purse)
    private readonly purseRepository: Repository<Purse>,
    /**
     * [PurseSavingService] injected to current service
     * and all its methods will be transactional in the transaction
     * which will be initiated from the [AppController]
     */
    private readonly purseSavingService: PurseSavingService,
    moduleRef: ModuleRef,
  ) {
    super(moduleRef);
  }
Example #11
Source File: DisciplineRepository.ts    From Typescript_TypeORM with Apache License 2.0 6 votes vote down vote up
@EntityRepository(Discipline)
export default class DisciplineRepository extends Repository<Discipline> {
  public async findByName(name: string): Promise<Discipline[]> {
    return this.find({
      where: {
        name,
      },
    });
  }
}
Example #12
Source File: main.ts    From prox2 with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function reviveConfessions(repository: Repository<Confession>) {
  console.log(`Getting unviewed confessions...`);
  let unviewedConfessions;
  try {
    unviewedConfessions = await repository.find({ viewed: false });
  } catch (_) {
    throw `Failed to fetch unviewed confessions!`;
  }
  for (const record of unviewedConfessions) {
    console.log(`Removing old message (if any) and ignoring errors...`);
    if (record.staging_ts) {
      try {
        await web.chat.delete({
          channel: staging_channel,
          ts: record.staging_ts,
        });
      } catch (_) {
        console.log(
          `Warning: failed to delete staging message... continuing anyways`
        );
      }
    }
    const newTs = await postStagingMessage(record.id, record.text);
    console.log(`Updating record...`);
    try {
      record.staging_ts = newTs;
      await repository.save(record);
    } catch (_) {
      throw `Failed to update Postgres record!`;
    }
  }
  console.log(`Restaged all unviewed confessions!`);
}
Example #13
Source File: augment-site-data.ts    From aqualink-app with MIT License 6 votes vote down vote up
async function getRegion(
  longitude: number,
  latitude: number,
  regionRepository: Repository<Region>,
) {
  const googleRegion = await getGoogleRegion(longitude, latitude);
  const regions = await regionRepository.find({
    where: { name: googleRegion },
  });

  if (regions.length > 0) {
    return regions[0];
  }
  return googleRegion
    ? regionRepository.save({
        name: googleRegion,
        polygon: createPoint(longitude, latitude),
      })
    : undefined;
}
Example #14
Source File: polymorphic.repository.ts    From typeorm-polymorphic with MIT License 6 votes vote down vote up
private findRepository(
    entityType: Function,
  ): Repository<PolymorphicChildInterface | never> {
    const repositoryToken = this.resolveRepositoryToken(entityType);

    const repository: Repository<PolymorphicChildInterface> =
      repositoryToken !== entityType
        ? this.manager.getCustomRepository(repositoryToken)
        : this.manager.getRepository(repositoryToken);

    if (!repository) {
      throw new RepositoryNotFoundException(repositoryToken);
    }

    return repository;
  }
Example #15
Source File: product.entity.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@EntityRepository(Product)
export class ProductRepository extends Repository<Product> {
  private perPage: 20;

  public search(filters: ProductSearchFilters): SelectQueryBuilder<Product> {
    const query = this.createQueryBuilder()
      .where('published IS TRUE')
      .orderBy('updatedAt', 'DESC');

    if (filters.title !== undefined) {
      query.andWhere('lower(title) LIKE :title', {title: `%${filters.title}%`});
    }

    if (filters.priceMin !== undefined) {
      query.andWhere('price >= :priceMin', {priceMin: filters.priceMin});
    }

    if (filters.priceMax !== undefined) {
      query.andWhere('price <= :priceMax', {priceMax: filters.priceMax});
    }

    return query;
  }

  public paginate(
    query: SelectQueryBuilder<Product>,
    page: number | string,
  ): SelectQueryBuilder<Product> {
    if (page) {
      console.log(Number(page));
      query.offset(Number(page) * this.perPage);
    }

    return query.limit(this.perPage);
  }
}
Example #16
Source File: article.repository.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@EntityRepository(Article)
export class ArticleRepository extends Repository<Article> {
  async getById(id: number): Promise<Article> {
    const article = await this.findOne(id);
    if (!article) {
      throw new NotFoundException();
    }

    return article;
  }
}
Example #17
Source File: form.update.service.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(
    @InjectRepository(FormEntity)
    private readonly formRepository: Repository<FormEntity>,
    @InjectRepository(FormFieldEntity)
    private readonly formFieldRepository: Repository<FormFieldEntity>,
    @InjectRepository(FormHookEntity)
    private readonly formHookRepository: Repository<FormHookEntity>,
    private readonly idService: IdService,
    private readonly pageService: FormPageUpdateService,
  ) {
  }
Example #18
Source File: log.repository.ts    From 42_checkIn with GNU General Public License v3.0 5 votes vote down vote up
@EntityRepository(Log)
export class LogRepository extends Repository<Log> {}
Example #19
Source File: cms.service.ts    From Cromwell with MIT License 5 votes vote down vote up
public async buildSitemap() {
        const settings = await getCmsSettings();
        if (!settings?.url) throw new HttpException("CmsService::buildSitemap: could not find website's URL", HttpStatus.INTERNAL_SERVER_ERROR);
        if (!settings.themeName) throw new HttpException("CmsService::buildSitemap: could not find website's themeName", HttpStatus.INTERNAL_SERVER_ERROR);
        const configs = await getThemeConfigs(settings.themeName);
        setStoreItem('defaultPages', configs.themeConfig?.defaultPages);

        const urls: string[] = [];
        let content = '';

        const addPage = (route: string, updDate: Date) => {
            if (!route.startsWith('/')) route = '/' + route;
            const redirect = findRedirect(route);
            if (redirect?.type === 'redirect' && redirect.to) {
                route = redirect.to;
            }

            if (redirect?.type === 'rewrite' && redirect.from === '/404') return;

            if (!route.startsWith('http')) {
                route = settings.url + route;
            }

            if (urls.includes(route)) return;
            urls.push(route);

            content +=
                `  <url>
    <loc>${route}</loc>
    <lastmod>${format(updDate, 'yyyy-MM-dd')}</lastmod>
  </url>\n`;
        }

        configs.themeConfig?.pages?.forEach(page => {
            if (!page.route || page.route.includes('[slug]') ||
                page.route.includes('[id]') || page.route === 'index'
                || page.route === '404') return;

            addPage(
                page.route,
                new Date(Date.now())
            );
        })

        const outputEntity = async (repo: Repository<any>, pageName: TDefaultPageName) => {
            const entities: BasePageEntity[] = await repo.find({
                select: ['slug', 'id', 'updateDate', 'createDate'],
            });

            entities.forEach(ent => {
                const updDate = ent.updateDate ?? ent.createDate;
                addPage(
                    resolvePageRoute(pageName, { slug: ent.slug ?? ent.id + '' }),
                    updDate ?? new Date(Date.now())
                );
            });

        }

        await outputEntity(getCustomRepository(PostRepository), 'post');
        await outputEntity(getCustomRepository(ProductRepository), 'product');
        await outputEntity(getCustomRepository(ProductCategoryRepository), 'category');
        await outputEntity(getCustomRepository(TagRepository), 'tag');

        content = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${content}
</urlset>`;

        await fs.outputFile(resolve(getPublicDir(), 'default_sitemap.xml'), content, {
            encoding: 'UTF-8'
        });
        return true;
    }
Example #20
Source File: BaseSqlRepository.ts    From node-experience with MIT License 5 votes vote down vote up
protected repository: Repository<T>;
Example #21
Source File: AppointmentsRepository.ts    From gobarber-api with MIT License 5 votes vote down vote up
private ormRepository: Repository<Appointment>;
Example #22
Source File: CustomersRepository.ts    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
private ormRepository: Repository<Customer>;
Example #23
Source File: index.ts    From context-mod with MIT License 5 votes vote down vote up
invokeeRepo: Repository<InvokeeType>;
Example #24
Source File: PostCommentRepository.ts    From jaebook-server with MIT License 5 votes vote down vote up
@EntityRepository(PostComment)
export class PostCommentRepository extends Repository<PostComment> {
  /**
   * 포스트 Id와 댓글 Id가 일치하는 댓글 정보를 조회한다.
   * @param postId 포스트 Id
   * @param commentId 댓글 Id
   */
  public async getCommentById(postId: string, commentId: string) {
    return this.createQueryBuilder("comment")
      .where("comment.id = :commentId", { commentId })
      .andWhere("comment.postId = :postId", { postId })
      .getOne();
  }

  /**
   * 포스트 Id가 일치하며 답글을 제외한 댓글들을 조회한다.
   * @param postId 포스트 Id
   */
  public async getCommentsByPostId(postId: string) {
    return this.createQueryBuilder("comment")
      .select([
        "comment.id",
        "comment.text",
        "comment.createdAt",
        "comment.postId",
        "comment.isReplies",
        "comment.isDeleted",
      ])
      .leftJoinAndSelect("comment.user", "user")
      .where("comment.postId = :postId", { postId })
      .andWhere("comment.depth = :value", { value: 0 })
      .orderBy("comment.createdAt", "ASC")
      .getMany();
  }

  /**
   * 사용자가 작성한 삭제되지 않은 댓글과 답글들을 조회한다.
   * @param userId 사용자 Id
   */
  public async getCommentsByUserId(userId: string) {
    return this.createQueryBuilder("comment")
      .select([
        "comment.id",
        "comment.text",
        "comment.createdAt",
        "comment.postId",
      ])
      .where("comment.userId = :userId", { userId })
      .andWhere("comment.isDeleted = :value", { value: false })
      .orderBy("comment.createdAt", "DESC")
      .getMany();
  }

  /**
   * 포스트 Id와 댓글 Id가 일치하는 댓글의 답글들을 조회한다.
   * @param postId 포스트 Id
   * @param commentId 댓글 Id
   */
  public async getCommentReplies(postId: string, commentId: string) {
    return this.createQueryBuilder("comment")
      .select([
        "comment.id",
        "comment.parent",
        "comment.depth",
        "comment.text",
        "comment.createdAt",
        "comment.postId",
        "comment.isDeleted",
      ])
      .leftJoinAndSelect("comment.user", "user")
      .where("comment.postId = :postId", { postId })
      .andWhere("comment.parent = :commentId", { commentId })
      .orderBy("comment.createdAt", "ASC")
      .getMany();
  }
}
Example #25
Source File: user.repository.ts    From nestjs-api-example with MIT License 5 votes vote down vote up
@EntityRepository(User)
export class UserRepository extends Repository<User> {}
Example #26
Source File: AppointmentsRepository.ts    From hotseat-api with MIT License 5 votes vote down vote up
private ormRepository: Repository<Appointment>;
Example #27
Source File: comments.service.ts    From NestJs-youtube with MIT License 5 votes vote down vote up
constructor(
    @InjectRepository(CommentEntity)
    private commentRepo: Repository<CommentEntity>,
  ) {
    super(commentRepo);
  }
Example #28
Source File: users.repository.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
constructor(
    @InjectRepository(UserEntity)
    private readonly usersModel: Repository<UserEntity>,
  ) {}
Example #29
Source File: 1573598697833-Python3PackageManager.ts    From barista with Apache License 2.0 5 votes vote down vote up
public async down(queryRunner: QueryRunner): Promise<any> {
    const repo: Repository<PackageManager> = this.connection.getRepository(PackageManager);

    await repo.delete({ code: 'python3' });
  }