Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benomatis/dd78b482d2b089b06d6f523ec98f9b62 to your computer and use it in GitHub Desktop.
Save benomatis/dd78b482d2b089b06d6f523ec98f9b62 to your computer and use it in GitHub Desktop.
Automatically generate loopback models from existing MySQL schema (all at once)

Prerequisites

When using this script I'm assuming the following things are true:

  1. You have a working LoopBack application created.
  2. You have loopback-connector-mysql installed.
  3. You have a datasources.json file created inside the LoopBack application root folder server and have set up connection to your MySQL database. Basic example:
    "mydb": {
      "name": "mydb",
      "connector": "mysql",
      "host": "localhost",
      "port": 3306,
      "username": "username",
      "password": "password",
      "database": "database"
    }
  4. You have a model-config.json file created inside the LoopBack application root folder server with default content, like:
    {
      "_meta": {
        "sources": [
          "loopback/common/models",
          "loopback/server/models",
          "../common/models",
          "./models"
        ],
        "mixins": [
          "loopback/common/mixins",
          "loopback/server/mixins",
          "../common/mixins",
          "./mixins"
        ]
      }
    }

Usage

  1. Put the file in the folders server/bin inside your LoopBack application root folder.
  2. Run the script in the command line as node server/bin/script (omitting the .js extension name, but you can use it with it too, if you like).
  3. Enjoy (hopefully) / provide feedback!

Credits (based on)

https://stackoverflow.com/a/30179478/2037924 https://gist.github.com/serkanserttop/64fc2d4465fb154066db#file-discover-js

var fs = require('fs');
var path = require('path');
var app = require(path.resolve(__dirname, '../server'));
var appDir = './';
var baseFileName = 'model-config.json';
var fileName = path.resolve(__dirname, '../' + baseFileName);
var file = require(fileName);
var dataSource = app.dataSources.mydb;
var db = dataSource.settings.database;
function capitaliseFirstLetter(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
function jsFileString(model_name){
return '' +
'module.exports = function(' + capitaliseFirstLetter(model_name) + ') {\n' +
'\t\n' +
'};';
}
dataSource.discoverModelDefinitions({schema:db}, function (err, models) {
models.forEach(function (model) {
dataSource.discoverSchema(model.name, {associations: true}, function (err, schema) {
if( schema.options.mysql.schema !== db ){
console.log('options.mysql.schema !== db', schema);
}
fs.writeFile( appDir + 'common/models/' + model.name + '.json', JSON.stringify(schema, null, ' '), function (err) {
if (err) throw err;
console.log('Created ' + model.name + '.json file');
});
fs.writeFile( appDir + 'common/models/' + model.name + '.js', jsFileString(model.name), function (err) {
if (err) throw err;
console.log('Created ' + model.name + '.js file');
});
file[schema.name] = {
"dataSource": dataSource.settings.name,
"public": false
};
fs.writeFile(fileName, JSON.stringify(file, null, 2), function (err) {
if (err) throw err;
console.log('Updated ' + baseFileName + ' with an entry of ' + model.name);
});
});
});
});
@jonathanlyon
Copy link

This is just what I need - if only I can get it to work ;-) I'm getting this error:-

C:\dev\api> node server/bin/script
C:\dev\api\node_modules\mysql\lib\protocol\Parser.js:79
throw err; // Rethrow non-MySQL errors
^

TypeError: Cannot read property 'options' of undefined
at C:\dev\api\server\bin\script.js:26:17
at C:\dev\api\node_modules\loopback-datasource-juggler\lib\datasource.js:1412:13
at C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:359:16
at iteratorCallback (C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:933:13)
at C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:843:16
at C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:3691:13
at apply (C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:21:25)
at C:\dev\api\node_modules\loopback-datasource-juggler\node_modules\async\dist\async.js:56:12
at callback (C:\dev\api\node_modules\loopback-connector\lib\sql.js:1896:7)
at cbForWork (C:\dev\api\node_modules\loopback-datasource-juggler\lib\observer.js:234:34)
at C:\dev\api\node_modules\loopback-connector\lib\sql.js:642:7
at handleResponse (C:\dev\api\node_modules\loopback-connector-mysql\lib\mysql.js:193:17)
at Query._callback (C:\dev\api\node_modules\loopback-connector-mysql\lib\mysql.js:204:7)
at Query.Sequence.end (C:\dev\api\node_modules\mysql\lib\protocol\sequences\Sequence.js:86:24)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment