简体   繁体   English

Loopback discoverAndBuildModels不生成模型

[英]Loopback discoverAndBuildModels not generating models

I'm trying to get Loopback to discover and build my first table. 我正在尝试让Loopback发现并构建我的第一个表。 I've used the simple example on their page at the bottom here: 我在他们的页面底部使用了这个简单的例子:

http://docs.strongloop.com/display/LB/Database+discovery+API#DatabasediscoveryAPI-Exampleofbuildingmodelsviadiscovery http://docs.strongloop.com/display/LB/Database+discovery+API#DatabasediscoveryAPI-Exampleofbuildingmodelsviadiscovery

and I see the output of the table I'm discovering, but the API Explorer doesn't show the table or any newly generated endpoints. 我看到我正在发现的表的输出,但API Explorer不显示表或任何新生成的端点。 Also, the model-config.js file is not updated with the new table object. 此外,不使用新表对象更新model-config.js文件。 Here is the basic section of the code done on server start: 以下是在服务器启动时完成的代码的基本部分:

var loopback = require('loopback');
var boot = require('loopback-boot');
var DataSource = require('loopback-datasource-juggler').DataSource;
var mysqlSource = require('./datasources.json');
var dataSource = new DataSource('mssql', mysqlSource.mysqlserver);

var app = module.exports = loopback();

// Set up the /favicon.ico
app.use(loopback.favicon());

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

dataSource.discoverAndBuildModels('CATS', {owner: 'mamacat'}, function (err, models) {
    models.Cat.find(function (err, cat) {
        if (err) {
            console.error(err);
        } else {
            console.log(cat);
        }
        dataSource.disconnect();
    });
});

// boot scripts mount components like REST API
boot(app, __dirname);

To summarize, this runs, no errors. 总而言之,这样运行,没有错误。 But no new models show on http://localhost:3000/explorer 但是在http://localhost:3000/explorer上没有显示新模型

Seems that discovery scripts only shows the output and doesn't create the model files. 似乎发现脚本仅显示输出并且不创建模型文件。 I found some instructions on loopback docs: 我在loopback docs上找到了一些说明:

http://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases http://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases

In section Basic Procedure , the second step: 基本程序一节中,第二步:

2. Use fs.writeFile() to save the output in common/models/model-name.json. 2.使用fs.writeFile()将输出保存在common / models / model-name.json中。

So you can try the following approach: 所以你可以尝试以下方法:

  1. Setup your mysql data in yourloopbackproject/server/datasources.json file: yourloopbackproject / server / datasources.json文件中设置mysql数据:
{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "accountDs": {
    "host": "mysqlServerName",
    "port": 3306,
    "database": "databaseName",
    "username": "username",
    "password": "password!",
    "name": "accountDs",
    "connector": "mysql"
  }
}
  1. Create the models folder if doesn't exist: yourloopbackproject/common/models . 如果不存在,则创建models文件夹: yourloopbackproject / common / models

  2. Create discovery-and-build.js script on yourloopbackproject/server/bin folder: yourloopbackproject / server / bin文件夹上创建discovery-and-build.js脚本:

var path = require('path');
var fs = require('fs');
var app = require(path.resolve(__dirname, '../server'));
var outputPath = path.resolve(__dirname, '../../common/models');

var dataSource = app.dataSources.accountDs;

function schemaCB(err, schema) {
  if(schema) {
    console.log("Auto discovery success: " + schema.name);
    var outputName = outputPath + '/' +schema.name + '.json';
    fs.writeFile(outputName, JSON.stringify(schema, null, 2), function(err) {
      if(err) {
        console.log(err);
      } else {
        console.log("JSON saved to " + outputName);
      }
    });
  }
  if(err) {
    console.error(err);
    return;
  }
  return;
};

dataSource.discoverSchema('tableName',{schema:'schemaName'},schemaCB);

This script is based on: http://www.reddit.com/r/strongloop/comments/2upy76/autodiscoveryjs_recipe/ 此脚本基于: http//www.reddit.com/r/strongloop/comments/2upy76/autodiscoveryjs_recipe/

  1. After the script execution you will find a .json file on models folder. 脚本执行后,您将在models文件夹中找到.json文件。 Go to step 3 on Basic Procedure section: http://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases 转到基本过程部分的步骤3: http//docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases

  2. Follow these steps to expose your model over REST: http://docs.strongloop.com/display/public/LB/Exposing+models+over+REST 按照以下步骤通过REST公开您的模型: http//docs.strongloop.com/display/public/LB/Exposing+models+over+REST

I hope this helps! 我希望这有帮助!

Use Arc for this. 为此使用Arc。 Run slc arc from the project folder and it will show up the gui tool called arc in default browser. 从项目文件夹运行slc arc,它将在默认浏览器中显示名为arc的gui工具。 If you've not already registered, sign up and log in. You will be directed to GUI tool of StrongLoop, the Arc. 如果您尚未注册,请注册并登录。您将被引导至StrongLoop的GUI工具,即Arc。 Select your model from list on the left pane. 从左侧窗格的列表中选择您的模型。 You'll be able to see save and migrate button. 您将能够看到保存和迁移按钮。 Just click the migrate button and your table will be created into model.(within millisecs!) 只需单击“迁移”按钮,您的表就会被创建到模型中。(在毫秒内!)

Cheers! 干杯!

discovery api is used to only discover the schema not to create models for now. discovery api用于仅发现架构而不是为了现在创建模型。 please use the following project to create models with one to one and one to many relationships and all the models. 请使用以下项目创建具有一对一和一对多关系以及所有模型的模型。

https://github.com/savsharma2/loopback-sql-create-model-with-relation/ https://github.com/savsharma2/loopback-sql-create-model-with-relation/

Building off of @Underskay's answer , I did something like 建立@Underskay的回答 ,我做了类似的事情

var fs = require('fs');
var app = require(__dirname + '/server/server');

function makePromise(f, parent) {
    return function(...args) {
        return new Promise((resolve, reject) => {
            f.call(parent, ...args, (err, ...data) => {
                if (err) return reject(err);
                resolve(data.length === 1 ? data[0] : data);
            });
        });
    };
}

var readFile = makePromise(fs.readFile, fs);
var writeFile = makePromise(fs.writeFile, fs);

function writeSchemas(schemas) {
    return Promise.all(schemas.map(data => {
        var schema = data[Object.keys(data)[0]];
        return writeFile('common/models/' + schema.name + '.json', JSON.stringify(schema, null, '\t'));
    }))
        .then(() => readFile('server/model-config.json'))
        .then(JSON.parse)
        .then(conf => {
            for (let schema of schemas)
                conf[schema[Object.keys(schema)[0]].name] = { "dataSource": "mysql" };
            return conf;
        })
        .then(conf => writeFile('server/model-config.json', JSON.stringify(conf, null, '\t')));
}

function getSchemas(ds) {
    var discoverSchemas = makePromise(ds.discoverSchemas, ds);
    return makePromise(ds.discoverModelDefinitions, ds)({})
        .then(tables => Promise.all(tables.map(t => discoverSchemas(t.name, { relations: true }))))
        .then(data => { ds.disconnect(); return data; });
}

Promise.resolve(app.datasources.mysql)
    .then(ds => getSchemas(ds))
    .then(schemas => writeSchemas(schemas))
    .catch(err => log.error(err));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM