@ardsh/slonik-dataloaders
v2.1.1
Published
Utilities for creating DataLoaders using Slonik
Downloads
4
Maintainers
Readme
slonik-dataloaders
slonik-dataloaders
is a set of utilities for creating DataLoaders using Slonik. These DataLoaders abstract away some of the complexity of working with cursor-style pagination when working with a SQL database, while still maintaining the flexibility that comes with writing raw SQL statements.
createNodeByIdLoaderClass
Example usage:
const UserByIdLoader = createNodeByIdLoaderClass<User>({
query: sql`
SELECT
*
FROM user
`,
});
const pool = createPool("postgresql://");
const loader = new UserByIdLoader(pool);
const user = await loader.load(99);
By default, the loader will look for an integer column named id
to use as the key. You can specify a different column to use like this:
const UserByIdLoader = createNodeByIdLoaderClass<User>({
column: {
name: 'unique_id',
type: 'text',
}
query: sql`
SELECT
*
FROM user
`,
});
createConnectionLoaderClass
Example usage
const UserConnectionLoader = createConnectionLoaderClass<User>({
query: sql`
SELECT
*
FROM user
`,
});
const pool = createPool("postgresql://");
const loader = new UserByIdLoader(pool);
const connection = await loader.load({
where: ({ firstName }) => sql`${firstName} = 'Susan'`,
orderBy: ({ firstName }) => [[firstName, "ASC"]],
});
When calling load
, you can include where
and orderBy
expression factories that will be used to generate each respective clause. These factory functions allow for type-safe loader usage and abstract away the actual table alias used inside the generated SQL query. Note that the column names passed to each factory reflect the type provided when creating the loader class (i.e. User
in the example above); however, each column name is transformed using columnNameTransformer
as described below.
Usage example with forward pagination:
const connection = await loader.load({
orderBy: ({ firstName }) => [[firstName, "ASC"]],
limit: first,
cursor: after,
});
Usage example with backward pagination:
const connection = await loader.load({
orderBy: ({ firstName }) => [[firstName, "ASC"]],
limit: last,
cursor: before,
reverse: true,
});
Conditionally fetching edges and count based on requested fields
In addition to the standard edges
and pageInfo
fields, each connection returned by the loader also includes a count
field. This field reflects the total number of results that would be returned if no limit was applied. In order to fetch both the edges and the count, the loader makes two separate database queries. However, the loader can determine whether it needs to request only one or both of the queries by looking at the GraphQL fields that were actually requested. To do this, we pass in the GraphQLResolveInfo
parameter provided to every GraphQL resolver:
const connection = await loader.load({
orderBy: ({ firstName }) => [[firstName, "ASC"]],
limit: first,
cursor: after,
info,
});
Working with edge fields
It's possible to request columns that will be exposed as fields on the edge type in your schema, as opposed to on the node type. These fields should be included in your query and the TypeScript type provided to the loader. The loader returns each row of the results as both the edge
and the node
, so all requested columns are available inside the resolvers for either type. Note: each requested column should be unique, so if there's a name conflict, you should use an appropriate alias. For example:
const UserConnectionLoader = createConnectionLoaderClass<
User & { edgeCreatedAt }
>({
query: sql`
SELECT
user.id,
user.name,
user.created_at,
friend.created_at edge_created_at
FROM user
INNER JOIN friend ON
user.id = friend.user_id
`,
});
In the example above, if the field on the Edge type in the schema is named createdAt
, we just need to write a resolver for it and resolve the value to that of the edgeCreatedAt
property.
Dynamic queries
If you need more flexibility, it's possible to dynamically build queries by specifying a function instead of a static query. The function must return a slonik query, and it takes any arguments as input. For example:
const UserConnectionLoader = createConnectionLoaderClass<
User & { edgeCreatedAt }
>({
query: ({ friendName }: { friendName: string }) => sql.unsafe`
SELECT
user.*
FROM user
INNER JOIN friend ON
user.id = friend.user_id
WHERE friend.name ILIKE ${sql.literalValue(args.friendName)}
`,
});
Those arguments can then be passed down while loading
const connection = await loader.load({
args: { friendName: 'bob' }
orderBy: ({ name }) => [[name, "ASC"]],
});
columnNameTransformer
Both types of loaders also accept an columnNameTransformer
option. By default, the transformer used is snake-case. The default assumes:
- You're using conventional snake case column names; and
- You're using either
slonik-interceptor-field-name-transformation
or theslonik-interceptor-preset
, which means the columns are returned as camelCased in the query results
By using the columnNameTransformer
(snake case), fields can be referenced by their names as they appear in the results when calling the loader, while still referencing the correct columns inside the query itself. If your usage doesn't meet the above two criteria, consider providing an alternative transformer, like an identify function.