Sequelize-typescript: Solving Circular dependencies with associated models

Created on 17 Oct 2018  路  2Comments  路  Source: RobinBuschmann/sequelize-typescript

I currently have several issues due to recursive dependencies in my code. I'm not sure if this is something this library should be able to resolve, but I think it is.

Assume I have a model Book and a model Author. The model Book has an association to Author, defined as BelongsToMany(() => Author, () => AuthorBooks). Author in turn has BelongsToMany(() => Book, () => AuthorBooks). To achieve this, both modules have to import eachother. This seems to work when there's a trivial amount of models. However, when adding complexity onto the system, everything breaks. Depending on which import is shifted where, eventually, errors like this will appear:

C:\Projects\API\node_modules\sequelize-typescript\lib\services\models.js:180
                    throw new Error("No default export defined for file \"" + fileName + "\" or " +
                    ^

Error: No default export defined for file "school.model" or export does not satisfy filename.
    at C:\Projects\API\node_modules\sequelize-typescript\lib\services\models.js:180:27

When logging the files accordingly, require(fullPath) seems to return {}, meaning, an invalid module. Now I already was able to narrow it down to this being a result of circular dependency, however, all the fixes online seem to suggest that if you place the imports that cause this issue at the bottom of your exported class, there's no longer an issue. But when using this library, this will cause issues, because it will attempt to run something like __metadata("design:type", internal_1.User), while internal_1 is defined below the current line. How could something like this be resolved? I can't lower the complexity of the system, and by not defining a relation, I render the use of the ORM almost entirely.

Most helpful comment

Do you have an example of how this looks? As soon as two files reference eachother in my imports, I get a circular dependency error and have had to use declaration merging to pull it off, but in this library it doesn't seem to work.

All 2 comments

It seems one of my models used an import of the actual Sequelize instance, causing all the errors. Removing this import solved the issue. Due to the Sequelize instance being accessible through models instances passed in hooks, I no longer have any issues.

Do you have an example of how this looks? As soon as two files reference eachother in my imports, I get a circular dependency error and have had to use declaration merging to pull it off, but in this library it doesn't seem to work.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lilling picture lilling  路  4Comments

nandox5 picture nandox5  路  3Comments

zebkailash picture zebkailash  路  4Comments

YaroslavOsetrov picture YaroslavOsetrov  路  3Comments

fareshan picture fareshan  路  3Comments