Search code examples
node.jsloopback

Loopback get model from datasource with discoverSchemas


I've been testing loopback for couple hours now and everyhing is working fine when i'm creating models manually and modify the model.json created to match my oracleDb columns name.

But i'm getting stuck when i want to get a model from my oracle db to avoid to write the 50 columns manually.. I made a test with a table called "atest" and contains a column "name" and "id". It's create the atest.json , and add this in model-config.json:

"Atest": { "dataSource": "oracledb", "public": true }

But in my atest.json there is just a "undefined"..

My discover-models.js file :

'use strict';

const loopback = require('loopback');
const promisify = require('util').promisify;
const fs = require('fs');
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);
const mkdirp = promisify(require('mkdirp'));

const DATASOURCE_NAME = 'oracledb';
const dataSourceConfig = require('./server/datasources.json');
const db = new loopback.DataSource(dataSourceConfig[DATASOURCE_NAME]);

discover().then(
  success => process.exit(),
  error => { console.error('UNHANDLED ERROR:\n', error); process.exit(1); },
);

async function discover() {
  // It's important to pass the same "options" object to all calls
  // of dataSource.discoverSchemas(), it allows the method to cache
  // discovered related models
  const options = { relations: false };

  // Discover models and relations
  const atestSchemas = await db.discoverSchemas('ATEST', options);

  // Create model definition files
  await mkdirp('common/models');
  var response = await writeFile(
    'common/models/atest.json',
    JSON.stringify(atestSchemas['ATEST'], null, 2)
  );
  console.log(response);
  // Expose models via REST API
  const configJson = await readFile('server/model-config.json', 'utf-8');
  console.log('MODEL CONFIG', configJson);
  const config = JSON.parse(configJson);
  config.Atest = { dataSource: DATASOURCE_NAME, public: true };

  await writeFile(
    'server/model-config.json',
    JSON.stringify(config, null, 2)
  );
}

My oracle connection is working fine, i don't get it, any idea?


Solution

  • Add a console.log after you invoke discoverSchemas:

    // Discover models and relations
    const atestSchemas = await db.discoverSchemas('ATEST', options);
    console.log(atestSchemas);
    

    You should see that the key is not just 'ATEST', as referenced later with atestSchemas['ATEST']. The key is 'SCHEMA_NAME.ATEST' (SCHEMA_NAME will vary as per your environment).

    If you target the appropriate key, you should get what you're looking for.