From 5b1f73b2060b3e7211ddd429af85edc8b431452b Mon Sep 17 00:00:00 2001 From: Charles Fulnecky Date: Sat, 22 Jun 2019 18:13:56 -0400 Subject: [PATCH] Constrain dispatch to specific action types. --- src/index.ts | 6 ++++-- src/messaging/message-handler.ts | 8 +++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index 72ad7c9..26efe92 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,11 +23,13 @@ export const createMessageDispatcherMiddleware = ({ senderURL, parentURL, target type MessageRecieverOptions = { allowedURLs: string[]; + allowedTypes?: string[]; }; -export const createMessageRecieverMiddleware = ({ allowedURLs }: MessageRecieverOptions) => { +export const createMessageRecieverMiddleware = ({ allowedURLs, allowedTypes = [] }: MessageRecieverOptions) => { const messageToActionHandler = createMessageToActionHandler({ - allowedURLs + allowedURLs, + allowedTypes }); return MessageRecieverMiddleware({ messageToActionHandler }); diff --git a/src/messaging/message-handler.ts b/src/messaging/message-handler.ts index 1a1c174..d378a90 100644 --- a/src/messaging/message-handler.ts +++ b/src/messaging/message-handler.ts @@ -18,6 +18,7 @@ const isValidAction = (action: any): boolean => isString(action.type); type Dependencies = { allowedURLs: string[]; + allowedTypes?: string[]; } export type ActionHandler = (action: any) => void; @@ -26,17 +27,22 @@ export type MessageHandler = (ev: MessageEvent) => void; export type MessageToActionHandler = (fn: ActionHandler) => MessageHandler; -export const createMessageToActionHandler = ({ allowedURLs }: Dependencies): MessageToActionHandler => { +export const createMessageToActionHandler = ({allowedURLs: allowedURLs, allowedTypes: allowedTypes = []}: Dependencies): MessageToActionHandler => { const isValidOrigin = (origin: string): boolean => { return allowedURLs.some(url => url.includes(origin)); }; + const isValidType = (action: string): boolean => { + return allowedTypes !== undefined ? allowedTypes.some(type => type.includes(action)) : true; + }; + return (fn: ActionHandler): MessageHandler => (ev: MessageEvent) => { const origin = getEventOrigin(ev); if (!isValidOrigin(origin)) { return; } const action = readAction(ev); if (!isValidAction(action)) { return; } + if (!isValidType(action)) { return; } fn(action); }; };