Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): record metadata when entity is created and updated #1847

Merged
merged 3 commits into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/app/core/entity/entity-mapper.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ import { waitForAsync } from "@angular/core/testing";
import { PouchDatabase } from "../database/pouch-database";
import { DatabaseEntity, entityRegistry } from "./database-entity.decorator";
import { Child } from "../../child-dev-project/children/model/child";
import { TEST_USER } from "../../utils/mocked-testing.module";
import { SessionService } from "../session/session-service/session.service";

describe("EntityMapperService", () => {
let entityMapper: EntityMapperService;
let testDatabase: PouchDatabase;
let mockSessionService: jasmine.SpyObj<SessionService>;

const existingEntity = {
_id: "Entity:existing-entity",
Expand All @@ -41,9 +44,11 @@ describe("EntityMapperService", () => {

beforeEach(waitForAsync(() => {
testDatabase = PouchDatabase.create();
mockSessionService = jasmine.createSpyObj(["getCurrentUser"]);
entityMapper = new EntityMapperService(
testDatabase,
new EntitySchemaService(),
mockSessionService,
entityRegistry
);

Expand Down Expand Up @@ -273,6 +278,36 @@ describe("EntityMapperService", () => {
});
});

it("sets the entityCreated property on save if it is a new entity & entityUpdated on subsequent saves", async () => {
jasmine.clock().install();
mockSessionService.getCurrentUser.and.returnValue({
name: TEST_USER,
roles: [],
});
const id = "test_created";
const entity = new Entity(id);

const mockTime1 = 1;
jasmine.clock().mockDate(new Date(mockTime1));
await entityMapper.save<Entity>(entity);
const createdEntity = await entityMapper.load<Entity>(Entity, id);

expect(createdEntity.created?.at.getTime()).toEqual(mockTime1);
expect(createdEntity.created?.by).toEqual(TEST_USER);
expect(createdEntity.updated?.at.getTime()).toEqual(mockTime1);
expect(createdEntity.updated?.by).toEqual(TEST_USER);

const mockTime2 = mockTime1 + 1;
jasmine.clock().mockDate(new Date(mockTime2));
await entityMapper.save<Entity>(createdEntity);
const updatedEntity = await entityMapper.load<Entity>(Entity, id);

expect(updatedEntity.created?.at.getTime()).toEqual(mockTime1);
expect(updatedEntity.updated?.at.getTime()).toEqual(mockTime2);

jasmine.clock().uninstall();
});

function receiveUpdatesAndTestTypeAndId(type?: string, entityId?: string) {
return new Promise<void>((resolve) => {
entityMapper.receiveUpdates(Entity).subscribe((e) => {
Expand Down
15 changes: 15 additions & 0 deletions src/app/core/entity/entity-mapper.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { Observable } from "rxjs";
import { UpdatedEntity } from "./model/entity-update";
import { EntityRegistry } from "./database-entity.decorator";
import { map } from "rxjs/operators";
import { UpdateMetadata } from "./model/update-metadata";
import { SessionService } from "../session/session-service/session.service";

/**
* Handles loading and saving of data for any higher-level feature module.
Expand All @@ -39,6 +41,7 @@ export class EntityMapperService {
constructor(
private _db: Database,
private entitySchemaService: EntitySchemaService,
private sessionService: SessionService,
private registry: EntityRegistry
) {}

Expand Down Expand Up @@ -136,6 +139,7 @@ export class EntityMapperService {
entity: T,
forceUpdate: boolean = false
): Promise<any> {
this.setEntityMetadata(entity);
const rawData =
this.entitySchemaService.transformEntityToDatabaseFormat(entity);
const result = await this._db.put(rawData, forceUpdate);
Expand All @@ -153,6 +157,7 @@ export class EntityMapperService {
* @param entities The entities to save
*/
public async saveAll(entities: Entity[]): Promise<any> {
entities.forEach((e) => this.setEntityMetadata(e));
const rawData = entities.map((e) =>
this.entitySchemaService.transformEntityToDatabaseFormat(e)
);
Expand Down Expand Up @@ -183,4 +188,14 @@ export class EntityMapperService {
return constructible;
}
}

private setEntityMetadata(entity: Entity) {
const newMetadata = new UpdateMetadata(
this.sessionService.getCurrentUser()?.name
);
if (entity.isNew) {
entity.created = newMetadata;
}
entity.updated = newMetadata;
}
}
6 changes: 2 additions & 4 deletions src/app/core/entity/mock-entity-mapper-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class MockEntityMapperService extends EntityMapperService {
private observables: Map<string, Subject<UpdatedEntity<any>>> = new Map();

constructor() {
super(null, null, entityRegistry);
super(null, null, null, entityRegistry);
}

private publishUpdates(type: string, update: UpdatedEntity<any>) {
Expand All @@ -45,9 +45,7 @@ export class MockEntityMapperService extends EntityMapperService {
this.data.get(type).set(entity.getId(), entity);
this.publishUpdates(
entity.getType(),
alreadyExists
? { type: "update", entity }
: { type: "new", entity }
alreadyExists ? { type: "update", entity } : { type: "new", entity }
);
}

Expand Down
13 changes: 13 additions & 0 deletions src/app/core/entity/model/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { EntitySchema } from "../schema/entity-schema";
import { DatabaseField } from "../database-field.decorator";
import { getWarningLevelColor, WarningLevel } from "./warning-level";
import { IconName } from "@fortawesome/fontawesome-svg-core";
import { UpdateMetadata } from "./update-metadata";

/**
* This represents a static class of type <T>.
Expand Down Expand Up @@ -169,6 +170,18 @@ export class Entity {
/** internal database doc revision, used to detect conflicts by PouchDB/CouchDB */
@DatabaseField() _rev: string;

@DatabaseField({
dataType: "schema-embed",
additional: UpdateMetadata,
})
created: UpdateMetadata;

@DatabaseField({
dataType: "schema-embed",
additional: UpdateMetadata,
})
updated: UpdateMetadata;

@DatabaseField({
label: $localize`:Label of checkbox:Inactive`,
description: $localize`:Description of checkbox:Ticking this box will archive the record. No data will be lost but the record will be hidden.`,
Expand Down
17 changes: 17 additions & 0 deletions src/app/core/entity/model/update-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { DatabaseField } from "../database-field.decorator";

/**
* Object to store metadata about a "revision" of a document including date and author of the change.
*/
export class UpdateMetadata {
/** when the update was saved to db */
@DatabaseField() at: Date;

/** username who saved the update */
@DatabaseField() by: string;

constructor(by: string, at: Date = new Date()) {
this.by = by;
this.at = at;
}
}