Skip to main content

ObjectLoader

ObjectLoader is the Loader used to fetch nodes from the database.

ObjectLoaderFactory

Public Facing LoaderFactory API of ObjectLoader used to create new instances of ObjectLoader as needed.

For each node, an instance of ObjectLoaderFactory is generated which is used to load the raw data from the database.

For example:

src/ent/generated/loaders.ts
export const accountLoader = new ObjectLoaderFactory({
tableName: accountTable,
fields: accountFields,
key: "id",
});

And if there are unique fields in the schema, a loader is also generated for that. So, for an account with a unique phone number, this is also generated:

src/ent/generated/loaders.ts
export const accountPhoneNumberLoader = new ObjectLoaderFactory({
tableName: accountTable,
fields: accountFields,
key: "phone_number",
});

We also make each loader aware of the other so that when data is fetched from the database via one key, we don't refetch via the other. For example, if you fetch an account via phone number and then later want to fetch that same account in the same request via its id, we reuse the row that was previously fetched. The priming is done as follows (also autogenerated):

  accountLoader.addToPrime(accountPhoneNumberLoader);
accountPhoneNumberLoader.addToPrime(accountLoader);

For example,

// hits db
const account = await accountPhoneNumberLoader.load(phone);
// retrieves from cache
const user2 = await accountLoader.load(account.id);

This is obviously a trivial example because in practice, the data fetching doesn't happen in the very next line but in a completely different part of the system within the same request.