-
Notifications
You must be signed in to change notification settings - Fork 548
/
receive-message.ts
61 lines (54 loc) · 1.78 KB
/
receive-message.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import {
InitializeHandler,
InitializeHandlerArguments,
InitializeHandlerOptions,
InitializeHandlerOutput,
InitializeMiddleware,
MetadataBearer,
Pluggable,
} from "@aws-sdk/types";
import { toHex } from "@aws-sdk/util-hex-encoding";
import { PreviouslyResolved } from "./configurations";
interface ReceiveMessageResult {
Messages: Array<Message>;
}
interface Message {
Body: string | undefined;
MD5OfBody: string | undefined;
MessageId: string | undefined;
}
export function receiveMessageMiddleware(options: PreviouslyResolved): InitializeMiddleware<any, any> {
return <Output extends MetadataBearer>(
next: InitializeHandler<any, Output>
): InitializeHandler<any, Output> => async (
args: InitializeHandlerArguments<any>
): Promise<InitializeHandlerOutput<Output>> => {
const resp = await next({ ...args });
const output = (resp.output as unknown) as ReceiveMessageResult;
const messageIds = [];
if (output.Messages !== undefined) {
for (const message of output.Messages) {
const md5 = message.MD5OfBody;
const hash = new options.md5();
hash.update(message.Body || "");
if (md5 !== toHex(await hash.digest())) {
messageIds.push(message.MessageId);
}
}
}
if (messageIds.length > 0) {
throw new Error("Invalid MD5 checksum on messages: " + messageIds.join(", "));
}
return resp;
};
}
export const receiveMessageMiddlewareOptions: InitializeHandlerOptions = {
step: "initialize",
tags: ["VALIDATE_BODY_MD5"],
name: "receiveMessageMiddleware",
};
export const getReceiveMessagePlugin = (config: PreviouslyResolved): Pluggable<any, any> => ({
applyToStack: (clientStack) => {
clientStack.add(receiveMessageMiddleware(config), receiveMessageMiddlewareOptions);
},
});