Last active
July 27, 2018 01:15
-
-
Save csnover/e0b956a53abb0986dbcca6a5f066d368 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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