Skip to main content

QueryLoader

QueryLoader is a Loader which is used to fetch multiple rows in the database.

It's used by index based queries as well as custom ent queries.

QueryLoaderFactory

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

API

interface QueryOptions {
fields: string[];
tableName: string;
groupCol?: string;
clause?: clause.Clause;
orderby?: OrderBy;
toPrime?: ObjectLoaderFactory<ID>[];
}
class QueryLoaderFactory<K extends any> implements LoaderFactory<K, Data[]> {
constructor(options: QueryOptions);
}
  • fields: columns in the database to query for.
  • tableName: relevant table in the database.
  • groupCol: column in the database that can be converted into an IN query when querying for multiple sources
  • clause: Clause instance for filtering.
  • orderby: optional. Used to order the query. If not provided, we sort by the id field descending.
  • toPrime: optional. Other loaders that can be primed by the result of this query with the result stored in the context cache.

Note that at least one of groupCol and clause must be provided.

Examples

Given the following schema:

src/schema/todo_schema.ts
const TodoSchema = new EntSchema({
fields: {
text: StringType(),
completed: BooleanType({
index: true,
defaultValueOnCreate: () => {
return false;
},
}),
creatorID: UUIDType({
foreignKey: { schema: "Account", column: "id" },
}),
},
});
export default TodoSchema;

here are some examples:

  • open todos of a user. can be used to fetch multiple users at a time
const openTodosLoader = new QueryLoaderFactory({
...Todo.loaderOptions(),
groupCol: "creator_id",
clause: query.Eq("completed", false),
toPrime: [todoLoader],
});
  • open todos of a user. cannot be used to fetch multiple users at a time
const openTodosLoader = new QueryLoaderFactory({
...Todo.loaderOptions(),
clause: query.And(query.Eq("creator_id", user.id, query.Eq("completed", false)),
toPrime: [todoLoader],
});
  • all todos of a user. can be used to fetch multiple users at a time
const allTodosLoader = new QueryLoaderFactory({
...Todo.loaderOptions(),
groupCol: "creator_id",
toPrime: [todoLoader],
});
  • all todos of a user. cannot be used to fetch multiple users at a time
const allTodosLoader = new QueryLoaderFactory({
...Todo.loaderOptions(),
clause: query.Eq("creator_id", user.id),
toPrime: [todoLoader],
});

Note that the best way to use QueryLoader is via a custom query as that gives you the benefits of pagination, sorting, filtering etc.