import { UserInputError } from 'apollo-server'; import { merge } from 'lodash'; import { Arg, Query, Resolver } from 'type-graphql'; import { getRepository } from 'typeorm'; import { AggregateProduct } from '@/entities'; import { connectionFromQuery } from '../shared/pagination/utils'; import { AggregateProductConnection, AggregateProductInput, AggregateProductPayload, AggregateProductsInput, AGGREGATE_PRODUCTS_INPUT_DEFAULTS, DEFAULT_AGGREGATE_PRODUCT_INPUT, } from './types'; @Resolver(AggregateProduct) export class AggregateProductResolver { @Query(() => AggregateProductPayload, { nullable: false, description: `Aggregate product.`, }) async aggregateProduct( @Arg('input', { nullable: false }) inputWithoutDefaults: AggregateProductInput ): Promise { const input = merge( {}, DEFAULT_AGGREGATE_PRODUCT_INPUT, inputWithoutDefaults ); const { id } = input; if (!id) { throw new UserInputError( 'Must provide an ID when getting a specific aggregate product' ); } const aggregateProduct = await AggregateProduct.findOneOrFail(input.id); return { aggregateProduct, }; } @Query(() => AggregateProductConnection, { nullable: true }) async aggregateProducts( @Arg('first', { nullable: true }) first?: number, @Arg('last', { nullable: true }) last?: number, @Arg('before', { nullable: true }) before?: string, @Arg('after', { nullable: true }) after?: string, @Arg('input', { nullable: true }) inputWithoutDefaults?: AggregateProductsInput ): Promise { const input = merge( {}, AGGREGATE_PRODUCTS_INPUT_DEFAULTS, inputWithoutDefaults ); let query = getRepository(AggregateProduct).createQueryBuilder('AggregateProduct'); if (input?.category) { query = query.andWhere('"AggregateProduct".category = :category', { category: input.category, }); } return connectionFromQuery({ first, last, before, after }, query); } }