Connect to external database


#1

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.


#2

Here is my hacky solution (Use it on your own risk):

  1. Make a copy of \core\server\data\db and paste it inside \node_modules\ghost-app\lib\

  2. Delete unecessary files backup.js and migrator.js in \node_modules\ghost-app\lib

  3. Install knex as a dependency for ghost-app

  4. 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;

  5. 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));
    }

  6. 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();
     };
    
  7. In your own App.js file (content\apps\your_app_name\index.js) you can now start quering. For example: this.db.knex.select()

  8. 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.


#3

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.