danyalutsevich
danyalutsevich

Reputation: 130

Record versioning and approving changes TypeOrm postgres

I need to setup record versioning and approvin changes pattern for my app. For now i have two entities that are identical. When user changes some data it will be added in the first entity. After admin approves the changes the data will be copied to the second (Main) entity. This approach does not seems right. I'm thinking of using the @VersionColumn and admin will only set the active version. Im thinking of how it can be implemented. May be you have other solutions please let me know how it can be implemented.

Im currently thinking of creating a OneToOne relation with this kind of entity

@Entity({ name: 'version' })
export class VersionEntity {
  @PrimaryGeneratedColumn() // may be this is wrong decorator for this purpose
  id: number;

  @Column()
  activeVersion: number;
}

It will contain id of the entity(which is unchanged when new versions added) and active version id

The problem is that the records in this VesionEntity table should somehow appear and i dont know what is the proper way of doing it.

P.S. Im using postgres if that helps

Upvotes: 0

Views: 283

Answers (1)

TSCAmerica.com
TSCAmerica.com

Reputation: 5377

Instead of having two separate entities for the unapproved and approved data, you can have a single entity that contains all versions of the data along with a status to indicate whether it's approved or not. Try this

@Entity()
export class VersionedEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @VersionColumn()
  version: number;

  @Column()
  data: string; // Your data fields here

  @Column({ default: 'PENDING' })
  status: 'PENDING' | 'APPROVED';

  // Relationship to self to indicate the active approved version
  @OneToOne(() => VersionedEntity)
  @JoinColumn()
  activeVersion: VersionedEntity;
}

GET all active versions

const activeVersions = await repository.find({
  where: {
    status: 'APPROVED',
    activeVersion: Not(IsNull()),
  },
  relations: ['activeVersion'],
});

Upvotes: 1

Related Questions