This library helps to manage trees that are structured as as adjacency list in postgres.
It partially implements public interface of TreeRepository
from typeorm. Check tree-repository.interface.ts
npm i typeorm-pg-adjacency-list-tree
There are three decorators exported from this module: Tree
, TreeParent
and TreeChildren
.
Tree
is used to specify that decoratable entity is a tree.
@Tree()
@Entity()
export class Node {
@PrimaryGeneratedColumn()
public id!: number
@Column()
public value!: number
}
TreeParent
is used to identify class property which will hold entities parent:
@Tree()
@Entity()
export class Node {
@PrimaryGeneratedColumn()
public id!: number
@TreeParent()
public parent!: Node
@Column()
public value!: number
}
TreeChildren
is used to identify class property which will hold children of current entity:
@Tree()
@Entity()
export class Node {
@PrimaryGeneratedColumn()
public id!: number
@TreeParent()
public parent!: Node
@TreeChildren()
public children!: Node[]
@Column()
public value!: number
}
TreeRepository
can be used to access some methods used for working with trees:
// node-repository.ts
@EntityRepository(Node)
class NodeRepository extends TreeRepository<Node> {}
// node-service.ts
class NodeService {
private _nodeRepo = getConnection().getCustomRepository(NodeRepository)
public getAllTrees() {
return this._nodeRepo.findTrees()
}
}
public findTrees(options?: FindTreeOptions): Promise<Entity[]>
Gets complete trees for all roots in the table.
public findRoots(options?: FindTreeOptions): Promise<Entity[]>
Roots are entities that have no ancestors. Finds them all.
public findDescendants(entity: Entity, options?: FindTreeOptions): Promise<Entity[]>
Gets all children (descendants) of the given entity. Returns them all in a flat array.
public findDescendantsTree(entity: Entity, options?: FindTreeOptions): Promise<Entity>
Gets all children (descendants) of the given entity. Returns them in a tree - nested into each other.
public countDescendants(entity: Entity): Promise<number>
Gets number of descendants of the entity.
public createDescendantsQueryBuilder(alias: string, entity: Entity): Promise<SelectQueryBuilder<Entity>>
Creates a query builder used to get descendants of the entities in a tree.
public findAncestors(entity: Entity, options?: FindTreeOptions): Promise<Entity[]>
Creates a query builder used to get descendants of the entities in a tree.
public findAncestorsTree(entity: Entity, options?: FindTreeOptions): Promise<Entity>
Gets all parents (ancestors) of the given entity. Returns them in a tree - nested into each other.
public countAncestors(entity: Entity): Promise<number>
Gets number of ancestors of the entity.
public createAncestorsQueryBuilder(alias: string, entity: Entity): Promise<SelectQueryBuilder<Entity>>
Creates a query builder used to get ancestors of the entities in the tree.