【发布时间】:2020-06-14 17:21:29
【问题描述】:
我正在使用 nestjs、type-graphql 和 typeorm 创建一个 graphql api。我无法找出如何进行某个查询。假设我有以下实体:
@Entity()
@ObjectType({ description: 'The user model' })
export class User extends BaseEntity {
@Field(type => ID)
@PrimaryGeneratedColumn('uuid')
readonly id: string;
@Field()
@Column()
@IsNotEmpty()
@IsEmail()
email: string;
@Field()
@IsNotEmpty()
@Column()
password: string;
@Field(type => [Project], { nullable: true })
@ManyToMany(type => Project)
@JoinTable()
projects?: Project[];
}
@Entity()
@ObjectType({ description: 'The project model' })
export class Project extends BaseEntity {
@Field(type => ID)
@PrimaryGeneratedColumn('uuid')
readonly id: string;
@Field()
@Column()
@IsNotEmpty()
description: string;
@Field(type => [User], { nullable: true })
@ManyToMany(type => User)
@JoinTable()
participants?: User[];
}
我有以下服务:
import { includes } from 'lodash';
@Injectable()
export class ProjectService {
constructor(
@InjectRepository(Project)
private projectRepository: Repository<Project>,
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
async loadAllForUser(
userId: string
): Promise<Project[]> {
const projects = await this.projectRepository.find(
{
relations: ['participants'],
},
);
return projects.filter(project =>
includes(
project.participants.map(participant => participant.id),
userId,
),
);
}
}
这将是我的解析器:
@Resolver( of => Project)
export class ProjectResolver {
constructor(
private projectService: ProjectService,
private userService: UserService,
) {}
@Query(returns => [Project])
@UseGuards(GqlAuthGuard)
async myProjects(
@GqlUser() user: User,
) {
return await this.projectService.loadAllForUser(
user.id,
);
}
}
正如您在我的项目服务中看到的,我只是使用 find 方法获取所有项目,然后我使用 lodash 中的包含过滤此列表以仅过滤掉包含用户 ID 的项目。有没有办法在项目存储库的 find 方法中添加某种操作,例如“where”或“in”,以便我可以直接从那里过滤它,而不是手动过滤和使用 lodash 中的包含?我什至不知道我手动过滤的方式是否正确?
亲切的问候,
格里
【问题讨论】:
标签: graphql nestjs typeorm typegraphql