|
| 1 | +var colors = require('colours'), |
| 2 | + glob = require('glob'), |
| 3 | + path = require('path'), |
| 4 | + util = require('util'), |
| 5 | + lodash = require('lodash-node'), |
| 6 | + fs = require('fs'), |
| 7 | + errors = { |
| 8 | + 'NOT_ABE': 'This file isn\'t valid ABE JSON format' |
| 9 | + }, |
| 10 | + opt = { |
| 11 | + 'verbose': false, |
| 12 | + 'location': './', |
| 13 | + 'build': 'tmp/' |
| 14 | + }; |
| 15 | + |
| 16 | +exports.jsonBuilder = function (options) { |
| 17 | + lodash.merge(opt, options); |
| 18 | + |
| 19 | + glob |
| 20 | + .sync(opt.location + '.json', { |
| 21 | + mark: true |
| 22 | + }) |
| 23 | + .forEach(function (match) { |
| 24 | + var json = require(process.cwd() + '/' + match); |
| 25 | + |
| 26 | + // Check that the JSON passed to the function has examples / matches |
| 27 | + // ABE Spec |
| 28 | + if (!lodash.has(json, 'examples')) { |
| 29 | + return errors.NOT_ABE; |
| 30 | + } |
| 31 | + |
| 32 | + var folderArr = path.dirname(match).split('/'), |
| 33 | + filePath = process.cwd() + '/' + opt.build, |
| 34 | + buildName = folderArr[folderArr.length - 1] + '-', |
| 35 | + baseName = path.basename(match, '.json'); |
| 36 | + |
| 37 | + if (!fs.existsSync(filePath)) { |
| 38 | + fs.mkdir(filePath, function (err) { |
| 39 | + if (err) { |
| 40 | + console.log(err.red); |
| 41 | + } else if (opt.verbose) { |
| 42 | + console.log(opt.build.yellow, ' created.'); |
| 43 | + } |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + // Loop through each example within the JSON to create it's own |
| 48 | + // JSON file |
| 49 | + lodash.forEach(json.examples, function (obj, key) { |
| 50 | + var bodyData = json.examples[key].response.body, |
| 51 | + fileData = JSON.stringify(bodyData, null, 4), |
| 52 | + file = buildName + baseName + '-' + key + '.json'; |
| 53 | + |
| 54 | + fs.writeFile(filePath + file, fileData, function (err) { |
| 55 | + if (err) { |
| 56 | + console.log(err.red); |
| 57 | + } else if (opt.verbose) { |
| 58 | + console.log(file.green, ' file was saved.'); |
| 59 | + } |
| 60 | + }); |
| 61 | + }); |
| 62 | + |
| 63 | + }); |
| 64 | +}; |
0 commit comments