jsonapi-serializer icon indicating copy to clipboard operation
jsonapi-serializer copied to clipboard

Cannot read property 'opts' of undefined

Open braadworst opened this issue 8 years ago • 2 comments

Context for this/that is lost in serialize function

const serializer = require('jsonapi-serializer').Serializer;

module.exports = function(table) {
  return new serializer(table.name, {
    attributes : table.fields.map(field => field.name)
  }).serialize;
}

Table.name is just a string and fields are the fields that get mapped to the attributes. Is there a possibillity to have json-serializer work without the new keyword and this, wink wink refactor.

Cheers,

Roy

braadworst avatar Feb 21 '17 10:02 braadworst

Got it fixed by setting the context using a .call function, for people who need this too:

const serializer = require('jsonapi-serializer').Serializer;

module.exports = function(table) {
  return new serializer('typeName', {
    attributes : ['field1', 'field2']
  });
}

// Then call like so
const serializer = require('./serializer');
serializer.serialize.call(serializer, data)

Little bit weird that I have to do this, but it works for now... Maybe programming without this and classes, pretty please...?

braadworst avatar Feb 21 '17 11:02 braadworst

Hey @braadworst thanks for your issue. Unfortunately I don't understand your use case :(

Here's my example:

      function foo(table) {
        return new JSONAPISerializer(table.name, {
          attributes : table.fields.map(field => field.name)
        });
      }

      var json = foo({ name: 'users', fields: [{ name: 'aaa' }, { name: 'bbb' }]}).serialize({
        aaa: 111,
        bbb: 222
      })

And the result is:

{ data: 
   { type: 'users',
     id: 'undefined',
     attributes: { aaa: 111, bbb: 222 } } }

What's the problem? Not sure to understand the this issue. Can you tell me more about it? :)

SeyZ avatar Mar 31 '17 20:03 SeyZ