Created
January 28, 2022 18:23
-
-
Save vivmaha/4e2904830108ad24694103c8563f83da 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 { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"; | |
import stableStringify from "fast-json-stable-stringify"; | |
import forge from "node-forge"; | |
import { createS3Client } from "./client-aws"; | |
import { streamToString } from "./stream-ultils"; | |
function get128BitHash(input: string): string { | |
const messageDigest = forge.md.md5.create(); | |
messageDigest.update(input); | |
return messageDigest.digest().toHex(); | |
} | |
// S3-backed POJO dictionary | |
export class BlobStore<TKey, TItem> { | |
constructor(private bucketName: string, private prefix: string) {} | |
private getS3Key(key: TKey): string { | |
const hashedItemKey = get128BitHash(stableStringify(key)); | |
const s3Key = this.prefix + hashedItemKey; | |
return s3Key; | |
} | |
async set(key: TKey, item: TItem): Promise<void> { | |
await createS3Client().send( | |
new PutObjectCommand({ | |
Bucket: this.bucketName, | |
Key: this.getS3Key(key), | |
Body: JSON.stringify(item), | |
}) | |
); | |
} | |
async get(key: TKey): Promise<TItem> { | |
const item = await createS3Client().send( | |
new GetObjectCommand({ | |
Bucket: this.bucketName, | |
Key: this.getS3Key(key), | |
}) | |
); | |
const str = await streamToString(item.Body); | |
return JSON.parse(str) as TItem; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment