Loopback discoverAndBuildModels not generating models

后端 未结 4 1341
鱼传尺愫
鱼传尺愫 2021-02-05 23:29

I\'m trying to get Loopback to discover and build my first table. I\'ve used the simple example on their page at the bottom here:

http://docs.strongloop.com/display/LB/D

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 23:47

    Building off of @Underskay's answer, I did something like

    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));
    

提交回复
热议问题