Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. var loopback = require('loopback');
  4. var boot = require('loopback-boot');
  5.  
  6. var app = module.exports = loopback();
  7.  
  8. var initialization = function() {
  9.   var fs = require('fs');
  10.   var path = require('path');
  11.   var outputPath = path.resolve(__dirname, '../common/models');
  12.   var configPath = path.resolve(__dirname, '../server');
  13.  
  14.   var datasource = app.dataSources.wordpress;  
  15.  
  16.   var modelsFile = new Promise((resolve, reject) => fs.readFile('server/model-config.json', function(error, content) {
  17.       if (error) console.log(error); else {
  18.         var jsonModels = JSON.parse(content);
  19.         resolve(jsonModels);
  20.       }
  21.     })
  22.   );
  23.  
  24.   datasource.discoverModelDefinitions({schema: 'tailor', views: false, all: true}, function(error, models) {
  25.       if (error) console.log(error); else {
  26.         var promises = [];
  27.         for (var index in models) {
  28.           promises.push(new Promise((resolve, reject) => datasource.discoverAndBuildModels(models[index].name, {associations: true, nameMapper: (type, name) => name}, function(innerError, definition) {
  29.               if (innerError) reject(innerError); else {
  30.                   var name = Object.keys(definition)[0];                  
  31.                   definition[name].setup();
  32.                   fs.writeFile(outputPath + '/' + name + '.json', JSON.stringify(definition[name].definition), function(fileError) {
  33.                     if (fileError)
  34.                       reject(fileError); // This is a callback hell! You may also use promises.
  35.                     else {
  36.                       resolve(name);
  37.                     }
  38.                   });
  39.               }
  40.             })
  41.           ));
  42.         }
  43.  
  44.         modelsFile.then(content => Promise.all(promises).then(values => {
  45.           values.forEach(modelName => content[modelName] = { public: true, dataSource: "wordpress" });
  46.           fs.writeFile(configPath + '/model-config.json', JSON.stringify(content), function(fileError) {
  47.             if (fileError)
  48.               console.log(fileError);
  49.             else
  50.               console.log('Models definitions done');
  51.  
  52.               process.exit();
  53.           });
  54.         }));
  55.       }
  56.     }
  57.   );
  58. };
  59.  
  60. // Bootstrap the application, configure models, datasources and middleware.
  61. // Sub-apps like REST API are mounted via boot scripts.
  62. boot(app, __dirname, function(err) {
  63.   if (err) throw err;
  64.  
  65.   initialization();
  66. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement