Circular Relations
Problem: circular imports
When two of your ActiveClasses are meant to reciprocally relate to each other, you may encounter a problem of circular imports.
For example, consider the below two classes defined in separate folders. For the purposes of simplicity, we are assuming:
- People own at most one pet; and
- Pets have at most one owner (who is a person).
- src/models/person.js
- src/models/animal.js
import { ActiveClass, Schema, relations } from 'fireactive'
import Animal from './animal'
const personSchema = {
name: Schema.string,
age: Schema.number,
petId: Schema.string({ optional: true }) // not all people have pets
}
class Person extends ActiveClass(personSchema) {
pet = relations.findById(Animal, 'petId')
}
export default Person
Because person.js
imports from animal.js
, which imports from person.js
... we can get stuck in some messy circular imports.
relations.store
One fix: You can reorganise your code to get around this, but there is an alternative solution provided by Fireactive.
To make a class available as a relation (without needing to be imported), pass it as an argument to relations.store
, and then you can set up a relation using the string name of that class:
- src/models/person.js
- src/models/animal.js
- Demo
import { ActiveClass, Schema, relations } from 'fireactive'
const personSchema = {
name: Schema.string,
age: Schema.number,
petId: Schema.string({ optional: true })
}
class Person extends ActiveClass(personSchema) {
// pass the string 'Animal' instead of the class
pet = relations.findById('Animal', 'petId')
}
// store the Person class so other classes can relate to it
relations.store(Person)
export default Person