forked from Growmies/sequelize-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
33 lines (29 loc) · 971 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var Sequelize = require('sequelize');
function JsonField(db, modelName, fieldName, options) {
var self = this;
options = options || {};
process.nextTick(function() {
db.models[modelName].hook('beforeValidate', function(instance) {
if (typeof instance.dataValues[fieldName] != 'string') {
instance.setDataValue(fieldName, JSON.stringify(instance.getDataValue(fieldName)));
return self;
} else if (instance.dataValues[fieldName] == 'null') {
instance.setDataValue(fieldName, null);
}
});
});
return {
type: options.type || Sequelize.TEXT,
get: function() {
var currentValue = this.getDataValue(fieldName);
if (typeof currentValue == 'string') {
this.dataValues[fieldName] = JSON.parse(currentValue);
}
return this.dataValues[fieldName];
},
set: function(value) {
this.setDataValue(fieldName, JSON.stringify(value))
}
}
}
module.exports = JsonField;