index.js

  1. // Copyright 2018 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. 'use strict';
  15. var proc = require('./lib/process.js')
  16. var compile = require('./lib/compile.js')
  17. var sway = require('sway')
  18. var fs = require('fs')
  19. var join = require('path').join
  20. var merge2 = require('./lib/util').merge2
  21. module.exports = {
  22. generate: generate
  23. }
  24. /**
  25. * GenerationResults is the final result of the generation function
  26. * @typedef {object} GenerationResults
  27. * @property {compilation.GeneratedTest[]} generated set of generated test objects
  28. */
  29. /**
  30. * Generates test artifacts based on the given API Spec and options
  31. * @function generate
  32. * @instance
  33. * @param {string} specPath path to the API spec document
  34. * @param {object} options options to apply during processing of API spec
  35. * @return {Promise<GenerationResults>}
  36. */
  37. function generate(specPath, options) {
  38. return sway.create({
  39. 'definition': specPath,
  40. 'jsonRefs': options && options.jsonRefs,
  41. 'customFormats': options && options.customFormats,
  42. 'customFormatGenerators': options && options.customFormatGenerators,
  43. 'customValidators': options && options.customValidators
  44. })
  45. .then(function (api) {
  46. if (options.customValues) {
  47. options.customValues = JSON.parse(options.customValues);
  48. }
  49. if (options.customValuesFile) {
  50. var customFromFile = require(
  51. join(process.cwd(), options.customValuesFile))
  52. options.customValues = merge2(options.customValues, customFromFile)
  53. }
  54. var processed = proc(api, options)
  55. var compiled = compile(processed, options)
  56. if (options.writeTo !== undefined) {
  57. if (!fs.existsSync(options.writeTo)) {
  58. fs.mkdirSync(options.writeTo)
  59. }
  60. try {
  61. for (var i = 0; i < compiled.length; i++) {
  62. const testObj = compiled[i];
  63. fs.writeFileSync(join(options.writeTo, testObj.filename), testObj.contents)
  64. }
  65. } catch (err) {
  66. console.log(err);
  67. }
  68. }
  69. return {'generated': compiled}
  70. }, function (err) {
  71. console.error(err.stack);
  72. return err
  73. });
  74. }