Skip to content

Instantly share code, notes, and snippets.

@Mando75
Created May 7, 2019 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mando75/37ae5a636a31836363ee4dd39b37088d to your computer and use it in GitHub Desktop.
Save Mando75/37ae5a636a31836363ee4dd39b37088d to your computer and use it in GitHub Desktop.
GraphQL Dataloader factory TypeORM Example
import { BaseEntity as typeOrmEntity, ObjectType } from "typeorm";
import { ObjectUtils } from "typeorm/util/ObjectUtils";
import * as DataLoader from "dataloader";
// Creating our own BaseEntity Class...
export class BaseEntity extends typeOrmEntity {
id: string;
constructor() {
super();
}
/*
Create a static method that all our entities can use
This will dyanimcally call the right repository find method
based on the entity calling the loader. It will work just like
any other dataloader after initialization
*/
static getDataloader<T extends BaseEntity>(
this: ObjectType<T>,
options?: DataLoader.Options<string, T>
): DataLoader<string, T> {
const batch = async (entityIds: string[]) => {
const records = await (this as any).getRepository().findByIds(entityIds);
const recordMap: { [key: string]: T } = {};
records.forEach((record: T) => (recordMap[record.id] = record));
return entityIds.map(id => recordMap[id]);
};
return new DataLoader(batch, options);
}
}
//Example Usage:
const resolver = (id) => User.getDataloader().load(id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment