如何对JSON对象的大小设置限制?



我创建了一个API,其中一个字段是任意JSON对象。我正在使用Sequelize和Postgres。这个字段需要灵活,因为它允许用户存储自己的元数据,但我确实希望限制大小,以防止用户上传巨大的对象。这是我目前对对象定义的解决方案:

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

这基本上是有效的,但我不知道len实际上是什么测量,因为它不是一个字符串。它似乎不测量JSON对象中的字符数。我确信有更好的方法来做到这一点,但我所有的谷歌搜索只是显示有关Postgres中JSONB对象的最大大小的信息。我想设置一个小于最大尺寸的限制。我希望现在能够将其限制在~1,000个字符或1KB。

您可以使用检查约束:

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

考虑规范化数据

您可以为您的列提供自定义验证器。

文档中的参考:https://sequelize.org/master/manual/validations-and-constraints.html#per-attribute-validations(观察那里的最后两个验证器-您可以为它们命名任何名称)

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
},
},
},

最新更新