nicklandgrebe / active-resource.js

ActiveResource.js - API resource relational mapping in JavaScript
https://active-resource.js.org
MIT License
133 stars 20 forks source link

Uncaught NameError: klass does not exist #44

Closed CharlieIGG closed 5 years ago

CharlieIGG commented 5 years ago

Hello, and thanks for the awesome library.

I have the problem listed in the title on-and-off with the following resource when trying to save or update an instance:

import resourceLibrary from './library'

class Car extends resourceLibrary.Base {
    static define() {
        this.attributes('year', 'prices')
        this.belongsTo('engine')
        this.belongsTo('make')
        this.belongsTo('model')
    }
}

export default resourceLibrary.createResource(Car);

If one inspects the source code of this library, it becomes evident that the message should be Uncaught NameError: klass <CLASS_NAME> does not exist.

I figured this problem might be related to #21 and/or #22.

If I capture the Car instance when it's all working, I see this:

car.klass().fields().toArray()
(5) ["year", "prices", "engine", "make", "model"]

However if I capture it when the problem arises I see this:

car.klass().fields().toArray()
(6) ["year", "prices", "engine", "make", "model", undefined]

It's this 6th undefined that's causing car.save() to break, but the problem is, up to this point I haven't done any direct operations on the car instance whatsoever, so I'm at a loss about what's causing this.

Any ideas?

CharlieIGG commented 5 years ago

After a bunch of time debugging, I've been able to trace this problem to this line in my own code:

const relationships = Object.keys(Car.belongsTo()).slice().concat(Object.keys(Car.hasMany())

Which makes me feel stupid, but at the same time I don't understand what's going on.

Shed any light on me?

Edit:

I now realize belongsTo() and hasMany() assign undefined if passed nothing, and THEN return the relationship.

What's the right way to get al relationships on a model?

CharlieIGG commented 5 years ago

For the time being, the best I could come up with that fixes this is to use:

    const relationships = Car.reflectOnAllAssociations().map(a => a.name).toArray()
CharlieIGG commented 5 years ago

@nicklandgrebe I would like to make a PR to propose a more meaningful error message for this scenarios (i.e. "klass does not exist"), so that other users don't have to spend as much time debugging as I did to figure out what they're doing wrong.

The thing is I see this message in a couple of the source's files.

How should I go about making this contribution?