Skip to content

Commit

Permalink
Merge pull request #69 from energywebfoundation/synced-status
Browse files Browse the repository at this point in the history
  • Loading branch information
soanvig authored Jan 12, 2022
2 parents 39a213e + d16005d commit 0c95801
Show file tree
Hide file tree
Showing 14 changed files with 532 additions and 185 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
import { groupBy } from 'lodash';

export class AddIsSyncedToReadModel1641991678453 implements MigrationInterface {
name = 'AddIsSyncedToReadModel1641991678453';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "certificate_read_model" ADD "isSynced" boolean`);
await this.setSyncStatus(queryRunner);
await queryRunner.query(
`ALTER TABLE "certificate_read_model" ALTER COLUMN "isSynced" SET NOT NULL`
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "certificate_read_model" DROP COLUMN "isSynced"`);
}

private async setSyncStatus(queryRunner: QueryRunner): Promise<void> {
const events = await queryRunner.query(`SELECT * FROM certificate_event`);

const eventsByCertificate = groupBy(events, 'internalCertificateId');

for (const [internalCertificateId, events] of Object.entries(eventsByCertificate)) {
const isSynced = this.reduceIsSynced(events);

await queryRunner.query(
`UPDATE "certificate_read_model" SET "isSynced" = $1 WHERE "internalCertificateId" = $2`,
[isSynced, internalCertificateId]
);
}
}

private reduceIsSynced(events: any[]): boolean {
const toPersistCounter = events.reduce((toPersistCounter, event) => {
switch (event.type) {
case 'Issued':
case 'Transferred':
case 'Claimed':
return toPersistCounter + 1;
case 'ClaimPersisted':
case 'IssuancePersisted':
case 'TransferPersisted':
return toPersistCounter - 1;
case 'PersistError':
return toPersistCounter;
default:
toPersistCounter;
}
}, 0);

if (toPersistCounter > 0) {
return false;
} else if (toPersistCounter === 0) {
return true;
} else {
throw new Error(
`Too many persisted events for certificate ${events[0].internalCertificateId}`
);
}
}
}
2 changes: 1 addition & 1 deletion packages/origin-247-certificate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"main": "./dist/js/src/index.js",
"types": "./dist/js/src/index.d.ts",
"scripts": {
"test:unit": "jest --testRegex 'offchain-certificate\\.spec.ts$'",
"test:unit": "jest --testRegex '\\.spec.ts$'",
"test:e2e": "concurrently --success first --kill-others -n eth,test \"yarn run:ganache\" \"wait-on tcp:8545 && yarn drop && yarn migrate && jest --maxWorkers 1 --testRegex '.e2e-spec.ts$'\"",
"build": "tsc -b tsconfig.json",
"migrate": "yarn typeorm:run && yarn typeorm:run:issuer",
Expand Down
Loading

0 comments on commit 0c95801

Please sign in to comment.