on dee2cd5 help sign in
bridge/src/lib/useMailer.js
57 lines 1.6 kB history raw
1import { useCallback } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
4import { hasReceived, sendMail } from './inviteMail';
5import useSetState from './useSetState';
7const STUB_MAILER = process.env.REACT_APP_STUB_MAILER === 'true';
9function useHasReceivedCache() {
10 const [cache, addToCache] = useSetState();
12 const getHasRecieved = useCallback(
13 email => cache[email] || Nothing(), //
14 [cache]
15 );
17 const syncHasReceivedForEmail = useCallback(
18 async email => {
19 if (Just.hasInstance(getHasRecieved(email))) {
20 // never update the cache after we know about it
21 return;
22 }
24 if (STUB_MAILER) {
25 // always allow sending emails when stubbing
26 return addToCache({ [email]: Just(false) });
27 }
29 const _hasReceived = await hasReceived(email);
30 addToCache({ [email]: Just(_hasReceived) });
31 },
32 [getHasRecieved, addToCache]
33 );
35 return { getHasRecieved, syncHasReceivedForEmail };
38export default function useMailer(emails) {
39 const hasReceivedCache = useHasReceivedCache(emails);
41 // prefix to avoid clobbering sendMail import
42 // also throws if return value is false
43 const _sendMail = useCallback(async (email, ticket, rawTx) => {
44 if (STUB_MAILER) {
45 console.log(`${email} - ${ticket}`);
46 return;
47 }
49 const mailSuccess = await sendMail(email, ticket, rawTx);
51 if (!mailSuccess) {
52 throw new Error(`Internal mailing error when mailing ${email}`);
53 }
54 }, []);
56 return { ...hasReceivedCache, sendMail: _sendMail };