Skip to content

Instantly share code, notes, and snippets.

@vivmaha
Created January 28, 2022 18:23
Show Gist options
  • Save vivmaha/4e2904830108ad24694103c8563f83da to your computer and use it in GitHub Desktop.
Save vivmaha/4e2904830108ad24694103c8563f83da to your computer and use it in GitHub Desktop.
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