serverless-spy
Version:
CDK-based library for writing elegant integration tests on AWS serverless architecture and an additional web console to monitor events in real time.
45 lines (44 loc) • 1.55 kB
JavaScript
import { toBase64 } from "@smithy/util-base64";
import { Duplex } from "stream";
export class ChecksumStream extends Duplex {
constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) {
super();
if (typeof source.pipe === "function") {
this.source = source;
}
else {
throw new Error(` /util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);
}
this.base64Encoder = base64Encoder ?? toBase64;
this.expectedChecksum = expectedChecksum;
this.checksum = checksum;
this.checksumSourceLocation = checksumSourceLocation;
this.source.pipe(this);
}
_read(size) { }
_write(chunk, encoding, callback) {
try {
this.checksum.update(chunk);
this.push(chunk);
}
catch (e) {
return callback(e);
}
return callback();
}
async _final(callback) {
try {
const digest = await this.checksum.digest();
const received = this.base64Encoder(digest);
if (this.expectedChecksum !== received) {
return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` +
` in response header "${this.checksumSourceLocation}".`));
}
}
catch (e) {
return callback(e);
}
this.push(null);
return callback();
}
}