Загрузка изображения в GraphQL

как я могу обрабатывать загрузку изображений в graphql

Через multer с использованием экспресс-маршрута для загрузки и запроса из graphql для просмотра изображений и других данных.

app.use('/graphql', upload);
app.use('/graphql', getData, graphqlHTTP(tokenData => ({
    schema,
    pretty: true,
    tokenData,
    graphiql: true,
})));

person terik_poe    schedule 19.01.2017    source источник
comment
Возможный дубликат Как бы вы загружали файлы в приложение React-Relay?   -  person Chris    schedule 20.01.2017
comment
Согласен, скорее всего дубликат. Файл — это файл, изображение или что-то другое.   -  person Scot Matson    schedule 22.12.2017


Ответы (1)


Это дубликат Как вы бы загрузили файлы в приложение React-Relay?

Короче говоря, да, вы можете загрузить файл в graphql с помощью реакции + реле. Вам нужно написать действие Relay update store, например:

onDrop: function(files) {
  files.forEach((file)=> {
    Relay.Store.commitUpdate(
      new AddImageMutation({
        file,
        images: this.props.User,
      }),
      {onSuccess, onFailure}
    );
  });
},

Затем внедрите мутацию для хранилища реле.

class AddImageMutation extends Relay.Mutation {
   static fragments = {
     images: () => Relay.QL`
       fragment on User {
         id,
       }`,
     };

   getMutation() {
     return Relay.QL`mutation{ introduceImage }`;
   }

   getFiles() {
     return {
       file: this.props.file,
     };
   }

   getVariables() {
     return {
       imageName: this.props.file.name,
     };
   }

   getFatQuery() {
     return Relay.QL`
       fragment on IntroduceImagePayload {
         User {
           images(first: 30) {
             edges {
               node {
                 id,
               }
             }
           }
         },
         newImageEdge,
       }
     `;
   }

   getConfigs() {
     return [{
       type: 'RANGE_ADD',
       parentName: 'User',
       parentID: this.props.images.id,
       connectionName: 'images',
       edgeName: 'newImageEdge',
       rangeBehaviors: {
         '': 'prepend',
       },
     }];
   }
 }

В вашей схеме на стороне сервера преформируйте обновление

const imageMutation = Relay.mutationWithClientMutationId({
  name: 'IntroduceImage',
  inputFields: {
    imageName: {
      type: new GraphQL.GraphQLNonNull(GraphQL.GraphQLString),
    },
  },
  outputFields: {
    newImageEdge: {
      type: ImageEdge,
      resolve: (payload, args, options) => {
        const file = options.rootValue.request.file;
        //write the image to you disk
        return uploadFile(file.buffer, filePath, filename)
        .then(() => {
          /* Find the offset for new edge*/
          return Promise.all(
            [(new myImages()).getAll(),
              (new myImages()).getById(payload.insertId)])
          .spread((allImages, newImage) => {
            const newImageStr = JSON.stringify(newImage);
            /* If edge is in list return index */
            const offset = allImages.reduce((pre, ele, idx) => {
              if (JSON.stringify(ele) === newImageStr) {
                return idx;
              }
              return pre;
            }, -1);

            return {
              cursor: offset !== -1 ? Relay.offsetToCursor(offset) : null,
              node: newImage,
            };
          });
        });
      },
    },
    User: {
      type: UserType,
      resolve: () => (new myImages()).getAll(),
    },
  },
  mutateAndGetPayload: (input) => {
    //break the names to array.
    let imageName = input.imageName.substring(0, input.imageName.lastIndexOf('.'));
    const mimeType = input.imageName.substring(input.imageName.lastIndexOf('.'));
    //wirte the image to database
    return (new myImages())
    .add(imageName)
    .then(id => {
    //prepare to wirte disk
      return {
        insertId: id,
        imgNmae: imageName,
      };
    });
  },
});

Весь приведенный выше код вы можете найти в этом репозитории https://github.com/bfwg/relay-gallery Существует также живая демонстрация http://fanjin.io.

person Fan Jin    schedule 19.01.2017
comment
Если этот ответ является дубликатом, вы должны проголосовать, чтобы отметить его как таковой и указать на существующий ответ, поскольку он в основном такой же. - person Chris; 20.01.2017