0

I fell into an issue the first time trying to create instances of .json objects.

for example lets say in my node project I have this model:

city.json

{
    "links": {
        "self": null,
        "parent": null
    },
    "id": null,
    "name":{
        "full": null,
        "abbreviated": null,
        "urlFriendlyName": null
    },
    "countries": null
}

I found that in my code, when I included this via a require at the top of a module, that if I tried to use it more than once, I couldn't and ended up having to create an instance of this like this:

I had a utility module that would do this:

modelUtilities.js

var cityEntity = require('../src/entities/city');


module.exports = {
    "createCityEntity": createCityEntity
    .. and a bunch more helpers
};    
function createCityEntity(cityId, stateId, fullname, abbreviatedName, urlFriendlyName){
    var city = clone(cityEntity);

    city.id = cityId;
    city.name.full = fullname;
    city.name.abbreviated = abbreviatedName;
    city.name.urlFriendlyName = urlFriendlyName;
    city.links.self = "/cities/" + cityId;
    city.links.parent = "/states/" + stateId;

    return city;
}

function clone(obj){
    return JSON.parse(JSON.stringify(obj));
};

I don't remember exactly the issue but I know I had to do this clone or else I couldn't end up with multiple different instances of that .json object for use in my SUT code and also for reuse in my tests because I was using that structure to also create a dummy city for stub data.

Any idea if I was just thinking about .json wrong or if this is normal? Or not?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
PositiveGuy
  • 17,621
  • 26
  • 79
  • 138
  • 1
    Node caches the results of requires as far as I know, so it will return the *same* object every time you require the same file. Here are some ideas as to how to circumvent this http://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate – JCOC611 Nov 16 '15 at 21:01
  • But it shouldn't be applied to deserialized.. Other words - with `clone` all ok, w/o - it is always same object. – vp_arth Nov 16 '15 at 21:04
  • that's probably it then, it's caching it. Thanks – PositiveGuy Nov 16 '15 at 21:36

0 Answers0