Loopback也创建了一个构建json模型的数据库结构

时间:2015-03-13 01:37:13

标签: json node.js postgresql loopbackjs strongloop

我有一个大型数据库的书面规范,该数据库将托管在postgresql中,并用作backloop nodejs api实现的数据源。 问题是规范是由机器直接编写的,所以我必须自己创建模型和结构。 我最近才开始使用loopback,之前我主要使用django。从我看到我认为适合我的方法是dataSource.createModel但该方法不会在json文件夹中创建common/model文件,因此它不会真正适用于api。< / p>

有没有办法在数据库和api注册表中构建模型? 到目前为止这是我的代码:(

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我的模型将有这样的外键和关系

{
  "name": "Order",
  "base": "PersistedModel",
  "properties": {
    "description": {
      "type": "string"
    },
    "total": {
      "type": "number"
    }
  },
  "validations": [],
  "relations": {
    "customer": {
      "type": "belongsTo",
      "model": "Customer",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": []
}

1 个答案:

答案 0 :(得分:0)

我制作了一个脚本,可以从数据库创建模型,并自动在common / models中创建.json文件。该脚本还在Explorer API中公开API。希望这就是你所需要的。要点也可用here

请注意您应该与项目匹配的TODO评论

/**
 * 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, '  ');
}