Skip to content

Commit

Permalink
Merge pull request #489 from numbersprotocol/feature-avoid-duplicate-…
Browse files Browse the repository at this point in the history
…write

Avoid duplicate write when setAsset in Proof.
  • Loading branch information
shc261392 authored Jan 27, 2021
2 parents 8a724e3 + c7f6c74 commit 1616e12
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
23 changes: 22 additions & 1 deletion src/app/shared/services/image-store/image-store.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,24 @@ export class ImageStore {
return result.data;
}

async write(base64: string, mimeType: MimeType) {
async write(
base64: string,
mimeType: MimeType,
onWriteExistStrategy = OnWriteExistStrategy.REPLACE
) {
const index = await sha256WithBase64(base64);
await this.initialize();
if (onWriteExistStrategy === OnWriteExistStrategy.REPLACE) {
return this._write(index, base64, mimeType);
}
const exists = await this.exists(index);
if (exists) {
return index;
}
return this._write(index, base64, mimeType);
}

private async _write(index: string, base64: string, mimeType: MimeType) {
await this.initialize();
return this.mutex.runExclusive(async () => {
const imageExtension = await this.setImageExtension(index, mimeType);
Expand Down Expand Up @@ -226,3 +242,8 @@ interface Thumbnail extends Tuple {
readonly imageIndex: string;
readonly thumbnailIndex: string;
}

export const enum OnWriteExistStrategy {
IGNORE,
REPLACE,
}
11 changes: 9 additions & 2 deletions src/app/shared/services/repositories/proof/proof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { sortObjectDeeplyByKey } from '../../../../utils/immutable/immutable';
import { MimeType } from '../../../../utils/mime-type';
import { toDataUrl } from '../../../../utils/url';
import { Tuple } from '../../database/table/table';
import { ImageStore } from '../../image-store/image-store.service';
import {
ImageStore,
OnWriteExistStrategy,
} from '../../image-store/image-store.service';

export class Proof {
diaBackendAssetId?: string = undefined;
Expand Down Expand Up @@ -35,7 +38,11 @@ export class Proof {
async setAssets(assets: Assets) {
const indexedAssetEntries: [string, AssetMeta][] = [];
for (const [base64, meta] of Object.entries(assets)) {
const index = await this.imageStore.write(base64, meta.mimeType);
const index = await this.imageStore.write(
base64,
meta.mimeType,
OnWriteExistStrategy.IGNORE
);
indexedAssetEntries.push([index, meta]);
}

Expand Down

0 comments on commit 1616e12

Please sign in to comment.