Created
May 22, 2019 18:55
-
-
Save rightisleft/0f170a563f8235413ebf01cd2652c9c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ObjectStoreInjectable} from "./objectStore.injectable"; | |
import {Container} from "aurelia-dependency-injection"; | |
import {HeadObjectOutput} from "aws-sdk/clients/s3"; | |
export class SimpleFileState<T> { | |
private _assetId: string; | |
private _store: ObjectStoreInjectable; | |
public state: FileState<T>; | |
private _inFlight: boolean = false; | |
constructor(private _container: Container) { | |
} | |
public configure(assetId: string): SimpleFileState<T> { | |
this._assetId = assetId; | |
return this; | |
} | |
public async init() { | |
console.log('SimpleFileState::init'); | |
this._store = this._container.get(ObjectStoreInjectable); | |
await this._touch(); | |
} | |
private async _touch(): Promise<void> { | |
console.log('SimpleFileState::touch'); | |
const existingState: HeadObjectOutput = await this._store.hasKey(this._assetId); | |
if (existingState) { | |
console.log('SimpleFileState::touch::assetId', this._assetId); | |
this.state = await this._store.getObjectByJsonKey(this._assetId); | |
console.log('Initial file state set to: ', this.state); | |
} else { | |
this.state = { entities: [] }; | |
await this._store.putObject(JSON.stringify(this.state), this._assetId, {}, 'application/json'); | |
console.log('New initial file state created!'); | |
} | |
} | |
private async ensureAtomic(handle: () => Promise<void>) { | |
if (this._inFlight) { | |
throw new Error("race condition encountered"); | |
} else { | |
this._inFlight = true; | |
await handle() | |
this._inFlight = false; | |
} | |
} | |
public async persist(): Promise<void> { | |
await this.ensureAtomic(async () => { | |
const str: string = JSON.stringify(this.state); | |
const type: string = 'application/json'; | |
const response: string = await this._store.putObject(str, this._assetId, {}, type); | |
console.log('Object Store updated on: persist()', response); | |
}); | |
} | |
} | |
export interface FileState<T> { entities: T[]; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment