Ridhwaan Shakeel
Ridhwaan Shakeel

Reputation: 1043

How do you fix this circular dependency issue in node

` I'm getting errors such as Type variable is undefined and getLastUnknownAlbumTrackNumber is not a function

I installed madge to check circular dependencies but I dont know how to resolve them

following is the output from madge

const madge = require('madge');

madge('./server.js').then((res) => {
    console.log(res.circular());
});

OUTPUT:
(node:6960) Warning: Accessing non-existent property 'getLastUnknownAlbumTrackNumber' of module exports inside circular dependency
(node:6960) Warning: Accessing non-existent property 'Type' of module exports inside circular dependency
[
[ 'jobs/index.js', 'models/index.js' ],
[ 'models/index.js', 'services/metadata.js' ]
]

The following are the related imports & exports

jobs/index.js

const { getMovieMetaData, getTVShowMetaData, getAlbumMetaData } = require('../models');
...
module.exports = { getAll, upsertAll, getLastUnknownAlbumTrackNumber }

services/metadata.js

const { Type } = require('../models');
...
module.exports = Metadata

models/index.js

const { getLastUnknownAlbumTrackNumber } = require('../jobs');
const metadataServiceConstructor = require('../services/metadata');
const metadataService = new metadataServiceConstructor()
...
module.exports = { Type, getMovieMetaData, getTVShowMetaData, getAlbumMetaData }

Upvotes: 3

Views: 6447

Answers (2)

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27395

At first read, this answer may seem a bit cryptic
This is due to nature of cyclic dependency.

Once you understand it, it will be easy to fix your solution too

Issue:

1.js -> 2.js -> 3.js
                3.js -> 4.js -> 2.js ( `cycle` )

Solution that worked:

1.js -> 2.js `(remove connection)`
               3.js -> 4.js -> 2.js
1.js -> `200.js (add new)` -> 3.JS

Upvotes: 0

user4945014
user4945014

Reputation:

What do you expect to happen? An attempt to resolve a circular import would result in infinite recursion.

Even if you're using this tool to check for circular imports, it's not static analysis, so the code still needs to be run, hence you encounter the same issue.

As a side note, why are you using this tool at all? It's clear where the circular import lies. You need to refactor to avoid this.

Upvotes: 1

Related Questions