wedgwood / fastify-mysql

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fastify-mysql

Greenkeeper badge

js-standard-style Build Status

Fastify MySQL connection plugin, with this you can share the same MySQL connection pool in every part of your server. Under the hood the mysql is used, the options that you pass to register will be passed to the MySQL pool builder.

Install

npm i fastify-mysql --save

Usage

Add it to you project with register and you are done! This plugin will add the mysql namespace in your Fastify instance, with the following properties:

connect: the function to get a connection from the pool
pool: the pool instance
query: an utility to perform a query without a transaction

Example:

const fastify = require('fastify')

fastify.register(require('fastify-mysql'), {
  connectionString: 'mysql://root@localhost/mysql'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.mysql.connect(onConnect)

  function onConnect (err, client) {
    if (err) return reply.send(err)

    client.query(
      'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
      function onResult (err, result) {
        client.release()
        reply.send(err || result)
      }
    )
  }
})

fastify.listen(3000, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

Use of mysql.query

const fastify = require('fastify')

fastify.register(require('fastify-mysql'), {
  connectionString: 'mysql://root@localhost/mysql'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.mysql.query(
    'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen(3000, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

As you can see there is no need to close the client, since is done internally.

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.

About

License:MIT License


Languages

Language:JavaScript 100.0%