A simple, lightweight JSON serializer.
Pinkie is available on npm.
npm install --save pinkie-json-serializer
Let's say we fetch data from our database in this form:
var user = {
"id" : 3,
"username" : "Mrs.Sparkle",
"password" : "un4re8da0bl34ash",
"gender" : "F",
"last_login" : 14712041
}
It would be nice to have one place in our project, where we could properly format our output. So we hook up this serializer in our data access layer. It may look as follows:
var Serializer = require('pinkie-json-serializer');
var serializer = new Serializer();
function isOwner(id){
return (id === 4);
}
var serialization_schema = {
"name" : {"as" : "username"},
"gender" : true,
"password" : {
"show" : function(json){
return isOwner(json["id"]);
}
},
"last_login" : {
"set" : function(json){
return {
"utc" : json["last_login"], //our fetched time
"halved" : json["last_login"]/2
}
};
}
};
var user = fetch_by_id(3); //pseudo-function
var serialized = serializer.serialize(user, schema);
console.log(serialized);
//Outputs
{
"username" : "Mrs.Sparkle",
"gender" : "F",
"last_login" : {
"utc" : 14712041,
"halved" : 7356020.5
}
}
Schema allows nested arrays and objects, but in this case the "show" value must contain next serialization schema.
I used it as a Moongose plugin when I was building my API. I implemented it as Moongose middleware, but it has some downsides like inability to access request object and parse headers for example(in this case you may want to create serialize method on your model with request arg).
//src/models/plugins/serializer.js
var Serializer = require('pinkie-json-serializer');
var serializer = new Serializer();
module.exports = function(schema, serialization_schema){
schema.methods.toJSON = function(){
return serializer.serialize(this.toObject(), serialization_schema, this);
};
};
//src/models/user.js
var mongoose = require('mongoose');
var serializer = require('./plugins/serializer');
var userSchema = new mongoose.Schema({
name: {
type: String
},
gender:{
type: String,
enum: ["M", "F"]
},
password:{
type: String
}
last_login:{
type: Number
}
});
userSchema.plugin(serializer, {
"_id" : {"as" : "id"},
"name" : {"as" : "username"},
"gender" : {
"set" : function(json, user){
//user is moongose object we passed in serializer.js as a 3rd param. we can use it to access related objects if we need any
if(json["gender"] === "F"){
return "girl";
}else{
return "boy";
}
}
}
});
module.exports = mongoose.model('User', userSchema);
Now if you query your DB via you'll be responded with nicely formatted output.