diff --git a/src/handlers.spec.js b/src/handlers.spec.js index 09486c1..8fffd87 100644 --- a/src/handlers.spec.js +++ b/src/handlers.spec.js @@ -5,7 +5,7 @@ import { payload } from './mail'; describe('handlers', () => { beforeAll(() => { - global.fetch = vi.fn().mockImplementation(() => new Response()); + global.fetch = vi.fn().mockImplementation(() => new Response('{}')); }); it('400 if missing required parameters', async () => { diff --git a/src/log.js b/src/log.js new file mode 100644 index 0000000..d9187cf --- /dev/null +++ b/src/log.js @@ -0,0 +1,20 @@ +export const log = async ({ env, user_id, tags }) => { + const response = await fetch('https://api.logsnag.com/v1/log', { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${env.LOGSNAG_API_TOKEN}`, + }, + body: JSON.stringify({ + project: 'cinotify', + channel: 'api', + event: 'mail', + icon: '📬', + user_id, + tags, + }), + method: 'POST', + }); + const data = await response.json(); + // eslint-disable-next-line no-console + console.log(data); +}; diff --git a/src/mail.js b/src/mail.js index c11db55..eead642 100644 --- a/src/mail.js +++ b/src/mail.js @@ -1,3 +1,5 @@ +import { log } from './log'; + export const payload = ({ subject, to, type, body, attachments }) => ({ // https://docs.sendgrid.com/api-reference/mail-send/mail-send#body attachments, @@ -31,6 +33,15 @@ export const mail = async ({ env = {}, ...rest }) => { method: 'POST', body: JSON.stringify(payload({ ...rest })), }); + await log({ + env, + user_id: rest.to?.split(',')[0], + tags: { + attachments: !!rest.attachments, + contentType: rest.type, + status: response.status, + }, + }); if (response.status > 299) { throw new Error((await response.json()).errors[0].message); } diff --git a/src/mail.test.js b/src/mail.test.js index 4247d16..f4d3c69 100644 --- a/src/mail.test.js +++ b/src/mail.test.js @@ -31,7 +31,7 @@ describe('mail', () => { global.fetch = vi.fn(); }); it('makes a request to the sendgrid api', async () => { - global.fetch.mockResolvedValueOnce({ json: () => '{}' }); + global.fetch.mockResolvedValue({ json: () => '{}' }); await mail(input); expect(global.fetch).toHaveBeenCalledWith( 'https://api.sendgrid.com/v3/mail/send', @@ -45,6 +45,27 @@ describe('mail', () => { }, ); }); + it('logs', async () => { + global.fetch.mockResolvedValue({ json: () => '{}', status: 200 }); + await mail({ ...input, to: 'one@example.com,two@example.com' }); + expect(global.fetch).toHaveBeenCalledWith( + 'https://api.logsnag.com/v1/log', + expect.objectContaining({ + body: JSON.stringify({ + project: 'cinotify', + channel: 'api', + event: 'mail', + icon: '📬', + user_id: 'one@example.com', + tags: { + attachments: true, + contentType: 'text/html', + status: 200, + }, + }), + }), + ); + }); }); describe('payload', () => {