Получение полной строки запроса из резолвера - PullRequest
1 голос
/ 26 апреля 2019

Я новичок в nodejs и сервере apollo, поэтому не судите меня.

Проблема звучит точно так же, как и заголовок: "Как получить строку graphql внутри функции распознавателя?".

На самом делеу вас есть четыре аргумента в каждом преобразователе: родитель, аргументы, контекст, информация.Некоторая информация здесь: https://www.apollographql.com/docs/apollo-server/essentials/data#type-signature

Я решил написать функцию, которая собирает вложенный объект в контексте для регенерации строки запроса.Зачем мне это нужно?Хороший вопрос.Я пишу микросервис, поэтому когда я получаю вложенный запрос к полю, который находится вне текущего микросервиса, я передаю запрос по http.

Мой преобразователь:

eventByID: async (root, args, context) => {
const event = await EventModel.findById(root.id);
event.creator = await nestedContextProvider(context, 'creator', event.creator);
return eventFascade(event); //just fascade for object - nothing serious

},

Это относится к nestedContextProvider для решения вложенного контекста:

const nestedQueryTraverser = (nestedQueryArray) => {
const nestedQueryTraversed = nestedQueryArray.selectionSet.selections.map(element => (
element.selectionSet === undefined
  ? element.name.value
  : `${element.name.value}{${nestedQueryTraverser(element)}}`));
return nestedQueryTraversed;
};

const nestedContextProvider = async (context, checkField, ID) => {
if (context.operation.selectionSet.selections[0].selectionSet.selections
.find(selector => selector.name.value === checkField)) {
let nestedFieldsArr = context.operation.selectionSet.selections[0]
  .selectionSet.selections.find(selector => selector.name.value === checkField);
nestedFieldsArr = nestedQueryTraverser(nestedFieldsArr);
const a = (await users(ID, nestedFieldsArr));
return a.data.usersByIDs[0];
}
return ID;
};

Так что это работает для меня, но я знаю, что должно быть лучшее решение.

Есть идеи?

1 Ответ

0 голосов
/ 26 апреля 2019

Пакет graphql включает функцию print, которая принимает любой AST и возвращает строковое представление, так что вы можете сделать что-то вроде этого:

const { print } = require('graphql')

function anyResolver (parent, args, context, info) {
  const operationString = print(info.operation)
  // Fragments are not included in the operation, but we still need to print
  // them otherwise our document will reference non-existing fragments
  const fragmentsString = Object.keys(info.fragments)
    .map(fragmentName => print(info.fragments[fragmentName]))
    .join('\n\n')
  const documentString = `${operationString}\n\n${fragmentsString}`
}
...