Ravel DatabaseProvider for MySQL
ravel-mysql-provider
is a DatabaseProvider
for Ravel, wrapping the powerful node mysql library. It supports connection pooling as well as Ravel's transaction system (including rollbacks).
app.js
const app = new require('ravel')();
const MySQLProvider = require('ravel-mysql-provider');
app.registerProvider(MySQLProvider);
// ... other providers and parameters
app.scan('./modules');
app.scan('./resources');
// ... the rest of your Ravel app
app.start();
resources/posts_resource.js
const Ravel = require('ravel');
const autoinject = Ravel.autoinject;
const Resource = Ravel.Resource;
const transaction = Resource.transaction;
@Resource('/post')
@autoinject('posts')
class PostsResource {
/**
* Retrieve a single post
*/
@transaction('mysql')
get(ctx) {
// Best practice is to pass the transaction object through to a Module, where you handle the actual business logic.
return this.posts.getPost(ctx.transaction, ctx.params.id)
.then((posts) => {
ctx.body = posts;
});
}
}
modules/posts.js
const Ravel = require('ravel');
const Module = Ravel.Module;
@Module('posts')
class Posts {
getPost(transaction, id) {
return new Promise((resolve, reject) => {
const mysql = transaction['mysql'];
// for more information about the mysql connection's capabilities, visit the docs: https://github.com/mysqljs/mysql
mysql.query(
`SELECT * from posts WHERE \`id\` = ?`,
[id],
(err, results) => {
if (err) { return reject(err); }
resolve(results);
}
);
});
}
}
Requiring the ravel-mysql-provider
module will register a configuration parameter with Ravel which must be supplied via .ravelrc
or app.set()
:
.ravelrc
{
"mysql options": {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "a password",
"database": "mydatabase"
}
}
All options for a mysql
connection are supported, and are documented here.
ravel-mysql-provider
also supports multiple simultaneous pools for different mysql databases, as long as you name them:
app.js
const app = new require('ravel')();
const MySQLProvider = require('ravel-mysql-provider');
app.registerProvider(app, 'first mysql');
app.registerProvider(app, 'second mysql');
// ... other providers and parameters
app.start();
.ravelrc
{
"first mysql options": {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "a password",
"database": "myfirstdatabase"
},
"second mysql options": {
"host": "localhost",
"port": 3307,
"user": "root",
"password": "another password",
"database": "myseconddatabase"
}
}
resources/posts_resource.js
const Ravel = require('ravel');
const Resource = Ravel.Resource;
const transaction = Resource.transaction;
@Resource('/post')
class PostsResource {
// ...
@transaction('first mysql', 'second mysql')
get(ctx) {
// can use ctx.transaction['first mysql']
// and ctx.transaction['second mysql']
}
}
ravel-mysql-provider
bakes-in the named parameter syntax described here.