Alexander Mills
Alexander Mills

Reputation: 100220

Auto-generate swagger docs if you only use auto-discovery to discover DB tables

I am wondering if we can still auto-generate Swagger API documentation for our Loopback API server if we only use the auto-discovery features outlined here:

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

does anyone know if it's possible? If we use autodiscovery, I somehow doubt that any .json files for our models will get written to our server project, and that will make generating docs difficult.

Upvotes: 0

Views: 286

Answers (1)

Alexander Mills
Alexander Mills

Reputation: 100220

Turns out yes it is possible, and the way to do that is to write the models-x.json files out for all models with a script, and then start the server after the script has finished!

https://docs.strongloop.com/display/public/LB/Database+discovery+API

this is standard practice for auto-discovery, here is my code that accomplishes this:

const loopback = require('loopback');
const fs = require('fs');
const path = require('path');
const async = require('async');

var ds = loopback.createDataSource('postgresql', {
  'host': 'localhost',
  'port': 5432,
  'database': 'foo',
  'username': 'bar',
  'password': 'baz'
});


ds.discoverModelDefinitions(function (err, models) {

  async.each(models, function (def, cb) {

    ds.discoverSchema(def.name, null, function (err, schema) {
      if (err) {
        console.error(err.stack || err);
        cb(err);
      }
      else {
        fs.writeFile(path.resolve(__dirname, 'server/models', def.name + '.json'),
          JSON.stringify(schema), {}, cb);
      }
    });

  }, function (err) {
    if (err) {
      console.log(err.stack || err);
      process.exit(1);
    }
    else {
      console.log(' => Successfully wrote model data.');
      process.exit(0);
    }

  });
});

Upvotes: 1

Related Questions