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.
npm i fastify-mysql --save
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.
This project is kindly sponsored by:
Licensed under MIT.