Skip to content

hook into postgraphql mutations to send email via mailgun

Notifications You must be signed in to change notification settings

stlbucket/postgraphql-hook-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

postgraphql-hook-demo

setup and demo

This demo builds upon postgraphql ^4.0 to show how to send emails via mailgun.

For now, postgraphql-hook is used to help setup the hook. This library may or may not be subsumed into the postgraphql library in some way.

After setting up your mailgun account, follow these steps to send an email through postgraphql:

git clone https://github.com/stlbucket/postgraphql-hook-demo.git

Create a new database to use with the demo - 'pgql_hook' is a good name, but use whatever you like.

Copy 'example_config.js' to 'config.js' in root directory and update the following settings:

  • DB_CONNECTION_STRING
  • MAILGUN_API_KEY
  • MAILGUN_DOMAIN
npm install

If you do not already have knex-migrate installed globally:

npm install -g knex-migrate
knex-migrate up
npm start

Navigate to http://localhost:3000/graphiql and execute this mutation:

mutation {
  sendEmail(input: {
    _fromAddress: "YOUR VALID FROM EMAIL"
    _toAddress: "YOUR VALID TO EMAIL"
    _subject: "Mailgun Test"
    _body: "You got it, you get it, you're gonna get it!"
  }) {
    emailInfo {
      id
      fromAddress
      toAddress
      subject
      body
    }
  }
}

the code that matters

sendEmail.js

const apiKey = process.env.MAILGUN_API_KEY
const domain = process.env.MAILGUN_DOMAIN

const mailgun = require('mailgun-js')({apiKey: apiKey, domain: domain})
const appendMutation = require('postgraphql-hook').appendMutation

async function handler (args, result) {
  const emailInfo = result.data

  const mailgunData = {
    from: `Postgraphql-Mailgun Demo <${emailInfo.fromAddress}>`,
    to: emailInfo.toAddress,
    subject: emailInfo.subject,
    text: emailInfo.body
  }

  console.log('SENDING EMAIL', emailInfo)

  mailgun
    .messages()
    .send(mailgunData, function (error, body) {
      if (error) {
        console.log('MAILGUN ERROR', error)
      } else {
        console.log('MAILGUN RESULT', body)
      }
    })
}

const plugin = appendMutation({
  mutationName: 'sendEmail',
  handler: handler
})

module.exports = plugin

About

hook into postgraphql mutations to send email via mailgun

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published