import { Ctx, Field, ObjectType } from 'type-graphql'; import { Column, Entity, JoinTable, ManyToMany, ManyToOne } from 'typeorm'; import { AbstractEntity } from '@/entities/abstract'; import { ContextType } from '@/types'; import AggregateProductVariant from '../AggregateProduct/AggregateProductVariant'; import { User } from '../User'; @Entity({ name: 'aggregate_product_variant_saves_list' }) @ObjectType({ implements: AbstractEntity.objectTypeImplements, }) export default class AggregateProductVariantSavesList extends AbstractEntity { @ManyToMany(() => AggregateProductVariant, (variant) => variant.savesLists) @JoinTable() variants!: AggregateProductVariant[]; @Field(() => [AggregateProductVariant], { name: 'variants', nullable: false, }) async variantsResolver( @Ctx() { dbDataLoader }: ContextType ): Promise { return dbDataLoader.variantsForSavesList.load(this.id); } @ManyToOne(() => User, { nullable: false }) createdBy!: User; @Column() createdById!: string; @Field(() => User, { nullable: false, name: 'createdBy' }) async createdByResolver(@Ctx() { dbDataLoader }: ContextType): Promise { return dbDataLoader.users.load(this.createdById); } @ManyToMany(() => User, (collaborator) => collaborator.savesLists) @JoinTable() collaborators!: User[]; @Field(() => [User], { name: 'collaborators', nullable: false, }) async collaboratorsResolver( @Ctx() { dbDataLoader }: ContextType ): Promise { return dbDataLoader.collaboratorsForSavesList.load(this.id); } @Field(() => Boolean) async viewerCanEdit( @Ctx() { user, dbDataLoader }: ContextType ): Promise { if (!user) return false; if (this.createdById === user.id) return true; const collaborators = await dbDataLoader.collaboratorsForSavesList.load( this.id ); return collaborators.some((collaborator) => collaborator.id === user.id); } }