【问题标题】:serving images with graphql使用 graphql 提供图像
【发布时间】:2019-10-14 03:30:01
【问题描述】:

我有 express-graphql 构建的 graphql 服务器,并且我使用 mongoDb 将图像存储在普通数据库集合中,因为它们

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

在我的架构中,我有类似的东西。

const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},

}); 在我的架构中,我有类似

const productType = new GraphQLObjectType({
    name: 'Product',
    fields: () => ({
        //.........
        thumbnail: {type: 'WHAT TO DO HERE'},
        views: {type: new GraphQLNonNull(GraphQLInt)}
        //.........
    }),
});

编辑: 我创建了一个这样的路由器。

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);
    });
});

【问题讨论】:

    标签: graphql express-graphql


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复!那么 URL 和 Base64 哪个更好呢?
    • 前者需要您仍然想办法从服务器实际提供图片,而后者需要您将编码的字符串转换为客户端可用的格式。哪个更好取决于很多变量。
    • 我创建了一个单独的路由器。你能看看我是否做得正确。我编辑了上面的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2019-02-20
    • 2018-12-03
    • 2018-04-04
    • 2013-09-28
    • 2017-08-11
    相关资源
    最近更新 更多