Currently I have a Product class like so:
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(() => Product, (product) => product.id, {
onDelete: 'RESTRICT',
onUpdate: 'CASCADE',
})
@JoinTable({ joinColumn: { name: 'product_id_1' } })
sub_products: Product[];
...
}
When a user wants to create/update a Product, I'll need to check if there's a cyclic relation between them.
For example:
- Product A with id: 1 { sub_products: [B] }
- Product B with id: 2 { sub_products: [C] }
- User tries to update Product C with id: 3 with { sub_products: [A] } // should prevent this
What I have in mind is:
- Construct a graph recursively by querying the database to fetch the next children. Where vertices are products, and edges represent a parent relation (from: parent, to: child)
- Run DFS cycle detection algorithm from https://stackoverflow.com/a/53995651/13142405
My question is:
- In order to do (1), would it suffice if I only construct the vertex/edges of unvisited nodes before? Meaning to say I'll keep a set of visited products, and if the next product I see is in this set, I can skip construction of its vertex/edge.
- Would it suffice to prove its correctness with the following tests?
Tests:




Solved this by: