@api-buddy/sendgrid
Version:
API Buddy integration for SendGrid - Email delivery service for transactional and marketing emails
1 lines • 11.1 kB
Source Map (JSON)
{"version":3,"sources":["../src/client.ts","../src/hooks/useSendEmail.ts"],"sourcesContent":["import sgMail, { ClientResponse } from '@sendgrid/mail';\r\nimport { SendGridConfig, EmailOptions, BatchSendGridResponse } from './types';\r\n\r\nexport class SendGridClient {\r\n private config: SendGridConfig;\r\n private initialized = false;\r\n\r\n constructor(config: SendGridConfig) {\r\n this.config = config;\r\n this.initialize();\r\n }\r\n\r\n /**\r\n * Initialize the SendGrid client with the API key\r\n */\r\n private initialize(): void {\r\n if (!this.initialized) {\r\n if (!this.config.apiKey && !process.env.SENDGRID_API_KEY) {\r\n throw new Error(\r\n 'SendGrid API key is required. Either provide it in the config or set the SENDGRID_API_KEY environment variable.'\r\n );\r\n }\r\n\r\n sgMail.setApiKey(this.config.apiKey || process.env.SENDGRID_API_KEY!);\r\n this.initialized = true;\r\n }\r\n }\r\n\r\n /**\r\n * Send an email using SendGrid\r\n * @param options Email options\r\n * @returns Promise with the SendGrid response\r\n */\r\n public async sendEmail(options: EmailOptions) {\r\n if (!this.initialized) {\r\n this.initialize();\r\n }\r\n\r\n try {\r\n const msg = {\r\n to: options.to,\r\n from: options.from || this.config.defaultFrom || 'no-reply@example.com',\r\n subject: options.subject,\r\n text: options.text,\r\n html: options.html,\r\n templateId: options.templateId,\r\n dynamicTemplateData: options.dynamicTemplateData,\r\n attachments: options.attachments,\r\n categories: options.categories,\r\n customArgs: options.customArgs,\r\n headers: options.headers,\r\n mailSettings: options.mailSettings || this.config.mailSettings,\r\n trackingSettings: options.trackingSettings || this.config.trackingSettings,\r\n replyTo: options.replyTo || this.config.defaultReplyTo,\r\n sendAt: options.sendAt,\r\n batchId: options.batchId,\r\n asm: options.asm || this.config.asm,\r\n ipPoolName: options.ipPoolName || this.config.ipPoolName,\r\n };\r\n\r\n const [response] = await sgMail.send(msg as any);\r\n return {\r\n success: true,\r\n statusCode: response.statusCode,\r\n headers: response.headers,\r\n body: response.body,\r\n };\r\n } catch (error) {\r\n console.error('Error sending email:', error);\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Send multiple emails in a single request\r\n * @param messages Array of email options\r\n * @returns Promise with the SendGrid response\r\n */\r\n public async sendMultipleEmails(messages: EmailOptions[]) {\r\n if (!this.initialized) {\r\n this.initialize();\r\n }\r\n\r\n try {\r\n const formattedMessages = messages.map((msg) => ({\r\n to: msg.to,\r\n from: msg.from || this.config.defaultFrom || 'no-reply@example.com',\r\n subject: msg.subject,\r\n text: msg.text,\r\n html: msg.html,\r\n templateId: msg.templateId,\r\n dynamicTemplateData: msg.dynamicTemplateData,\r\n attachments: msg.attachments,\r\n categories: msg.categories,\r\n customArgs: msg.customArgs,\r\n headers: msg.headers,\r\n mailSettings: msg.mailSettings || this.config.mailSettings,\r\n trackingSettings: msg.trackingSettings || this.config.trackingSettings,\r\n replyTo: msg.replyTo || this.config.defaultReplyTo,\r\n sendAt: msg.sendAt,\r\n batchId: msg.batchId,\r\n asm: msg.asm || this.config.asm,\r\n ipPoolName: msg.ipPoolName || this.config.ipPoolName,\r\n }));\r\n\r\n const response = await sgMail.send(formattedMessages as any, true) as ClientResponse[];\r\n return {\r\n success: true,\r\n responses: response.map((res) => ({\r\n statusCode: res.statusCode,\r\n headers: res.headers,\r\n body: res.body,\r\n })),\r\n } as BatchSendGridResponse;\r\n } catch (error) {\r\n console.error('Error sending multiple emails:', error);\r\n throw error;\r\n }\r\n }\r\n}\r\n\r\n// Create a singleton instance\r\nexport const sendGridClient = new SendGridClient({\r\n apiKey: process.env.SENDGRID_API_KEY || '',\r\n});\r\n\r\n/**\r\n * Send an email using the default SendGrid client\r\n * @param options Email options\r\n * @returns Promise with the SendGrid response\r\n */\r\nexport const sendEmail = (options: EmailOptions) => {\r\n return sendGridClient.sendEmail(options);\r\n};\r\n\r\n/**\r\n * Send multiple emails in a single request using the default SendGrid client\r\n * @param messages Array of email options\r\n * @returns Promise with the SendGrid response\r\n */\r\nexport const sendMultipleEmails = (messages: EmailOptions[]) => {\r\n return sendGridClient.sendMultipleEmails(messages);\r\n};\r\n","'use client';\n\nimport { useState, useCallback } from 'react';\nimport { sendEmail, sendMultipleEmails } from '../client';\nimport { EmailOptions, SendGridResponse, SendGridError, BatchSendGridResponse } from '../types';\n\n/**\n * Hook for sending emails with SendGrid\n * @returns Object containing the send function, loading state, and error state\n */\nexport function useSendEmail(): {\n send: (options: EmailOptions) => Promise<SendGridResponse>;\n isLoading: boolean;\n error: SendGridError | null;\n response: SendGridResponse | null;\n reset: () => void;\n} {\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<SendGridError | null>(null);\n const [response, setResponse] = useState<SendGridResponse | null>(null);\n\n /**\n * Send an email using SendGrid\n * @param options Email options\n * @returns Promise with the SendGrid response\n */\n const send = useCallback(\n async (options: EmailOptions): Promise<SendGridResponse> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const result = await sendEmail(options);\n setResponse(result);\n return result;\n } catch (err: any) {\n setError(err);\n throw err;\n } finally {\n setIsLoading(false);\n }\n },\n []\n );\n\n const reset = useCallback(() => {\n setError(null);\n setResponse(null);\n }, []);\n\n return {\n send,\n isLoading,\n error,\n response,\n reset,\n };\n}\n\n/**\n * Hook for sending multiple emails with SendGrid\n * @returns Object containing the send function, loading state, and error state\n */\nexport function useSendMultipleEmails(): {\n send: (messages: EmailOptions[]) => Promise<BatchSendGridResponse>;\n isLoading: boolean;\n error: SendGridError | null;\n response: BatchSendGridResponse | null;\n reset: () => void;\n} {\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<SendGridError | null>(null);\n const [response, setResponse] = useState<BatchSendGridResponse | null>(null);\n\n const send = useCallback(\n async (messages: EmailOptions[]): Promise<BatchSendGridResponse> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const result = await sendMultipleEmails(messages);\n setResponse(result);\n return result;\n } catch (err: any) {\n setError(err);\n throw err;\n } finally {\n setIsLoading(false);\n }\n },\n []\n );\n\n const reset = useCallback(() => {\n setError(null);\n setResponse(null);\n }, []);\n\n return {\n send,\n isLoading,\n error,\n response,\n reset,\n };\n}\n"],"mappings":";AAAA,OAAOA,MAAgC,iBAGhC,IAAMC,EAAN,KAAqB,CAClB,OACA,YAAc,GAEtB,YAAYC,EAAwB,CAClC,KAAK,OAASA,EACd,KAAK,WAAW,CAClB,CAKQ,YAAmB,CACzB,GAAI,CAAC,KAAK,YAAa,CACrB,GAAI,CAAC,KAAK,OAAO,QAAU,CAAC,QAAQ,IAAI,iBACtC,MAAM,IAAI,MACR,iHACF,EAGFF,EAAO,UAAU,KAAK,OAAO,QAAU,QAAQ,IAAI,gBAAiB,EACpE,KAAK,YAAc,EACrB,CACF,CAOA,MAAa,UAAUG,EAAuB,CACvC,KAAK,aACR,KAAK,WAAW,EAGlB,GAAI,CACF,IAAMC,EAAM,CACV,GAAID,EAAQ,GACZ,KAAMA,EAAQ,MAAQ,KAAK,OAAO,aAAe,uBACjD,QAASA,EAAQ,QACjB,KAAMA,EAAQ,KACd,KAAMA,EAAQ,KACd,WAAYA,EAAQ,WACpB,oBAAqBA,EAAQ,oBAC7B,YAAaA,EAAQ,YACrB,WAAYA,EAAQ,WACpB,WAAYA,EAAQ,WACpB,QAASA,EAAQ,QACjB,aAAcA,EAAQ,cAAgB,KAAK,OAAO,aAClD,iBAAkBA,EAAQ,kBAAoB,KAAK,OAAO,iBAC1D,QAASA,EAAQ,SAAW,KAAK,OAAO,eACxC,OAAQA,EAAQ,OAChB,QAASA,EAAQ,QACjB,IAAKA,EAAQ,KAAO,KAAK,OAAO,IAChC,WAAYA,EAAQ,YAAc,KAAK,OAAO,UAChD,EAEM,CAACE,CAAQ,EAAI,MAAML,EAAO,KAAKI,CAAU,EAC/C,MAAO,CACL,QAAS,GACT,WAAYC,EAAS,WACrB,QAASA,EAAS,QAClB,KAAMA,EAAS,IACjB,CACF,OAASC,EAAO,CACd,cAAQ,MAAM,uBAAwBA,CAAK,EACrC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,MAAOC,GAAqD,CAC1DR,EAAa,EAAI,EACjBG,EAAS,IAAI,EAEb,GAAI,CACF,IAAMM,EAAS,MAAMC,EAAUF,CAAO,EACtC,OAAAH,EAAYI,CAAM,EACXA,CACT,OAASE,EAAU,CACjB,MAAAR,EAASQ,CAAG,EACNA,CACR,QAAE,CACAX,EAAa,EAAK,CACpB,CACF,EACA,CAAC,CACH,EAEMY,EAAQL,EAAY,IAAM,CAC9BJ,EAAS,IAAI,EACbE,EAAY,IAAI,CAClB,EAAG,CAAC,CAAC,EAEL,MAAO,CACL,KAAAC,EACA,UAAAP,EACA,MAAAG,EACA,SAAAE,EACA,MAAAQ,CACF,CACF,CAMO,SAASC,GAMd,CACA,GAAM,CAACd,EAAWC,CAAY,EAAIC,EAAS,EAAK,EAC1C,CAACC,EAAOC,CAAQ,EAAIF,EAA+B,IAAI,EACvD,CAACG,EAAUC,CAAW,EAAIJ,EAAuC,IAAI,EAErEK,EAAOC,EACX,MAAOO,GAA6D,CAClEd,EAAa,EAAI,EACjBG,EAAS,IAAI,EAEb,GAAI,CACF,IAAMM,EAAS,MAAMM,EAAmBD,CAAQ,EAChD,OAAAT,EAAYI,CAAM,EACXA,CACT,OAASE,EAAU,CACjB,MAAAR,EAASQ,CAAG,EACNA,CACR,QAAE,CACAX,EAAa,EAAK,CACpB,CACF,EACA,CAAC,CACH,EAEMY,EAAQL,EAAY,IAAM,CAC9BJ,EAAS,IAAI,EACbE,EAAY,IAAI,CAClB,EAAG,CAAC,CAAC,EAEL,MAAO,CACL,KAAAC,EACA,UAAAP,EACA,MAAAG,EACA,SAAAE,EACA,MAAAQ,CACF,CACF","names":["sgMail","SendGridClient","config","options","msg","response","error","messages","formattedMessages","res","sendGridClient","sendEmail","sendMultipleEmails","useState","useCallback","useSendEmail","isLoading","setIsLoading","useState","error","setError","response","setResponse","send","useCallback","options","result","sendEmail","err","reset","useSendMultipleEmails","messages","sendMultipleEmails"]}