Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Plugin } from 'postgraphile';
/**
* Allows you to override the default orderBy for a given field to be the
* orderBy with the given name. Usage:
*
* ```
* const MyOrderByPlugin = makeSetDefaultOrderByForFieldPlugin(
* 'MyTableName',
* 'myRelationName',
* 'PRIMARY_KEY_DESC'
* );
* // ...
* app.use(postgraphile(DATABASE_URL, SCHEMA_NAMES, {
* appendPlugins: [MyOrderByPlugin]
* }));
* ```
*/
export default function makeSetDefaultOrderByForFieldPlugin(
targetTypeName: string,
targetFieldName: string,
targetOrderByName: string,
): Plugin {
// This plugin is heavily based on
// https://github.com/graphile/graphile-engine/blob/3f22f7698f84be288bf5791bcd9aa30b009ebfd7/packages/graphile-build-pg/src/plugins/PgConnectionArgOrderByDefaultValue.js
const plugin: Plugin = builder => {
builder.hook(
'GraphQLObjectType:fields:field:args',
(args, build, context) => {
const { extend, getTypeByName, pgGetGqlTypeByTypeIdAndModifier, inflection } = build;
const {
scope: {
fieldName,
isPgFieldConnection,
isPgFieldSimpleCollection,
pgFieldIntrospection: table,
},
Self,
} = context;
if (
!(isPgFieldConnection || isPgFieldSimpleCollection) ||
!table ||
table.kind !== 'class' ||
!table.namespace ||
!table.isSelectable ||
!args.orderBy ||
Self.name !== targetTypeName ||
fieldName !== targetFieldName
) {
return args;
}
const TableType = pgGetGqlTypeByTypeIdAndModifier(table.type.id, null);
const tableTypeName = TableType.name;
const TableOrderByType = getTypeByName(inflection.orderByType(tableTypeName));
if (!TableOrderByType) {
throw new Error(`Could not find orderBy type for field '${Self.name}.${fieldName}'`);
}
const targetValueEnum = TableOrderByType.getValues().find(
v => v.name === targetOrderByName,
);
if (!targetValueEnum) {
throw new Error(
`Could not find orderBy enum value named '${targetOrderByName}' for field '${targetTypeName}.${targetFieldName}'`,
);
}
return extend(args, {
orderBy: extend(
args.orderBy,
{
defaultValue: targetValueEnum,
},
`Setting defaultValue on orderBy arg for field '${Self.name}.${fieldName}'`,
),
});
},
// This hook provides:
[],
// Make sure this hook runs before:
['PgConnectionArgOrderByDefaultValue'],
);
};
// A pretty name for debugging
plugin.displayName = `Set_${targetTypeName}_${targetFieldName}_orderByDefaultTo_${targetOrderByName}_Plugin`;
return plugin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment