mirror of
https://github.com/IT4Change/Ocelot-Social.git
synced 2025-12-13 07:45:56 +00:00
Refactor Id Middleware
I found a way to cleanly request additional attributes in our middleware. We can use this pattern if we e.g. require the author of posts and comments to check if the user is the author and therefore authorized to update or delete the post. CC @mattwr18 @appinteractive @tirokk
This commit is contained in:
parent
98983bb575
commit
aa07a2a616
@ -1,25 +1,17 @@
|
||||
import find from 'lodash/find'
|
||||
import cloneDeep from 'lodash/cloneDeep'
|
||||
|
||||
const includeId = async (resolve, root, args, context, info) => {
|
||||
let isIdPresent
|
||||
let removeIdFromResult
|
||||
isIdPresent = find(info.fieldNodes[0].selectionSet.selections, item => item.name.value === 'id')
|
||||
if (!isIdPresent) {
|
||||
// add id to request as the user did not ask but we need it
|
||||
info.fieldNodes[0].selectionSet.selections.unshift({
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'id' }
|
||||
})
|
||||
removeIdFromResult = true
|
||||
}
|
||||
const includeId = async (resolve, root, args, context, resolveInfo) => {
|
||||
// Keeping the graphql resolveInfo untouched ensures that we don't add the
|
||||
// following attributes to the result set returned to the graphQL client.
|
||||
// We only want to pass these attributes to our resolver for internal
|
||||
// purposes e.g. authorization.
|
||||
const copy = cloneDeep(resolveInfo)
|
||||
|
||||
const result = await resolve(root, args, context, info)
|
||||
|
||||
if (!isIdPresent && removeIdFromResult) {
|
||||
// remove id if the user did not ask for it
|
||||
info.fieldNodes[0].selectionSet.selections.shift()
|
||||
}
|
||||
return result
|
||||
copy.fieldNodes[0].selectionSet.selections.unshift({
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'id' }
|
||||
})
|
||||
return resolve(root, args, context, copy)
|
||||
}
|
||||
|
||||
export default {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user