使用 graphql 服务图像
serving images with graphql
我有 graphql 服务器,由 express-graphql 构建,我使用 mongoDb 在普通数据库集合中存储图像,因为它们小于 16MB。
我有 react 和 android 应用程序。将这些图像提供给客户的最佳方式是什么。
在我的模式中有这样的东西。
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.js 响应被序列化为 JSON,这意味着您无法使用它 提供 图像。您可以 return URL 或表示图像的 Base64 编码字符串,如 所述。无论哪种方式,您的字段类型都是 GraphQLString
.
我有 graphql 服务器,由 express-graphql 构建,我使用 mongoDb 在普通数据库集合中存储图像,因为它们小于 16MB。
我有 react 和 android 应用程序。将这些图像提供给客户的最佳方式是什么。
在我的模式中有这样的东西。
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.js 响应被序列化为 JSON,这意味着您无法使用它 提供 图像。您可以 return URL 或表示图像的 Base64 编码字符串,如 GraphQLString
.