Skip to content

Latest commit

 

History

History
102 lines (79 loc) · 2.43 KB

README.md

File metadata and controls

102 lines (79 loc) · 2.43 KB

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