Created
May 7, 2019 03:50
-
-
Save Mando75/37ae5a636a31836363ee4dd39b37088d to your computer and use it in GitHub Desktop.
GraphQL Dataloader factory TypeORM Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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