使用graphql服务图像

使用graphql服务图像,graphql,express-graphql,Graphql,Express Graphql,我有graphql服务器,由express graphql构建,我使用mongoDb将图像存储在正常的数据库集合中,因为它们小于16MB 我有react和android应用程序。向客户提供这些图片的最佳方式是什么 在我的模式中,我有这样的东西 const productSchema = new Schema({ views: {type: Number, default: 0}, //Storing only thumbnail in this document. thumbnail: {dat

我有graphql服务器,由express graphql构建,我使用mongoDb将图像存储在正常的数据库集合中,因为它们小于16MB

我有reactandroid应用程序。向客户提供这些图片的最佳方式是什么

在我的模式中,我有这样的东西

const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},
router.get('/t/:productId', function (req, res) {
    const productId = req.params.productId;

    Product.findById(productId, {thumbnail: true}).then(thumbnail => {
        res.contentType(thumbnail.contentType);
        res.end(thumbnail.data, "binary");
    }).catch(e => {
        console.error(e);
        res.sendStatus(404);
    });
});
})); 在我的模式中,我有

const productType = new GraphQLObjectType({
    name: 'Product',
    fields: () => ({
        //.........
        thumbnail: {type: 'WHAT TO DO HERE'},
        views: {type: new GraphQLNonNull(GraphQLInt)}
        //.........
    }),
});
编辑: 我创建了一个这样的路由器

const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},
router.get('/t/:productId', function (req, res) {
    const productId = req.params.productId;

    Product.findById(productId, {thumbnail: true}).then(thumbnail => {
        res.contentType(thumbnail.contentType);
        res.end(thumbnail.data, "binary");
    }).catch(e => {
        console.error(e);
        res.sendStatus(404);
    });
});

js响应被序列化为JSON,这意味着您不能使用它提供图像。您可以返回表示图像的URL或Base64编码字符串,如下所述。无论哪种方式,您字段的类型都是
GraphQLString

,谢谢您的回复!那么URL和Base64之间哪一个更好呢?前者需要您仍然找到一种方法来实际从服务器提供图片,而后者需要您将编码字符串转换为客户端可用的格式。哪个更好取决于很多变量。我创建了一个单独的路由器。你能看看我做得对不对吗。我编辑了上面的代码