Search code examples
graphqlnestjstypeormdataloader

graphql dataloader Cannot read property 'load' of undefined error


I would like to bring the location data that exists below the location_group table. You are trying to use DataLoader because n + 1 problem exists.

I thought it was done, but when I actually run the code, I get a Cannot read property 'load' of undefined error. Could you tell me why this error occurs?

Resolver code:

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 code:

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 code:

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[]>;
}

The result value when the DataLoader is not used. enter image description here

The result value when the DataLoader is used. enter image description here


Solution

  • I found the answer.

    import DataLoader from 'dataloader';

    =>

    import * as DataLoader from 'dataloader';

    It is very sad that I have spent two days on this issue.