From aa07a2a6167cac5e06d3267745209dc787ec489b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Sch=C3=A4fer?= Date: Thu, 21 Feb 2019 10:45:34 +0100 Subject: [PATCH] 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 --- src/middleware/idMiddleware.js | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/src/middleware/idMiddleware.js b/src/middleware/idMiddleware.js index 59224bd64..d6dac0580 100644 --- a/src/middleware/idMiddleware.js +++ b/src/middleware/idMiddleware.js @@ -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 {