Auto-create mysql table with StrongLoop

后端 未结 8 819
栀梦
栀梦 2021-02-07 11:39

I am trying to use Strongloop with MySql but cannot figure out how to migrate or automatically create tables into a MySql database.

Is there at least a way to export the

8条回答
  •  臣服心动
    2021-02-07 12:35

    jduhls answer is beautiful, but I needed to tweak it slightly to add some static data into tables. Here's my tweaked version, along with an example of loading data into a simple SystemSettings table (id, settingName, settingValue):

    var async = require('async');
    
    var SYSTEM_SETTINGS = [
      {
        "settingName": "mustPayInAdvance",
        "settingValue": "false",
      }
    ];
    
    module.exports = function(app) {
        var path = require('path');
        var models = require(path.resolve(__dirname, '../model-config.json'));
        var datasources = require(path.resolve(__dirname, '../datasources.json'));
        var modelUpdates = [];
    
        function buildModelListForOperation(){
            Object.keys(models).forEach(function(key) {
                if (typeof models[key].dataSource != 'undefined') {
                    if (typeof datasources[models[key].dataSource] != 'undefined') {
                        modelUpdates.push({operation: app.dataSources[models[key].dataSource], key: key});
                    }
                }
            });
        }
    
        function createStaticData() {
            app.models.SystemSettings.create(SYSTEM_SETTINGS, function(err, created) {
                if (err) 
                    throw err;
                else
                    console.log('Sample data was imported.');
            });
        }
    
        function processModelsAndData(operationType) {
            buildModelListForOperation();
    
            // Create all models
            async.each(modelUpdates, function(item, callback) {
                item.operation[operationType](item.key, function (err) {
                    if (err) throw err;
                    console.log('Model ' + item.key + ' migrated');
                    callback();
                });
            }, function (err) {
                if (err) throw err;
                createStaticData();
            });    
        }
    
        //TODO: change to 'autoupdate' when ready for CI deployment to production
        processModelsAndData('automigrate');
    };
    

提交回复
热议问题