我想将存在于 location_group
表下方的位置数据。您正在尝试使用 DataLoader
,因为存在 n + 1 问题。
我以为已经完成了,但是当我实际运行代码时,我得到一个 Cannot read property 'load' of undefined error
。你能告诉我为什么会出现这个错误吗?
Resolver
代码:
import {
Args,
Context,
ID,
Mutation,
Parent,
Query,
ResolveField,
Resolver
} from '@nestjs/graphql';
import { Location_Group } from 'src/entities/location_group.entity';
import { Location } from 'src/entities/location.entity';
import { LocationDataInput } from 'src/input_graphQl/LocationDataInput.input';
import { LocationGroupDataInput } from 'src/input_graphQl/LocationGroupDataInput.input';
import { LocationService } from './location.service';
import { LocationGroupWhereInput } from 'src/input_graphQl/LocationGroupWhereInput.input';
import { GeoJSONPoint } from 'src/scalar/geoJSONPoint.scalar';
import { LocationConText } from 'src/loader/LocationConText.context';
@Resolver(() => Location_Group)
export class LocationResolver2 {
constructor(private readonly locationService: LocationService) {}
@ResolveField(() => [Location])
locations(
@Parent() location_group: Location_Group,
@Context() ctx: LocationConText
): Promise<Location[]> {
console.log(location_group);
return ctx.LocationDataLoader.load(location_group.id);
}
}
DataLoader
代码:
import DataLoader from 'dataloader';
import { Location_Group } from 'src/entities/location_group.entity';
import { getRepository } from 'typeorm';
export const LocationDataLoader = () =>
new DataLoader(async (keys: number[]) => {
const loc = await getRepository(Location_Group)
.createQueryBuilder('lg')
.leftJoinAndSelect('lg.locations', 'locations')
.where('lg.id IN (:...keys)', { keys })
.getMany();
return loc.map((element) => element.locations);
});
LocationConText
代码:
import DataLoader from 'dataloader';
import { Request, Response } from 'express';
import { Location } from 'src/entities/location.entity';
export interface LocationConText {
req: Request;
res: Response;
LocationDataLoader: DataLoader<number, Location[]>;
}
答案 0 :(得分:0)
我找到了答案。
从'dataloader'导入DataLoader;
=>
import * as DataLoader from 'dataloader';
很遗憾我在这个问题上花了两天时间。