Created
August 14, 2021 15:23
-
-
Save lmammino/f27c4ae0e7ae88f40bb342baa1a6d499 to your computer and use it in GitHub Desktop.
Sample Fastify Plugin to connect to MariaDB/MySql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const fp = require('fastify-plugin') | |
const mysql = require('mysql2/promise') | |
const CONNECTION_STRING = process.env.DB_CONN_STRING | |
module.exports = fp(async function (fastify, opts) { | |
const db = await mysql.createConnection(CONNECTION_STRING) | |
fastify.decorate('db', db) | |
fastify.addHook('onClose', async function () { | |
return db.end() | |
}) | |
fastify.log.info(`Database connected to "${db.connection.config.host}:${db.connection.config.port}" as "${db.connection.config.user}"`) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
module.exports = async function (fastify, opts) { | |
fastify.get('/some-data', async function (request, reply) { | |
let data = await fastify.db.execute( | |
'SELECT * FROM someTable LIMIT 10' | |
) | |
return data | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment