tx fun
tx fun

Reputation: 569

node.js objectmapper string to javascript object

using object-mapper node.js module, to map a object to another.

var objectMapper = require('object-mapper');
var map = {"foo": [{ key:"newfoo", transform: function(value){ return "##"+value;  }}]}
var data =  {"foo":"bar","baz":"blah"}
var dest = objectMapper(data, map);

The variable map is dynamic and would vary based on scenario to scenario. so i could have another translation as

{"foo": [{ key:"newfoo", transform: function(value){ return "$$"+value;  }}]}

I hold all templates by creating a javascript file map_tmpl.js

var tmpl_1= function () {return {"foo": [{ key:"newfoo", transform: function(value){ return "##"+value;  }}]};}
var tmpl_2= function () {return {"foo": [{ key:"newfoo", transform: function(value){ return "##"+value;  }}]};}
module.exports= {tmpl_1,tmpl_2}

I want to save these templates in a database and read from database when needed, If i store this as string and pass it to objectmapper, object-mapper does not work as it is expecting an object, kindly advice on the best way to resolve this.

Upvotes: 1

Views: 2281

Answers (1)

Val
Val

Reputation: 22797

Since JSON knows nothing about function, you have to use custom serializer & deserializer for storing in / out database.

var serializer = function(key, val) {
   if (typeof val === 'function') return val + '';      /* serialize function to string */
   return val;
};

var deserializer = function(key, val) {
   var reg = /^function\s*\(/;      /* match function string and deserialize back to function */
   if (typeof val === 'string' && reg.test(val)) {
      eval(`var fn = ${val}`);
      return fn;
   }
   return val;  
}

And take example of your code:

1) save into database

var tmpl_1= function () {return {"foo": [{ key:"newfoo", transform: function(value){ return "##"+value;  }}]};}
var StringIntoDatabase = JSON.stringify(tmpl_1, serializer);

2) take from database

var tmpl_1 = JSON.parse(StringFromDatabase, deserializer);

Console snapshot: enter image description here

Upvotes: 1

Related Questions