I need to access some data on another database from my Ghost site. This data will be used in a Ghost template. I have therefore created an app using the Ghost-app module. In combination with “express-hbs/lib/async” I manage to fetch data with Ghost-API and use it inside handlebars. My problem is that my
data is outside of the Ghost-database/API and I need a new database connection to do custom queries. When I try to use the mysql-module inside my app, Ghost is throwing “InternalServerError” and “Error: Unsafe App require: mysql”.
So what is the best solution for query custom data? Is it possible to get a database connection if the app is moved to core/server/apps? Using a external REST-service will be to slow for my requirements.
I greatly appreciate any help.
Here is my hacky solution (Use it on your own risk):
-
Make a copy of \core\server\data\db and paste it inside \node_modules\ghost-app\lib\
-
Delete unecessary files backup.js and migrator.js in \node_modules\ghost-app\lib
-
Install knex as a dependency for ghost-app
-
Change include lines in \node_modules\ghost-app\lib\ghost-app\lib\db\connection.js to this (Better solution it to write a local config module).
var knex = require(‘knex’),
config = require(‘…/…/…/…/core/server/config’),
common = require(‘…/…/…/…/core/server/lib/common’),
knexInstance;
-
Change connection init settings in same file (Better is to use your new config-data from local config module as argument)
if (!knexInstance && config.get(‘database’) && config.get(‘database’).client) {
var newConfig = config.get(‘database’);
newConfig.connection[‘database’] = ‘YOUR_CUSTOM_DATABASE_NAME’;
knexInstance = knex(configure(newConfig));
}
-
Require db-module as an property of App-module (\node_modules\ghost-app\lib\App.js):
App = function (ghost) {
this.db = require('./db');
this.ghost = ghost;
this.initialize();
};
-
In your own App.js file (content\apps\your_app_name\index.js) you can now start quering. For example: this.db.knex.select()
-
With ‘express-hbs/lib/async’ module you can registerAsyncHelper in your app and use database result in handlebar templates. See (https://gist.github.com/ofstudio/e13276a9c587ecd41a95)
If anybody sees any potential dangers. Please tell me.