1

I have a written specification for a sizable database that will be hosted in postgresql and used as a datasource for a backloop nodejs api implementation. The problem is the specification is written in no way parsable by a machine directly so i will have to create the models and the structure myself. I have only recently started working with loopback and i have mostly used django before. From what i saw i think the method that fits me is dataSource.createModel but that method does not create the json files in the common/model folder so its not really going to work for the api.

Is there a way to build the models both in the database and the api registry? this is my code so far :(

var path = require('path');
var app = require(path.resolve(__dirname, '../server'));
// var ds = require('../data-sources/db')('oracle');
var ds = app.dataSources.floatDB;
var User = ds.createModel('User', {
    email: { type: String, limit: 150, index: true },
    password: { type: String, limit: 50 },
    birthDate: Date,
    registrationDate: {type: Date, default: function () { return new Date }},
    activated: { type: Boolean, default: false }
});

ds.automigrate(function () {
  ds.discoverModelProperties('CUSTOMER_TEST', function (err, props) {
    console.log(props);
  });
});

PS my models will have foreign keys and relationships like this

{
  "name": "Order",
  "base": "PersistedModel",
  "properties": {
    "description": {
      "type": "string"
    },
    "total": {
      "type": "number"
    }
  },
  "validations": [],
  "relations": {
    "customer": {
      "type": "belongsTo",
      "model": "Customer",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": []
}
Evan
  • 1,683
  • 7
  • 35
  • 65
  • Can you make this question any clearer? Have you already created a schema in your database and want code to generate your API endpoints? Or are you creating your models in code, and want the JSON models and the Database schema to both be created? – conradj May 18 '15 at 09:48

1 Answers1

0

I've made a script that creates the models from the database and automatically creates the .json files in common/models. The script also exposes the API in Explorer API. Hope that's what you need. The gist is also available here

Be aware of the TODO's comments where you should match with your project

/**
 * loopback-discover-database.js
 *
 * Put this file in the root directory for your project and it should work.
 * run: node loopback-discover-database.js
 */
var fs = require('fs');
var loopback = require('loopback');

var commonFolder = './common';
var modelsFolder = commonFolder+'/models';

//TODO: Change to the correct path for your server folder if needed
var serverPath = './server/';
var modelConfig = require(serverPath + 'model-config');
var dataSources = require(serverPath + 'datasources');

//TODO: dataSourceName should be the name of your datasource in server/datasources.json 
var dataSourceName = 'dbname';

var ds = loopback.createDataSource('postgresql', dataSources[dataSourceName]);

initMain();

function initMain(){
  // Check if common/models exists
  // If not, create them and build models from database
  if (!fs.existsSync(commonFolder)){
      fs.mkdirSync(commonFolder);
  }
  if (!fs.existsSync(modelsFolder)){
      fs.mkdirSync(modelsFolder);
  }

  discoverAndCreate();
}

function discoverAndCreate(callback){
  //Will print the schema of the database
  ds.discoverModelDefinitions(function (err, models) {
    models.forEach(function (def, index, array) {
      // def.name ~ the model name
      ds.discoverSchema(def.name, null, function (err, schema) {
        schema.name = schema.name.toLowerCase();
        fs.writeFile('common/models/'+def.name+'.json', prettyJSON(schema), function(err){
          if (err) throw err;
          console.log('It\'s saved!');
          //If last, then save
          if(index === array.length - 1){
            saveAndExposeSchemas();
          }
        });
        addSchema(schema.name);
      });
    });
  });
}

function addSchema(schema){
  modelConfig[schema] = {
    dataSource: dataSourceName,
    public: true,
    $promise: {},
    $resolved: true
  };
}

function saveAndExposeSchemas(){
  fs.writeFile('server/model-config.json', prettyJSON(modelConfig), function(err){
    if (err) throw err;
    console.log('Schemas are exposed!');
  });
}

function prettyJSON(str){
  return JSON.stringify(str, null, '  ');
}
Edudjr
  • 1,676
  • 18
  • 28