Skip to content

Instantly share code, notes, and snippets.

@csnover
Last active July 27, 2018 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csnover/e0b956a53abb0986dbcca6a5f066d368 to your computer and use it in GitHub Desktop.
Save csnover/e0b956a53abb0986dbcca6a5f066d368 to your computer and use it in GitHub Desktop.
// License: MIT
module.exports = async function MakeNonNullableReferencesPlugin(builder, { pgConfig }) {
async function getPolicies() {
const { rows } = await pgConfig.query({
text: `SELECT DISTINCT polrelid::text, true FROM pg_policy WHERE polcmd IN ('r', '*')`,
rowMode: 'array'
});
return new Map(rows);
}
let policies = await getPolicies();
builder.hook('GraphQLObjectType:fields:field', (field, build, context) => {
const GraphQLNonNull = build.graphql.GraphQLNonNull;
const {
scope: {
isMutationPayload,
isPgForwardRelationField,
pgIntrospection,
pgIntrospectionTable,
pgFieldIntrospection
}
} = context;
const pgTableIntrospection = pgIntrospectionTable || pgIntrospection;
if (isMutationPayload) {
return field;
}
if (!isPgForwardRelationField || !pgTableIntrospection) {
return field;
}
const hasRowLevelReadSecurity = policies.get(pgFieldIntrospection.classId);
if (hasRowLevelReadSecurity) {
return field;
}
const allKeysAreNonNull = pgFieldIntrospection.keyAttributeNums.every((num) =>
pgTableIntrospection.attributes.find((attribute) =>
attribute.num === num && attribute.isNotNull)
);
if (!allKeysAreNonNull) {
return field;
}
return {
...field,
type: new GraphQLNonNull(field.type)
};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment