2

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);
    });
});
Nux
  • 5,890
  • 13
  • 48
  • 74

1 Answers1

3

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.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thanks for you response! So which one is better between URL and Base64? – Nux May 28 '19 at 19:30
  • The former will require you to still figure out a way to actually serve the pictures from the server, while the latter will require you to convert the encoded strings into a usable format client-side. Which one is *better* depends on a lot of variables. – Daniel Rearden May 28 '19 at 19:47
  • I created a separate router. Can you take a look if I have done it correctly. I edited above code – Nux May 29 '19 at 05:21