Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a string from a Buffer from a mysql blob field in my Express API?

I'm building a restful API on Express and using Sequelize. I have a Blob field in my mysql table, but in the get response it's returning a Buffer object. How should I return the string value of any of my response data's properties which are Buffer objects?

I'll be consuming this API with PHP but I'm using Postman to test it.

Here's what my model definition looks like:

module.exports = function (sequelize, DataTypes) {
  return sequelize.define('submissions', {
    comments: {
      type: DataTypes.BLOB,
      allowNull: true,
      defaultValue: ''
    },
    // Other fields...
  }, {tableName: 'submission', timestamps: false});
};

Here's an example of one of my routes:

router.get('/:model', function(req, res) {
  var where = req.query;
    models[req.params.model].findAll({ where: where}).then(function(results){
        var status = models.utils._.isNull(results) ? 404 : 200;
        res.status(status).json(results);
    });
});
like image 242
Brandon Avatar asked Dec 24 '22 20:12

Brandon


1 Answers

If your blob data is encoded as utf8 strings you could simply do this:

buffer.toString('utf8')

But if you're going to return string data I wonder why you wouldn't simply store the field as a Sequelize.STRING. If comments is structured data, you might consider defining a separate Comment model. If you're using Postgres you also have the option of defining comments as an array or as json.

like image 163
Andrew Lavers Avatar answered Jan 13 '23 13:01

Andrew Lavers