Как реализовать ссылку на другую модель в Relay Mutations на стороне сервера?

Я застрял с Refs в Relay Mutation и globalIdField.

Итак, предположим, что комментарий может иметь идентификатор родительского комментария, должен иметь идентификатор сообщения в реквизитах, и у меня есть мутация, определенная со следующей схемой:

const createComment = mutationWithClientMutationId({
  name: 'CreateComment',
  description: 'Create comment of the post',
  inputFields: {
    content: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Content of the comment',
    },
    parent: {
      type: GraphQLID,
      description: 'Parent of the comment',
    },
    post: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'Post of the comment',
    },
  },
  outputFields: {
    comment: { type: commentType, resolve: comment => comment },
  },
  mutateAndGetPayload: (input, context) => (context.user
    ? Comment.create(Object.assign(input, { author: context.user._id }))
    : new Error('Only logged in user can create new comment')),
});

В моем комментарии есть globalIdField, postType тоже. Когда я буду запрашивать мутацию у клиента, я буду везде использовать globalIds вместо реального mongo _id этих объектов. Вот лучший способ для этого вместо этой части в mutateAndGetPayload:

mutateAndGetPayload: (input, context) => {
  if (input.parent) input.parent = fromGlobalId(input.parent).id;
  if (input.post) input.post = fromGlobalId(input.post).id;
  // And other logic
}

Было бы очень удобно, если бы я мог просто добавить globalIdField() в сообщение, но Relay не может передать это, потому что поле в inputFields не может иметь функцию разрешения, которая есть у globalIdField.


person Vadim Shvetsov    schedule 06.06.2017    source источник


Ответы (1)


Пока я не могу найти решение лучше, чем ниже:

mutateAndGetPayload: ({ content, post, parent }, context) => {
    if (!context.user) throw new Error('Only logged in user can create new comment');
    const newComment = { author: context.user._id, content };
    if (post) newComment.post = fromGlobalId(post).id;
    if (parent) newComment.parent = fromGlobalId(parent).id;
    return Comment.create(newComment);
  },

Был бы очень рад, если бы кто-то предоставил лучший опыт с этим.

person Vadim Shvetsov    schedule 07.06.2017