Nux
Nux

Reputation: 7088

serving images with graphql

I have graphql server built by express-graphql and I use mongoDb to store images in normal database collection since they are < 16MB.

I have react and android app. What is the best way to serve these images to the clients.

In my schema I have something like this.

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

}); And in my schema I have something like

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

Edit: I created a router like this.

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

Upvotes: 2

Views: 8961

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84747

GraphQL.js responses are serialized as JSON, which means you can't serve images with it. You can return either a URL or a Base64-encoded string representing the image, as described in this answer. Either way the type for your field would be GraphQLString.

Upvotes: 4

Related Questions