typeorm#getCustomRepository TypeScript Examples

The following examples show how to use typeorm#getCustomRepository. 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: plugin-settings.ts    From Cromwell with MIT License 6 votes vote down vote up
findPlugin = async (pluginName: string): Promise<TPluginEntity | undefined> => {
    const pluginRepo = getCustomRepository(GenericPlugin.repository);
    try {
        return await pluginRepo.findOne({
            where: {
                name: pluginName
            }
        });
    } catch (error) {
        getLogger().error(error);
    }
}
Example #2
Source File: CreateTransactionService.ts    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
public async execute({
    title,
    value,
    type,
    category,
  }: Request): Promise<Transaction> {
    const transactionsRepository = getCustomRepository(TransactionsRepository);
    const categoryRepository = getRepository(Category);

    if (type === 'outcome') {
      const { total } = await transactionsRepository.getBalance();

      if (value > total) {
        throw new AppError('Value for outcome is bigger than total value');
      }
    }

    let categoryExists = await categoryRepository.findOne({
      where: { title: category },
    });

    if (!categoryExists) {
      categoryExists = categoryRepository.create({ title: category });
      await categoryRepository.save(categoryExists);
    }

    const transaction = transactionsRepository.create({
      title,
      value,
      type,
      category_id: categoryExists.id,
    });

    await transactionsRepository.save(transaction);

    return transaction;
  }
Example #3
Source File: AnswerController.ts    From NextLevelWeek with MIT License 6 votes vote down vote up
async execute(req: Request, res: Response) {
        const { value } = req.params;
        const { u } = req.query;

        const surveysUsersRepository = getCustomRepository(
            SurveysUsersRepository
        );

        // Buscando de dentro do repositório se existe.
        const surveyUser = await surveysUsersRepository.findOne({
            id: String(u),
        });

        // Se não existir retorna o erro.
        if (!surveyUser) {
            throw new AppError("Survey user does not exists!");
        }

        // Se existir, vamos sobrescrever o value.
        surveyUser.value = Number(value);

        await surveysUsersRepository.save(surveyUser);

        return res.status(201).json(surveyUser);
    }
Example #4
Source File: permissions.ts    From gobarber-project with MIT License 6 votes vote down vote up
async function decoder(request: Request): Promise<User | undefined> {
  const authHeader = request.headers.authorization || "";
  const userRepository = getCustomRepository(UserRepository);

  const [, token] = authHeader?.split(" ");

  const payload = decode(token);

  const user = await userRepository.findOne(payload?.sub, {
    relations: ["roles"],
  });

  return user;
}
Example #5
Source File: product-showcase.resolver.ts    From Cromwell with MIT License 5 votes vote down vote up
@Query(() => PagedProduct)
    async pluginProductShowcase(@Arg("slug", { nullable: true }) slug?: string): Promise<TPagedList<TProduct>> {
        logger.log('ProductShowcaseResolver::productShowcase slug:' + slug);
        const timestamp = Date.now();

        let products: TPagedList<TProduct> = {
            elements: []
        };
        const settings = await getCustomRepository(PluginRepository).getPluginSettings<TSettings>('@cromwell/plugin-product-showcase');
        const maxSize = settings?.size ?? 20;

        if (slug) {
            const product = await this.productRepo.getBySlug(slug, ['categories']);
            if (!product?.id) throw new HttpException('Product with slug ' + slug + ' was not found!', HttpStatus.NOT_FOUND);

            // Gather products from all related categories until reach limit (maxSize)
            for (const category of product.categories ?? []) {
                if (category?.id) {
                    const categoryProducts = await this.productRepo.getProductsFromCategory(category.id, {
                        pageSize: maxSize
                    });
                    if (categoryProducts?.elements && products.elements) {
                        for (const prod of categoryProducts.elements) {

                            // Differnt categories may contain same products, we don't want to duplicate them
                            if (products.elements.some(addedProd => addedProd.id === prod.id)) continue;

                            products.elements.push(prod);

                            if (products.elements.length >= maxSize) break;
                        }

                    }
                }

                if (products.elements?.length &&
                    products.elements?.length >= maxSize) break;
            }

            if (products.elements && products.elements.length < maxSize) {
                (await this.productRepo.getProducts({ pageSize: maxSize }))?.elements?.forEach(prod => {
                    if (products.elements && products.elements.length < maxSize) {
                        products.elements?.push(prod);
                    }
                })
            }
        } else {
            products = await this.productRepo.getProducts({ pageSize: maxSize });
        }

        const timestamp2 = Date.now();
        logger.log('ProductShowcaseResolver::productShowcase time elapsed: ' + (timestamp2 - timestamp) + 'ms');

        return products;
    }
Example #6
Source File: transactions.routes.ts    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
transactionsRouter.get('/', async (req, res) => {
  const transactionsRepository = getCustomRepository(TransactionsRepository);
  const transactions = await transactionsRepository.find();
  const balance = await transactionsRepository.getBalance();

  return res.json({ transactions, balance });
});
Example #7
Source File: class.routes.ts    From Project-template-TS with Apache License 2.0 5 votes vote down vote up
classRouter.get('/:name', async (request, response) => {
  const repository = getCustomRepository(ClassRepository);
  const res = await repository.findByName(request.params.name);
  response.json(res);
});
Example #8
Source File: discipline.routes.ts    From Typescript_TypeORM with Apache License 2.0 5 votes vote down vote up
disciplineRouter.get('/:name', async (request, response) => {
  const repository = getCustomRepository(DisciplineRepository);
  const res = await repository.findByName(request.params.name);
  response.json(res);
});
Example #9
Source File: NpsController.ts    From NextLevelWeek with MIT License 5 votes vote down vote up
/**
     * 1 2 3 4 5 6 7 8 9 10
     * Detratores => 0 - 6
     * Passivos => 7 - 8
     * Promotores => 9 - 10
     * (Número de promotores — número de detratores) / (número de respondentes) x 100
     */
    async execute(req: Request, res: Response) {
        const { survey_id } = req.params;

        const surveysUsersRepository = getCustomRepository(
            SurveysUsersRepository
        );

        const surveysUsers = await surveysUsersRepository.find({
            survey_id,
            value: Not(IsNull()),
        });

        // Dentro dessa resposta vamos filtrar os que são detratores, passivos ou promotores;
        const detractor = surveysUsers.filter(
            (survey) => survey.value >= 0 && survey.value <= 6
        ).length;

        const passive = surveysUsers.filter(
            (survey) => survey.value >= 7 && survey.value <= 8
        ).length;

        const promoters = surveysUsers.filter(
            (survey) => survey.value >= 9 && survey.value <= 10
        ).length;

        // Total de respostas.
        const totalAnswers = surveysUsers.length;

        const calculate = Number(
            (((promoters - detractor) / totalAnswers) * 100).toFixed(2)
        );

        return res.json({
            detractor,
            passive,
            promoters,
            totalAnswers,
            nps: calculate,
        });
    }
Example #10
Source File: create-generic-entity.ts    From Cromwell with MIT License 4 votes vote down vote up
createGenericEntity = <EntityType, EntityInputType = EntityType>(entityName: string,
    EntityClass: new (...args: any[]) => EntityType,
    InputEntityClass?: new (...args: any[]) => EntityInputType) => {

    @EntityRepository(EntityClass)
    class GenericRepository extends BaseRepository<EntityType, EntityInputType> {
        constructor() {
            super(EntityClass)
        }
    }

    @ObjectType(`Paged${entityName}`)
    class PagedEntity implements TPagedList<EntityType> {
        @Field(() => PagedMeta, { nullable: true })
        pagedMeta?: PagedMeta;

        @Field(() => [EntityClass], { nullable: true })
        elements?: EntityType[];
    }

    @ArgsType()
    class CreateArgs {
        @Field(() => InputEntityClass ?? String)
        data: EntityInputType;
    }

    @ArgsType()
    class UpdateArgs {
        @Field(() => Int)
        id: number;

        @Field(() => InputEntityClass ?? String)
        data: EntityInputType;
    }

    const getPagedPath = GraphQLPaths.Generic.getManyPaged + entityName;
    const getAllPath = GraphQLPaths.Generic.getMany + entityName;
    const getBySlugPath = GraphQLPaths.Generic.getOneBySlug + entityName;
    const getByIdPath = GraphQLPaths.Generic.getOneById + entityName;
    const createPath = GraphQLPaths.Generic.create + entityName;
    const updatePath = GraphQLPaths.Generic.update + entityName;
    const deletePath = GraphQLPaths.Generic.delete + entityName;
    const getFilteredPath = GraphQLPaths.Generic.getFiltered + entityName;

    @Resolver(EntityClass, { isAbstract: true })
    abstract class GenericResolver {

        private repository = getCustomRepository(GenericRepository)

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => PagedEntity)
        async [getPagedPath](@Arg("pagedParams") pagedParams: PagedParamsInput<EntityType>):
            Promise<TPagedList<EntityType>> {
            return this.repository.getPaged(pagedParams);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => [EntityClass])
        async [getAllPath](): Promise<EntityType[]> {
            return this.repository.getAll();
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => EntityClass)
        async [getBySlugPath](@Arg("slug") slug: string): Promise<EntityType | undefined> {
            return this.repository.getBySlug(slug);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => EntityClass)
        async [getByIdPath](@Arg("id", () => Int) id: number): Promise<EntityType | undefined> {
            return this.repository.getById(id);
        }

        @Authorized<TAuthRole>("administrator", "guest", "author")
        @Query(() => PagedEntity)
        async [getFilteredPath](
            @Arg("pagedParams", () => PagedParamsInput, { nullable: true }) pagedParams?: PagedParamsInput<EntityType>,
            @Arg("filterParams", () => BaseFilterInput, { nullable: true }) filterParams?: BaseFilterInput,
        ): Promise<TPagedList<EntityType> | undefined> {
            return this.repository.getFilteredEntities(pagedParams, filterParams);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => EntityClass)
        async [createPath](@Args() { data }: CreateArgs): Promise<EntityType> {
            return this.repository.createEntity(data);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => EntityClass)
        async [updatePath](@Args() { id, data }: UpdateArgs): Promise<EntityType> {
            return this.repository.updateEntity(id, data);
        }

        @Authorized<TAuthRole>("administrator")
        @Mutation(() => Boolean)
        async [deletePath](@Arg("id", () => Int) id: number): Promise<boolean> {
            return this.repository.deleteEntity(id);
        }

    }

    return {
        abstractResolver: GenericResolver as any,
        repository: GenericRepository as TObjectType<BaseRepository<EntityType, EntityInputType>>,
        pagedEntity: PagedEntity as any,
        createArgs: CreateArgs as any,
        updateArgs: UpdateArgs as any,
    }
}