How do I set a limit on the size of a JSON object?

Viewed 592

I've created an API where one of the fields is an arbitrary JSON object. I'm using Sequelize and Postgres. This field needs to be flexible, as it allows users to store their own metadata, but I do want to limit the size to prevent users from uploading gigantic objects. This is my current solution on the object definition:

metadata: {
  type: DataTypes.JSONB,
  allowNull: true,
  validate: {
    len: {
      args: [18, 1000],
      msg: 'Metadata exceeds the max length of 1000 characters.',
    },
  },
},

This basically works, but I have no idea what len is actually measuring since it's not a string. It doesn't appear to measure the number of characters in the JSON object. I'm sure there's a better way to do this, but all my googling just turns up information about the max size of a JSONB object in Postgres. I want to set a limit waaay below the max size. I would like to be able to limit it to ~1,000 characters or 1KB for now.

2 Answers

You could use a check constraint:

CREATE TABLE (
   ...
   jcol jsonb CHECK (length(jcol::text) < 1000)
);

Consider normalizing the data.

You can provide a custom validator for your column.

Reference in docs: https://sequelize.org/master/manual/validations-and-constraints.html#per-attribute-validations ( Observe the last 2 validators there - You can name them anything)

metadata: {
    type: DataTypes.JSONB,
    allowNull: true,
    validate: {
        isWithinSizeLimit(value) { // you can check/do whatever/however you need to validate

            // size in bytes ( 1000 Byte = 1KB )
            // const size = Buffer.byteLength(JSON.stringify(value)); // if size checking

            const size = JSON.stringify(value).length; // OR this way for number of characters
            if (size >= 1000) {
                throw new Error('Metadata exceeds the max length of 1000 characters.');
                // throw new Error('Metadata exceeds the max size of 1 KB.');

            }
            // if it reaches here means validation successful
        },
    },
},
Related