How to use outputPath method in argos

Best JavaScript code snippet using argos

codeGenerator.module.js

Source:codeGenerator.module.js Github

copy

Full Screen

1'use strict'2/**3 * The codeGenerator module. Contains the CodeGenerator class.4 * @module codeGeneratorModule5 */67const8 co = require('co'),9 fs = require('fs-extra'),10 glob = require('glob'),11 handlebars = require('handlebars'),12 jsdoc2md = require('jsdoc-to-markdown'),13 path = require('path'),14 pug = require('pug'),15 spec = require('./codeGenerator.module.spec')1617/**18 * The CodeGenerator class. Contains various methods for building and generating a wide variety of code files for a new or an existing project.19 * @class CodeGenerator20 */21class CodeGenerator {22 /**23 * Creates an instance of CodeGenerator. Sets test methods (defined in the accompanying .spec.js file) and adds the provided config param as a method property (if provided).24 * @param {object} config (optional) The full project config.25 * @see module:configModule26 * @memberof CodeGenerator27 */28 constructor(config) {29 for (const testName in spec) {30 this[testName] = spec[testName]31 }32 if (config) {33 /**34 * The full project config.35 * @type {object}36 * @see module:configModule37 */38 this.config = config39 }40 /**41 * An array containing class method names for which a project config is required to execute sucessfuly.42 * @type {string[]}43 */44 this.configRequiredForMethods = ['buildLayoutFile', 'generateNGINXConfig']45 /**46 * A map of PostgreSQL data types to typescript data types.47 * @type {Object.<string, string>}48 */49 this.pgToTSMap = {50 bigint: 'number',51 int8: 'number',52 bigserial: 'number',53 serial8: 'number',54 bit: 'string',55 varbit: 'string',56 boolean: 'boolean',57 bool: 'boolean',58 box: 'object',59 bytea: 'object',60 character: 'string',61 char: 'string',62 'character varying': 'string',63 varchar: 'string',64 cidr: 'object',65 cirle: 'object',66 date: 'string',67 'double precision': 'number',68 'float8': 'number',69 inet: 'string',70 integer: 'number',71 int: 'number',72 int4: 'number',73 interval: 'string',74 json: 'string',75 jsonb: 'object',76 line: 'object',77 lseg: 'object',78 macaddr: 'string',79 money: 'number',80 numeric: 'number',81 decimal: 'number',82 path: 'object',83 pg_lsn: 'number',84 point: 'object',85 polygon: 'object',86 real: 'number',87 float8: 'number',88 smallint: 'number',89 int2: 'number',90 smallserial: 'number',91 serial2: 'number',92 serial: 'number',93 serial4: 'number',94 text: 'string',95 time: 'string',96 timetz: 'string',97 timestamp: 'string',98 timestamptz: 'string',99 tsquery: 'string',100 tsvector: 'string',101 txid_snapshot: 'string',102 uuid: 'string',103 xml: 'string',104 'user-defined': 'string'105 }106 }107108 /**109 * Builds the layout.html file for a given client module out of it's layout_<configProfileName>.pug file.110 * @param {string} clientModuleName The name of the client module to build the layout file for.111 * @returns {Promise<boolean>} A promise which wraps a generator function.112 * @memberof CodeGenerator113 */114 buildLayoutFile(clientModuleName) {115 const instance = this,116 {config} = this117 return co(function*() {118 if ((typeof clientModuleName !== 'string') || !clientModuleName.length) {119 throw {customMessage: 'The clientModuleName argument must be a non-empty string.'}120 }121 instance.checkConfig(config, {clientModuleName})122 const moduleConfig = config.clients[clientModuleName]123 let publicSourcesPath = path.join(config.clientModulesPublicSourcesPath, clientModuleName),124 publicPath = path.join(config.clientModulesPublicPath, clientModuleName),125 profileLayoutFilePath = path.join(publicSourcesPath, 'layout_' + config.name + '.pug'),126 dirStats = yield fs.lstat(publicSourcesPath)127 if (!dirStats.isDirectory()) {128 throw {customMessage: 'The client module public sources path exists, but is not a directory.'}129 }130 dirStats = yield fs.lstat(publicPath)131 if (!dirStats.isDirectory()) {132 throw {customMessage: 'The client module public path exists, but is not a directory.'}133 }134 let layoutData = (pug.compileFile(profileLayoutFilePath, {}))(),135 layoutFilePath = path.join(publicPath, 'layout.html'),136 layoutFile = yield fs.open(layoutFilePath, 'w')137 yield fs.writeFile(layoutFile, layoutData)138 yield fs.close(layoutFile)139 return true140 })141 }142143 /**144 * Checks if a given config exists, and (optonally) check for the existence of a clent/api module with a given name within that config.145 * @param {object} config The full project config.146 * @see module:configModule147 * @param {object} options (optional) The client/api module names to check for.148 * @param {string} options.clientModuleName (optional) The name of the client module to check for - an error will be thrown if config.clients[clientModuleName] is undefined.149 * @param {string} options.apiModuleName (optional) The name of the api module to check for - an error will be thrown if config.apis[apiModuleName] is undefined.150 * @returns {boolean} The method returns true if the checks were successful, otherwise appropriate errors are thrown.151 * @memberof CodeGenerator152 */153 checkConfig(config, options) {154 if (!config) {155 throw {customMessage: 'No valid config property exists for this class. Please provide the config object on class instance creation, or at a later point by accessing the config property.'}156 }157 if (options) {158 const {clientModuleName, apiModuleName} = options159 if (clientModuleName && !config.clients[clientModuleName]) {160 throw {customMessage: 'No client module config exists in the provided config for the provided client module name.'}161 }162 if (apiModuleName && !config.apis[apiModuleName]) {163 throw {customMessage: 'No api module config exists in the provided config for the provided api module name.'}164 }165 }166 return true167 }168169 /**170 * Check if a given outputPath exists, and if it's a directory. Throws errors if it's not.171 * @param {string} outputPath The path to check.172 * @returns {Promise<boolean>} A promise which wraps a generator function. The promise resolution equals true if the checks were successful, otherwise appropriate errors are thrown.173 * @memberof CodeGenerator174 */175 checkOutputPath(outputPath) {176 return co(function*() {177 try {178 let dirStats = yield fs.lstat(outputPath)179 if (!dirStats.isDirectory()) {180 throw {customMessage: 'The provided outputPath path exists, but is not a directory.'}181 }182 } catch (e) {183 if (!e || (e.customMessage !== 'The provided output path exists, but is not a directory.')) {184 yield fs.mkdirp(outputPath)185 } else {186 throw e187 }188 }189 return true190 })191 }192193 /**194 * Generates a project config file from a template file.195 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.196 * @param {string} outputFileName The name of the generated file 197 * @param {string} templateFilePath The path to put the config template file. An error will be thrown if no file exists at it.198 * @returns {Promise<boolean>} A promise which wraps a generator function.199 * @memberof CodeGenerator200 */201 generateConfigFile(outputPath, outputFileName, templateFilePath) {202 const instance = this203 return co(function*() {204 let configTemplate = yield fs.readFile(templateFilePath)205 yield instance.checkOutputPath(outputPath)206 let fd = yield fs.open(path.join(outputPath, outputFileName), 'w')207 yield fs.writeFile(fd, configTemplate)208 yield fs.close(fd)209 return true210 })211 }212213 /**214 * Generates a project config file based on the "config/index.js" template. The purpose of this file is to merge the common config with the current profile config.215 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.216 * @returns {Promise<boolean>} A promise which wraps a generator function.217 * @memberof CodeGenerator218 */219 generateIndexConfigFile(outputPath) {220 return this.generateConfigFile(outputPath, 'index.js', path.join(__dirname, './templates/config/index.js'))221 }222223 /**224 * Generates a project config file based on the "config/common.js" template. The purpose of this file is to contain configuration options for the project, which are shared across all config profiles (i.e. are common for the project).225 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.226 * @returns {Promise<boolean>} A promise which wraps a generator function.227 * @memberof CodeGenerator228 */229 generateCommonConfigFile(outputPath) {230 return this.generateConfigFile(outputPath, 'common.js', path.join(__dirname, './templates/config/common.js'))231 }232233 /**234 * Generates a project config file based on the "config/profiles/<profileName>.js" template. The purpose of this file is to contain profile-specific configuration options. If some of them match the keys of certain configuration options from the common config file, the ones in the common config file will be overwritten.235 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.236 * @param {string} profileName The name of the config profile, whose template is to be used. An error will be thrown if it does not exist.237 * @returns {Promise<boolean>} A promise which wraps a generator function.238 * @memberof CodeGenerator239 */240 generateProfileConfigFile(outputPath, profileName) {241 if ((typeof profileName !== 'string') || !profileName.length) {242 throw {customMessage: 'The profileName argument must be a non-empty string.'}243 }244 return this.generateConfigFile(path.join(outputPath, './profiles'), `${profileName}.js`, path.join(__dirname, `./templates/config/profiles/${profileName}.js`))245 }246247 /**248 * Generates an NGINX config file based on the "config/nginx/images.conf" template. The purpose of this file is to set up the serving of static image assets and image-not-found placeholders.249 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.250 * @returns {Promise<boolean>} A promise which wraps a generator function.251 * @memberof CodeGenerator252 */253 generateImagesRedirectNGINXConfig(outputPath) {254 const instance = this255 return co(function*() {256 if ((typeof outputPath !== 'string') || !outputPath.length) {257 throw {customMessage: 'The outputPath argument must be a non-empty string.'}258 }259 let outputFilePath = path.join(outputPath, './images.conf')260 yield instance.checkOutputPath(outputPath)261 let outputFile = yield fs.open(outputFilePath, 'w')262 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, './templates/config/nginx/images.conf')))263 yield fs.close(outputFile)264 return true265 })266 }267268 /**269 * Generates the main NGINX config file based on the configuration variables in the project's config, as well as the ones in the specified clientModule's config. This file is meant to be used directly, or with minor adjustments, as the full NGINX config for your client server.270 * @param {string} clientModuleName The name of the client module whose config will be used.271 * @returns {Promise<boolean>} A promise which wraps a generator function.272 * @memberof CodeGenerator273 */274 generateNGINXConfig(clientModuleName) {275 const instance = this,276 {config} = this277 return co(function*() {278 if ((typeof clientModuleName !== 'string') || !clientModuleName.length) {279 throw {customMessage: 'The clientModuleName argument must be a non-empty string.'}280 }281 instance.checkConfig(config, {clientModuleName})282 const moduleConfig = config.clients[clientModuleName], {283 serverPort,284 nodeProxyProtocol,285 nodeProxyHostAddress,286 nodeProxyServerPort,287 prependWSServerConfigFromFiles,288 appendWSServerConfigFromFiles,289 webpackHost,290 webpackBuildFolderName291 } = moduleConfig,292 {projectName, clientModulesPublicPath, wsPort, wsConfigFolderPath, mountGlobalStorageInWebserver, globalStoragePath, addDistToStaticConfigInWebserver, hostProtocol, hostAddress} = config293 let configFilePath = path.join(wsConfigFolderPath, `${projectName}-${clientModuleName}.conf`),294 configFile = yield fs.open(configFilePath, 'w'),295 prependToServerConfig = '',296 appendToServerConfig = '',297 bundleConfig = '',298 distToStaticConfig = '',299 publicPath = path.join(clientModulesPublicPath, clientModuleName)300301 if (prependWSServerConfigFromFiles instanceof Array) {302 for (const i in prependWSServerConfigFromFiles) {303 prependToServerConfig += (yield fs.readFile(prependWSServerConfigFromFiles[i])).toString()304 }305 }306307 if (appendWSServerConfigFromFiles instanceof Array) {308 for (const i in appendWSServerConfigFromFiles) {309 appendToServerConfig += (yield fs.readFile(appendWSServerConfigFromFiles[i])).toString()310 }311 }312313 if (mountGlobalStorageInWebserver) {314 let template = handlebars.compile((yield fs.readFile(path.join(__dirname, './templates/config/nginx/global-storage.conf'))).toString())315 prependToServerConfig += template({globalStoragePath: globalStoragePath.replace(/\\/g, '\\\\')})316 }317318 if (webpackHost) {319 let template = handlebars.compile((yield fs.readFile(path.join(__dirname, './templates/config/nginx/bundle.conf'))).toString())320 bundleConfig += template({webpackHost, webpackFolder: webpackBuildFolderName || 'dist'})321 }322323 if (addDistToStaticConfigInWebserver) {324 distToStaticConfig = yield fs.readFile(path.join(__dirname, './templates/config/nginx/distToStatic.conf'))325 }326327 let template = handlebars.compile((yield fs.readFile(path.join(__dirname, './templates/config/nginx/main.conf'))).toString())328 yield fs.writeFile(configFile, template({329 listeningPort: wsPort,330 serverName: hostAddress,331 serverRoot: /^win/.test(process.platform) ? publicPath.replace(/\\/g, '\\\\') : publicPath,332 prependToServerConfig,333 appendToServerConfig,334 bundleConfig,335 distToStaticConfig,336 nodeProxyProtocol: nodeProxyProtocol || hostProtocol,337 nodeProxyHostAddress: nodeProxyHostAddress || hostAddress,338 nodeProxyServerPort: nodeProxyServerPort || serverPort339 }))340 yield fs.close(configFile)341342 return true343 })344 }345346 /**347 * Generates a webpack config file based on template in "config/webpack/<type>.js". The generated file will contain the webpack config to be used when building the project (or module) 's front-end code.348 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.349 * @param {string} type The type of the webpack config - "react", angular", etc. It must exist in "config/webpack", otherwise an error will be thrown.350 * @returns {Promise<boolean>} A promise which wraps a generator function.351 * @memberof CodeGenerator352 */353 generateWebpackConfig(outputPath, type) {354 const instance = this355 return co(function*() {356 if ((typeof outputPath !== 'string') || !outputPath.length) {357 throw {customMessage: 'The outputPath argument must be a non-empty string.'}358 }359 yield instance.checkOutputPath(outputPath)360 let configFileData = null361 try {362 configFileData = yield fs.readFile(path.join(__dirname, `templates/config/webpack/${type}.js`))363 } catch(e) {364 throw {customMessage: 'Invalid webpack config type.'}365 }366 let outputFilePath = path.join(outputPath, `${type}.js`),367 outputFile = yield fs.open(outputFilePath, 'w')368 yield fs.writeFile(outputFile, configFileData)369 yield fs.close(outputFile)370 return true371 })372 }373374 /**375 * Generates the webpackBuild and webpackDevserver build tools.376 * @param {string} outputPath The path to the folder in which the generated files will be put. Must be a valid and accessible directory.377 * @returns {Promise<boolean>} A promise which wraps a generator function.378 * @memberof CodeGenerator379 */380 generateWebpackBuildTools(outputPath) {381 const instance = this382 return co(function*() {383 if ((typeof outputPath !== 'string') || !outputPath.length) {384 throw {customMessage: 'The outputPath argument must be a non-empty string.'}385 }386 yield instance.checkOutputPath(outputPath)387 let outputFile = yield fs.open(path.join(outputPath, `webpackDevserver.js`), 'w')388 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/webpackDevserver.js`)))389 yield fs.close(outputFile)390 outputFile = yield fs.open(path.join(outputPath, `webpackBuild.js`), 'w')391 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/webpackBuild.js`)))392 yield fs.close(outputFile)393 return true394 })395 }396397 /**398 * Generates the project's main, entry-point file. It's used to start the node process and run tests.399 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.400 * @returns {Promise<boolean>} A promise which wraps a generator function.401 * @memberof CodeGenerator402 */403 generateProjectMainFile(outputPath) {404 const instance = this405 return co(function*() {406 if ((typeof outputPath !== 'string') || !outputPath.length) {407 throw {customMessage: 'The outputPath argument must be a non-empty string.'}408 }409 yield instance.checkOutputPath(outputPath)410 let outputFile = yield fs.open(path.join(outputPath, `index.js`), 'w')411 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/projectMainFile.js`)))412 yield fs.close(outputFile)413 return true414 })415 }416417 /**418 * Generates the project's gitignore file.419 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.420 * @returns {Promise<boolean>} A promise which wraps a generator function.421 * @memberof CodeGenerator422 */423 generateGitignore(outputPath) {424 const instance = this425 return co(function*() {426 if ((typeof outputPath !== 'string') || !outputPath.length) {427 throw {customMessage: 'The outputPath argument must be a non-empty string.'}428 }429 yield instance.checkOutputPath(outputPath)430 let outputFile = yield fs.open(path.join(outputPath, `.gitignore`), 'w')431 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/gitignore`)))432 yield fs.close(outputFile)433 return true434 })435 }436437 /**438 * Generates markdown docs from the jsdoc in all files that match the provided options.439 * @param {string} inputPath The folder containing the files to test.440 * @param {string} pattern The pattern by which to match files.441 * @param {string} outputPath The folder to put the generated files into.442 * @param {string[]} postMatchIgnore A list of paths to ignore post-match, since I can't get glob's "ignore" to work.443 * @returns {Promise<boolean>} A promise which wraps a generator function.444 * @memberof CodeGenerator445 */446 generateDocs(inputPath, pattern, outputPath, postMatchIgnore) {447 const instance = this448 return co(function*() {449 if ((typeof outputPath !== 'string') || !outputPath.length) {450 throw {customMessage: 'The outputPath argument must be a non-empty string.'}451 }452 yield instance.checkOutputPath(outputPath)453 const normalizedInputPath = path.normalize(inputPath)454 let paths = yield (new Promise((resolve, reject) => glob(455 path.join(normalizedInputPath, pattern),456 (err, matches) => err ? reject(err) : resolve(matches)457 ))),458 fd = null459 if (paths.length && (postMatchIgnore instanceof Array)) {460 let pathsToIgnore = [],461 actualPaths = []462 postMatchIgnore.forEach((p, index) => {463 pathsToIgnore.push(path.join(normalizedInputPath, p).replace(/\\/g, '/'))464 })465 paths.forEach((p, index) => {466 let ignored = false467 for (const i in pathsToIgnore) {468 if (p.replace(pathsToIgnore[i], '').length !== p.length) {469 ignored = true470 break471 }472 }473 if (ignored) {474 return475 }476 actualPaths.push(p)477 })478 paths = actualPaths479 }480 for (const i in paths) {481 const inputFilePath = paths[i],482 outputFilePath = path.normalize(inputFilePath).replace(normalizedInputPath, '').replace(/\.[^/.]+$/, '') + '.md'483 let delimiter = '\\',484 parentDirectory = outputFilePath.split(delimiter) // windows-style paths485 if (parentDirectory.length <= 1) {486 delimiter = '/'487 parentDirectory = outputFilePath.split(delimiter) // unix-style paths488 }489 if (parentDirectory.length > 1) {490 parentDirectory.pop()491 yield fs.mkdirp(path.join(outputPath, parentDirectory.join(delimiter)))492 }493 fd = yield fs.open(path.join(outputPath, outputFilePath), 'w')494 yield fs.writeFile(fd, yield jsdoc2md.render({files: inputFilePath}))495 yield fs.close(fd)496 }497 return true498 })499 }500501 /**502 * Generates the project's basic directory structure.503 * @param {string} outputPath The path to the folder in which the generated folders will be put. Must be a valid and accessible directory.504 * @param {boolean} overwrite (optional) Overwrite the existing folders. False by default.505 * @returns {Promise<boolean>} A promise which wraps a generator function.506 * @memberof CodeGenerator507 */508 generateFolders(outputPath, overwrite) {509 const instance = this510 return co(function*() {511 if ((typeof outputPath !== 'string') || !outputPath.length) {512 throw {customMessage: 'The outputPath argument must be a non-empty string.'}513 }514 yield instance.checkOutputPath(outputPath)515 const folderPaths = [516 path.join(outputPath, 'clients'),517 path.join(outputPath, 'config/profiles'),518 path.join(outputPath, 'logs'),519 path.join(outputPath, 'modules/db'),520 path.join(outputPath, 'modules/clients'),521 path.join(outputPath, 'modules/apis'),522 path.join(outputPath, 'modules/emails/templates'),523 path.join(outputPath, 'modules/migrations/seedFiles'),524 path.join(outputPath, 'modules/migrations/syncHistory'),525 path.join(outputPath, 'modules/migrations/backup'),526 path.join(outputPath, 'modules/migrations/staticData'),527 path.join(outputPath, 'public'),528 path.join(outputPath, 'storage/importTemplates'),529 path.join(outputPath, 'storage/tmp')530 ]531 if (overwrite) {532 for (const i in folderPaths) {533 const folderPath = folderPaths[i]534 yield fs.mkdirp(folderPath)535 }536 return true537 }538 for (const i in folderPaths) {539 const folderPath = folderPaths[i]540 try {541 yield fs.lstat(folderPath)542 } catch(e) {543 yield fs.mkdirp(folderPath)544 }545 }546 return true547 })548 }549550 /**551 * Generates a layout_<configProfile>.pug for a client module, based on the provided configProfile arg.552 * @param {string} outputPath The path to the folder in which the generated folders will be put. Must be a valid and accessible directory.553 * @param {string} configProfile The name of the config profile, whose template is to be used. An error will be thrown if it does not exist.554 * @returns {Promise<boolean>} A promise which wraps a generator function.555 * @memberof CodeGenerator556 */557 generateLayoutFile(outputPath, configProfile) {558 const instance = this559 return co(function*() {560 if ((typeof outputPath !== 'string') || !outputPath.length) {561 throw {customMessage: 'The outputPath argument must be a non-empty string.'}562 }563 yield instance.checkOutputPath(outputPath)564 let outputFile = yield fs.open(path.join(outputPath, `layout_${configProfile || 'local'}.pug`), 'w')565 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/clients/site/layout_${configProfile || 'local'}.pug`)))566 yield fs.close(outputFile)567 return true568 })569 }570571 /**572 * Generates a dbComponentName.model.d.ts files for each of a ramster's instance db.components' table and sequelize association data and puts them in the specified folder.573 * @param {string} outputPath The path to the folder in which the generated file will be put. Must be a valid and accessible directory.574 * @param {object} db An instance of ramster's db module.575 * @returns {Promise<boolean>} A promise which wraps a generator function.576 * @memberof CodeGenerator577 */578 generateTypescriptModels(outputPath, db) {579 const instance = this,580 {pgToTSMap} = this581 return co(function*() {582 if ((typeof outputPath !== 'string') || !outputPath.length) {583 throw {customMessage: 'The outputPath argument must be a non-empty string.'}584 }585 if (!dbComponents instanceof Array) {586 throw {customMessage: 'The dbComponents arg must a be a valid array of ramster dbComponent objects.'}587 }588 yield instance.checkOutputPath(outputPath)589 // get the table layouts and column types590 const {components, sequelize} = db,591 rawTableData = yield sequelize.query(`select column_name, data_type, table_name from information_schema.columns;`)592 let tableData = {}593 rawTableData.forEach((row, index) => {594 let tData = tableData[row.table_name]595 if (!tData) {596 tData = {}597 tableData[row.table_name] = tData598 }599 tData[row.column_name] = pgToTSMap[row.data_type.toLowerCase()] || 'any'600 })601 for (const i in components) {602 const dbComponent = components[i]603 if ((typeof dbComponent !== 'object') || (dbComponent === null) || !dbComponent.model) {604 throw {customMessage: `The item at index ${i} is not a valid ramster dbComponent object.`}605 }606 const columns = tableData[dbComponent.model.getTableName()]607 // write the column types data608 let dataToWrite = `module.exports = {\n`609 for (const colName in columns) {610 dataToWrite += ` ${colName}: ${columns[colName]},\n`611 // dataToWrite += ',\n'612 }613 dbComponent.relReadKeys.forEach((key, index) => {614 dataToWrite += ` ${key}: any,\n`615 })616 dataToWrite = dataToWrite.substr(0, dataToWrite.length - 2)617 dataToWrite += '\n}\n'618 // save the file619 let outputFile = yield fs.open(path.join(outputPath, `${dbComponent.componentName}.model.d.ts`), 'w')620 yield fs.writeFile(outputFile, dataToWrite)621 yield fs.close(outputFile)622 }623 return true624 })625 }626627 /**628 * Generates a project using the "blank" template, based on the provided configProfile arg. The "blank" template contains all the project's directory structure, the "index", "common" and "profile" project config files, the project main file and the webpack build tools.629 * @param {string} outputPath The path to the folder in which the generated folders will be put. Must be a valid and accessible directory.630 * @param {string} configProfile The name of the config profile, whose template is to be used. An error will be thrown if it does not exist.631 * @returns {Promise<boolean>} A promise which wraps a generator function.632 * @memberof CodeGenerator633 */634 generateBlankProject(outputPath, configProfile) {635 const instance = this636 return co(function*() {637 if ((typeof outputPath !== 'string') || !outputPath.length) {638 throw {customMessage: 'The outputPath argument must be a non-empty string.'}639 }640 yield instance.checkOutputPath(outputPath)641 yield instance.generateProjectMainFile(outputPath)642 yield instance.generateGitignore(outputPath)643 yield instance.generateFolders(outputPath, true)644 yield instance.generateIndexConfigFile(path.join(outputPath, 'config'))645 yield instance.generateCommonConfigFile(path.join(outputPath, 'config'))646 yield instance.generateProfileConfigFile(path.join(outputPath, 'config'), configProfile || 'local')647 yield instance.generateWebpackBuildTools(outputPath)648 yield fs.copy(path.join(__dirname, 'templates/modules/emails/templates/sample.pug'), path.join(outputPath, 'modules/emails/templates/sample.pug'))649 return true650 })651 }652653 /**654 * Generates a project using the "basic" template, based on the provided configProfile arg. The "basic" template contains everythign in the "blank" template, plus:655 * - webpack config for reactjs656 * - db modules for globalConfig, moduleAccessPoints, moduleCategories, modules, users, userTypes657 * - a "site" client module with components for layout and users658 * - email templates for "resetPassword", "updateEmail" and "emailUpdatedSuccessfully"659 * - a fully functioning access control system based on modules, user types and access points, as well as the code for creating and managing users, and updating their profile, password and email660 * - full code coverage for the above, realized using mochajs .spec.js files661 * - a staticData file and a mockStaticData file, containing basic example data for the above functionality662 * - an empty cronJobs module663 * - eslintrc, jsbeautifyrc and pug-lintrc664 * @param {string} outputPath The path to the folder in which the generated folders will be put. Must be a valid and accessible directory.665 * @param {string} configProfile The name of the config profile, whose template is to be used. An error will be thrown if it does not exist.666 * @param {string} webpackConfigType (optional) The webpack config type to generate, defaults to 'react' if not provided. Can be 'react' or 'angular'.667 * @returns {Promise<boolean>} A promise which wraps a generator function.668 * @memberof CodeGenerator669 */670 generateBasicProject(outputPath, configProfile, webpackConfigType) {671 const instance = this672 return co(function*() {673 if ((typeof outputPath !== 'string') || !outputPath.length) {674 throw {customMessage: 'The outputPath argument must be a non-empty string.'}675 }676 yield instance.checkOutputPath(outputPath)677 let dbModules = ['globalConfig', 'accessPoints', 'displayModuleCategories', 'displayModules', 'users', 'userTypes'],678 clientModules = ['layout', 'users'],679 outputFile = null680 yield instance.generateBlankProject(outputPath, configProfile)681 yield fs.copy(path.join(__dirname, 'templates/eslintrc'), path.join(outputPath, '.eslintrc'))682 yield fs.copy(path.join(__dirname, 'templates/jsbeautifyrc'), path.join(outputPath, '.jsbeautifyrc'))683 yield fs.copy(path.join(__dirname, 'templates/pug-lintrc'), path.join(outputPath, '.pug-lintrc'))684 yield fs.copy(path.join(__dirname, 'templates/modules/emails/templates/emailUpdatedSuccessfully.pug'), path.join(outputPath, 'modules/emails/templates/emailUpdatedSuccessfully.pug'))685 yield fs.copy(path.join(__dirname, 'templates/modules/emails/templates/resetPassword.pug'), path.join(outputPath, 'modules/emails/templates/resetPassword.pug'))686 yield fs.copy(path.join(__dirname, 'templates/modules/emails/templates/updateEmail.pug'), path.join(outputPath, 'modules/emails/templates/updateEmail.pug'))687 yield fs.mkdirp(path.join(outputPath, 'config/webpack'))688 yield instance.generateWebpackConfig(path.join(outputPath, 'config/webpack'), webpackConfigType || 'react')689 yield instance.generateLayoutFile(path.join(outputPath, 'clients/site'), configProfile)690 yield fs.copy(path.join(__dirname, 'templates/clients/site/index.js'), path.join(outputPath, 'clients/site/index.js'))691 yield fs.mkdirp(path.join(outputPath, 'public/site'))692 for (const i in dbModules) {693 let moduleName = dbModules[i],694 modulePath = path.join(outputPath, `modules/db/${moduleName}`)695 yield fs.mkdirp(modulePath)696 outputFile = yield fs.open(path.join(modulePath, `index.js`), 'w')697 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/modules/db/${moduleName}/index.js`)))698 yield fs.close(outputFile)699 try {700 let specData = yield fs.readFile(path.join(__dirname, `templates/modules/db/${moduleName}/index.spec.js`))701 outputFile = yield fs.open(path.join(modulePath, `index.spec.js`), 'w')702 yield fs.writeFile(outputFile, specData)703 yield fs.close(outputFile)704 } catch(e) {}705 }706 for (const i in clientModules) {707 let moduleName = clientModules[i],708 modulePath = path.join(outputPath, `modules/clients/site/${moduleName}`)709 yield fs.mkdirp(modulePath)710 outputFile = yield fs.open(path.join(modulePath, `index.js`), 'w')711 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, `templates/modules/clients/site/${moduleName}/index.js`)))712 yield fs.close(outputFile)713 try {714 let specData = yield fs.readFile(path.join(__dirname, `templates/modules/clients/site/${moduleName}/index.spec.js`))715 outputFile = yield fs.open(path.join(modulePath, `index.spec.js`), 'w')716 yield fs.writeFile(outputFile, specData)717 yield fs.close(outputFile)718 } catch(e) {}719 }720 yield fs.mkdirp(path.join(outputPath, `modules/apis/mobile`))721 let cronJobsPath = path.join(outputPath, 'modules/cronJobs')722 yield fs.mkdirp(cronJobsPath)723 outputFile = yield fs.open(path.join(cronJobsPath, `index.js`), 'w')724 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, 'templates/modules/cronJobs/index.js')))725 yield fs.close(outputFile)726 outputFile = yield fs.open(path.join(cronJobsPath, `index.spec.js`), 'w')727 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, 'templates/modules/cronJobs/index.spec.js')))728 yield fs.close(outputFile)729 outputFile = yield fs.open(path.join(outputPath, `modules/migrations/staticData/staticData.json`), 'w')730 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, 'templates/modules/migrations/staticData/staticData.json')))731 yield fs.close(outputFile)732 outputFile = yield fs.open(path.join(outputPath, `modules/migrations/staticData/mockStaticData.json`), 'w')733 yield fs.writeFile(outputFile, yield fs.readFile(path.join(__dirname, 'templates/modules/migrations/staticData/mockStaticData.json')))734 yield fs.close(outputFile)735 return true736 })737 }738}739 ...

Full Screen

Full Screen

codeGenerator.module.spec.js

Source:codeGenerator.module.spec.js Github

copy

Full Screen

1const2 assert = require('assert'),3 co = require('co'),4 {describeSuiteConditionally, runTestConditionally} = require('../toolbelt'),5 path = require('path'),6 fs = require('fs-extra')78module.exports = {9 testMe: function(ramster) {10 const instance = this11 describe('codeGenerator', function() {12 it('should execute testBuildLayoutFile successfully', function() {13 instance.testBuildLayoutFile()14 })15 it('should execute testCheckConfig successfully', function() {16 instance.testCheckConfig()17 })18 it('should execute testCheckOutputPath successfully', function() {19 instance.testCheckOutputPath()20 })21 it('should execute testGenerateConfigFile successfully', function() {22 instance.testGenerateConfigFile()23 })24 it('should execute testGenerateIndexConfigFile successfully', function() {25 instance.testGenerateIndexConfigFile()26 })27 it('should execute testGenerateCommonConfigFile successfully', function() {28 instance.testGenerateCommonConfigFile()29 })30 it('should execute testGenerateProfileConfigFile successfully', function() {31 instance.testGenerateProfileConfigFile()32 })33 it('should execute testGenerateProfileConfigFile successfully', function() {34 instance.testGenerateProfileConfigFile()35 })36 it('should execute testGenerateImagesRedirectNGINXConfig successfully', function() {37 instance.testGenerateImagesRedirectNGINXConfig()38 })39 it('should execute testGenerateNGINXConfig successfully', function() {40 instance.testGenerateNGINXConfig()41 })42 it('should execute testGenerateWebpackConfig successfully', function() {43 instance.testGenerateWebpackConfig()44 })45 it('should execute testGenerateWebpackBuildTools successfully', function() {46 instance.testGenerateWebpackBuildTools()47 })48 it('should execute testGenerateProjectMainFile successfully', function() {49 instance.testGenerateProjectMainFile()50 })51 it('should execute testGenerateGitignore successfully', function() {52 instance.testGenerateGitignore()53 })54 it('should execute testGenerateDocs successfully', function() {55 instance.testGenerateDocs()56 })57 it('should execute testGenerateFolders successfully', function() {58 instance.testGenerateFolders()59 })60 it('should execute testGenerateLayoutFile successfully', function() {61 instance.testGenerateLayoutFile()62 })63 // it('should execute testGenerateTypescriptModels successfully', function(ramster) {64 // instance.testGenerateTypescriptModels()65 // })66 it('should execute testGenerateBlankProject successfully', function() {67 instance.testGenerateBlankProject()68 })69 it('should execute testGenerateBasicProject successfully', function() {70 instance.testGenerateBasicProject()71 })72 })73 },74 testBuildLayoutFile: function() {75 const instance = this76 describe('codeGenerator.buildLayoutFile', function() {77 it('should throw an error when the clientModuleName argument is not a string or is empty', function() {78 return co(function*() {79 let didThrowAnError = false80 try {81 yield instance.buildLayoutFile()82 } catch(e) {83 didThrowAnError = true84 }85 assert.strictEqual(didThrowAnError, true, 'no error was thrown')86 return true87 })88 })89 it('should execute successfully, if all parameters are correct', function() {90 return co(function*() {91 let outputPath = path.join(__dirname, '../../test/public/site/layout.html')92 yield instance.buildLayoutFile('site')93 let fileData = yield fs.lstat(outputPath)94 if (!fileData.isFile()) {95 try {96 yield fs.remove(outputPath)97 } catch (e) {98 }99 assert(false, 'no file was generated')100 return false101 }102 // yield fs.remove(outputPath)103 return true104 })105 })106 })107 },108 testCheckConfig: function() {109 const instance = this110 describe('codeGenerator.checkConfig', function() {111 it('should return true if the config is an object and is not null', function() {112 assert.strictEqual(instance.checkConfig({}), true, 'еxpected true from checkConfig')113 })114 it('should throw an error if the config is null or not an object', function() {115 let didThrowAnError = false116 try {117 instance.checkConfig()118 } catch (e) {119 didThrowAnError = true120 }121 assert.strictEqual(didThrowAnError, true, 'no error was thrown')122 })123 it('should return true if the sub-config for the provided client module is an object and is not null', function() {124 let result = instance.checkConfig({clients: {test: {}}}, {clientModuleName: 'test'})125 assert.strictEqual(result, true, `bad return value ${result}, expected true`)126 })127 it('should throw an error if the config does not have sub-config for the provided client module', function() {128 let didThrowAnError = false129 try {130 instance.checkConfig({}, {clientModuleName: 'test'})131 } catch (e) {132 didThrowAnError = true133 }134 assert.strictEqual(didThrowAnError, true, 'no error was thrown')135 })136 it('should return true if the sub-config for the provided api module is an object and is not null', function() {137 assert(instance.checkConfig({apis: {test: {}}}, {apiModuleName: 'test'}))138 })139 it('should throw an error if the config does not have sub-config for the provided api module', function() {140 let didThrowAnError = false141 try {142 instance.checkConfig({}, {apiModuleName: 'test'})143 } catch (e) {144 didThrowAnError = true145 }146 assert.strictEqual(didThrowAnError, true, 'no error was thrown')147 })148 })149 },150 testCheckOutputPath: function() {151 const instance = this152 describe('codeGenerator.checkOutputPath', function() {153 it('should throw an error when the outputPath argument is not a string or is empty', function() {154 return co(function*() {155 let didThrowAnError = false156 try {157 yield instance.checkOutputPath()158 } catch(e) {159 didThrowAnError = true160 }161 assert.strictEqual(didThrowAnError, true, 'no error was thrown')162 return true163 })164 })165 it('should throw an error when the outputPath argument points to a file, rather than a directory', function() {166 return co(function*() {167 let didThrowAnError = false168 try {169 yield instance.checkOutputPath(path.join(__dirname, './index.js'))170 } catch(e) {171 didThrowAnError = true172 }173 assert.strictEqual(didThrowAnError, true, 'no error was thrown')174 return true175 })176 })177 it('should return true if the sub-config for the provided api module is an object and is not null', function() {178 return co(function*() {179 assert.strictEqual(yield instance.checkOutputPath(__dirname), true, 'expected true from checkOutputPath')180 return true181 })182 })183 })184 },185 testGenerateConfigFile: function() {186 const instance = this187 describe('codeGenerator.generateConfigFile', function() {188 it('should create a directory if the provided outputPath is valid, but does not exist, and should work for nested non-existent directories', function() {189 return co(function*() {190 let outputPath = path.join(__dirname, './test/nestedTest')191 yield instance.generateConfigFile(outputPath, 'index.js', path.join(__dirname, './templates/config/index.js'))192 let dirData = yield fs.lstat(outputPath)193 if (!dirData.isDirectory()) {194 try {195 yield fs.remove(path.join(__dirname, './test'))196 } catch (e) {197 }198 assert(false, 'did not generate a file')199 return false200 }201 yield fs.remove(path.join(__dirname, './test'))202 return true203 })204 })205 it('should create a file with the correct name at the provided outputPath', function() {206 return co(function*() {207 let outputPath = path.join(__dirname, './test')208 yield instance.generateConfigFile(outputPath, 'index.js', path.join(__dirname, './templates/config/index.js'))209 let fileData = yield fs.lstat(path.join(outputPath, 'index.js'))210 if (!fileData.isFile()) {211 try {212 yield fs.remove(outputPath)213 } catch (e) {214 }215 assert(false, 'did not generate a file')216 return false217 }218 yield fs.remove(outputPath)219 return true220 })221 })222 })223 },224 testGenerateIndexConfigFile: function() {225 const instance = this226 describe('codeGenerator.generateIndexConfigFile', function() {227 it('should execute successfully', function() {228 return co(function*() {229 let outputPath = path.join(__dirname, './test')230 yield instance.generateIndexConfigFile(outputPath)231 let fileData = yield fs.lstat(path.join(outputPath, 'index.js'))232 if (!fileData.isFile()) {233 try {234 yield fs.remove(outputPath)235 } catch (e) {236 }237 assert(false, 'did not generate a file')238 return false239 }240 yield fs.remove(outputPath)241 return true242 })243 })244 })245 },246 testGenerateCommonConfigFile: function() {247 const instance = this248 describe('codeGenerator.generateCommonConfigFile', function() {249 it('should execute successfully', function() {250 return co(function*() {251 let outputPath = path.join(__dirname, './test')252 yield instance.generateCommonConfigFile(outputPath)253 let fileData = yield fs.lstat(path.join(outputPath, 'common.js'))254 if (!fileData.isFile()) {255 try {256 yield fs.remove(outputPath)257 } catch (e) {258 }259 assert(false, 'did not generate a file')260 return false261 }262 yield fs.remove(outputPath)263 return true264 })265 })266 })267 },268 testGenerateProfileConfigFile: function() {269 const instance = this270 describe('codeGenerator.generateProfileConfigFile', function() {271 it('should throw an error when the profileName argument is not a string or is empty', function() {272 return co(function*() {273 let didThrowAnError = false274 try {275 yield instance.generateProfileConfigFile(path.join(__dirname, './test', 'local'))276 } catch(e) {277 didThrowAnError = true278 }279 assert.strictEqual(didThrowAnError, true, 'no error was thrown')280 return true281 })282 })283 it('should execute successfully, if all parameters are correct', function() {284 return co(function*() {285 let outputPath = path.join(__dirname, './test', 'local')286 yield instance.generateProfileConfigFile(outputPath, 'local')287 let fileData = yield fs.lstat(path.join(outputPath, '/profiles/local.js'))288 if (!fileData.isFile()) {289 try {290 yield fs.remove(path.join(__dirname, './test'))291 } catch (e) {292 }293 assert(false, 'did not generate a file')294 return false295 }296 yield fs.remove(path.join(__dirname, './test'))297 return true298 })299 })300 })301 },302 testGenerateImagesRedirectNGINXConfig: function() {303 const instance = this304 describe('codeGenerator.generateImagesRedirectNGINXConfig', function() {305 it('should execute successfully, if all parameters are correct', function() {306 return co(function*() {307 let outputPath = path.join(__dirname, './test'),308 outputFilePath = path.join(outputPath, './images.conf')309 yield instance.generateImagesRedirectNGINXConfig(outputPath)310 let fileData = yield fs.lstat(outputFilePath)311 if (!fileData.isFile()) {312 try {313 yield fs.remove(outputFilePath)314 } catch (e) {315 }316 assert(false, 'did not generate a file')317 return false318 }319 yield fs.remove(outputFilePath)320 return true321 })322 })323 })324 },325 testGenerateNGINXConfig: function() {326 const instance = this,327 {config} = this328 describe('codeGenerator.generateNGINXConfig', function() {329 it('should throw an error when the clientModuleName argument is not a string or is empty', function() {330 return co(function*() {331 let didThrowAnError = false332 try {333 yield instance.generateNGINXConfig()334 } catch(e) {335 didThrowAnError = true336 }337 assert.strictEqual(didThrowAnError, true, 'no error was thrown')338 return true339 })340 })341 it('should execute successfully, if all parameters are correct', function() {342 return co(function*() {343 let isAFile = false344 yield instance.generateNGINXConfig('site')345 let configFilePath = path.join(config.wsConfigFolderPath, `${config.projectName}-site.conf`),346 fileStats = yield fs.lstat(configFilePath)347 isAFile = fileStats.isFile()348 try {349 yield fs.remove(configFilePath)350 } catch (e) {351 }352 assert.strictEqual(isAFile, true, `bad value ${isAFile} for the isFile check, expected true`)353 return true354 })355 })356 })357 },358 testGenerateWebpackConfig: function() {359 const instance = this360 describe('codeGenerator.generateWebpackConfig', function() {361 it('should throw an error with the correct message if the config type argument is invalid', function() {362 return co(function*() {363 let didThrowAnError = false364 try {365 yield instance.generateWebpackConfig(path.join(__dirname, './test'))366 } catch(e) {367 didThrowAnError = e && (e.customMessage === 'Invalid webpack config type.')368 }369 assert.strictEqual(didThrowAnError, true, 'no error was thrown')370 return true371 })372 })373 it('should execute successfully if all parameters are correct', function() {374 return co(function*() {375 let outputPath = path.join(__dirname, './test'),376 outputFilePath = path.join(outputPath, './react.js')377 yield instance.generateWebpackConfig(outputPath, 'react')378 let fileData = yield fs.lstat(outputFilePath)379 if (!fileData.isFile()) {380 try {381 yield fs.remove(outputFilePath)382 } catch (e) {383 }384 assert(false, 'no file was generated')385 return false386 }387 yield fs.remove(outputFilePath)388 return true389 })390 })391 })392 },393 testGenerateWebpackBuildTools: function() {394 const instance = this395 describe('codeGenerator.generateWebpackBuildTools', function() {396 it('should execute successfully if all parameters are correct', function() {397 return co(function*() {398 let outputPath = path.join(__dirname, './test'),399 devserverOutputFilePath = path.join(outputPath, './webpackDevserver.js'),400 builOutputFilePath = path.join(outputPath, './webpackBuild.js')401 yield instance.generateWebpackBuildTools(outputPath)402 let fileData = yield fs.lstat(devserverOutputFilePath)403 if (!fileData.isFile()) {404 try {405 yield fs.remove(devserverOutputFilePath)406 } catch (e) {407 }408 assert(false, 'no file was generated')409 return false410 }411 fileData = yield fs.lstat(builOutputFilePath)412 if (!fileData.isFile()) {413 try {414 yield fs.remove(builOutputFilePath)415 } catch (e) {416 }417 assert(false, 'no file was generated')418 return false419 }420 yield fs.remove(devserverOutputFilePath)421 yield fs.remove(builOutputFilePath)422 return true423 })424 })425 })426 },427 testGenerateProjectMainFile: function() {428 const instance = this429 describe('codeGenerator.generateProjectMainFile', function() {430 it('should execute successfully if all parameters are correct', function() {431 return co(function*() {432 let outputPath = path.join(__dirname, './test'),433 outputFilePath = path.join(outputPath, './index.js')434 yield instance.generateProjectMainFile(outputPath)435 let fileData = yield fs.lstat(outputFilePath)436 if (!fileData.isFile()) {437 try {438 yield fs.remove(outputFilePath)439 } catch (e) {440 }441 assert(false, 'no file was generated')442 return false443 }444 yield fs.remove(outputFilePath)445 return true446 })447 })448 })449 },450 testGenerateGitignore: function() {451 const instance = this452 describe('codeGenerator.generateGitignore', function() {453 it('should execute successfully if all parameters are correct', function() {454 return co(function*() {455 let outputPath = path.join(__dirname, './test'),456 outputFilePath = path.join(outputPath, './.gitignore')457 yield instance.generateGitignore(outputPath)458 let fileData = yield fs.lstat(outputFilePath)459 if (!fileData.isFile()) {460 try {461 yield fs.remove(outputFilePath)462 } catch (e) {463 }464 assert(false, 'no file was generated')465 return false466 }467 yield fs.remove(outputFilePath)468 return true469 })470 })471 })472 },473 testGenerateDocs: function() {474 const instance = this475 let inputPath = path.join(__dirname, './test/input'),476 outputPath = path.join(__dirname, './test/output'),477 fileList = ['topLevelTest.md', 'testFolder/firstLowerLevelTest.md', 'testFolder/innerTestFolder/secondLowerLevelTest.md']478 describe('codeGenerator.generateDocs', function() {479 before(function() {480 return co(function*() {481 yield fs.mkdirp(path.join(inputPath, 'testFolder/innerTestFolder'))482 yield fs.mkdirp(path.join(inputPath, 'node_modules'))483 yield fs.mkdirp(outputPath)484 let fd = yield fs.open(path.join(inputPath, 'topLevelTest.js'), 'w')485 yield fs.writeFile(fd, `486 /**487 * The topLevelTest module. Contains the TopLevelTest class.488 * @module topLevelTestModule489 */490 /**491 * The TopLevelTest class.492 * @class TopLevelTest493 */494 class TopLevelTest {495 /**496 * Does something.497 * @param {string} arg1 The first arg.498 * @param {number} arg2 The second arg.499 * @returns {void}500 * @memberof TopLevelTest501 */502 testMethod(arg1, arg2) {}503 }504 `)505 yield fs.close(fd)506 fd = yield fs.open(path.join(inputPath, 'testFolder/firstLowerLevelTest.js'), 'w')507 yield fs.writeFile(fd, `508 /**509 * The firstLowerLevelTest module. Contains the FirstLowerLevelTest class.510 * @module firstLowerLevelTestModule511 */512 /**513 * The FirstLowerLevelTest class.514 * @class FirstLowerLevelTest515 */516 class FirstLowerLevelTest {517 /**518 * Does something else.519 * @param {string} arg1 The first arg.520 * @param {number} arg2 The second arg.521 * @returns {void}522 * @memberof FirstLowerLevelTest523 */524 testMethod2(arg1, arg2) {}525 }526 `)527 yield fs.close(fd)528 fd = yield fs.open(path.join(inputPath, 'testFolder/innerTestFolder/secondLowerLevelTest.js'), 'w')529 yield fs.writeFile(fd, `530 /**531 * The secondLowerLevelTest module. Contains the SecondLowerLevelTest class.532 * @module secondLowerLevelTestModule533 */534 /**535 * The SecondLowerLevelTest class.536 * @class SecondLowerLevelTest537 */538 class SecondLowerLevelTest {539 /**540 * Does something else entirely.541 * @param {string} arg1 The first arg.542 * @param {number} arg2 The second arg.543 * @returns {void}544 * @memberof SecondLowerLevelTest545 */546 testMethod3(arg1, arg2) {}547 }548 `)549 yield fs.close(fd)550 fd = yield fs.open(path.join(inputPath, 'node_modules/shouldNotExist.js'), 'w')551 yield fs.writeFile(fd, `552 /**553 * The shouldNotExist module. Contains the ShouldNotExist class.554 * @module shouldNotExistModule555 */556 /**557 * The ShouldNotExist class.558 * @class ShouldNotExist559 */560 class ShouldNotExist {561 /**562 * Does not actually do anything.563 * @param {string} arg1 The first arg.564 * @param {number} arg2 The second arg.565 * @returns {void}566 * @memberof ShouldNotExist567 */568 testMethod4(arg1, arg2) {}569 }570 `)571 yield fs.close(fd)572 return true573 })574 })575 it('should execute successfully if all parameters are correct', function() {576 this.timeout(10000)577 return co(function*() {578 yield instance.generateDocs(inputPath, '**/*.js', outputPath, ['node_modules'])579 for (const i in fileList) {580 const pathToFile = path.join(outputPath, fileList[i])581 let fileData = yield fs.lstat(pathToFile)582 assert.strictEqual(fileData.isFile(), true, `expected ${pathToFile} to exist as a file`)583 }584 return true585 })586 })587 after(function() {588 return co(function*() {589 yield fs.remove(inputPath)590 yield fs.remove(outputPath)591 return true592 })593 })594 })595 },596 testGenerateFolders: function() {597 const instance = this598 describe('codeGenerator.generateFolders', function() {599 it('should execute successfully if all parameters are correct', function() {600 return co(function*() {601 let outputPath = path.join(__dirname, './test'),602 outputPaths = [603 {path: path.join(outputPath, 'clients'), type: false},604 {path: path.join(outputPath, 'config/profiles'), type: false},605 {path: path.join(outputPath, 'logs'), type: false},606 {path: path.join(outputPath, 'modules/db'), type: false},607 {path: path.join(outputPath, 'modules/clients'), type: false},608 {path: path.join(outputPath, 'modules/apis'), type: false},609 {path: path.join(outputPath, 'modules/emails/templates'), type: false},610 {path: path.join(outputPath, 'modules/migrations/seedFiles'), type: false},611 {path: path.join(outputPath, 'modules/migrations/syncHistory'), type: false},612 {path: path.join(outputPath, 'modules/migrations/backup'), type: false},613 {path: path.join(outputPath, 'modules/migrations/staticData'), type: false},614 {path: path.join(outputPath, 'public'), type: false},615 {path: path.join(outputPath, 'storage/importTemplates'), type: false},616 {path: path.join(outputPath, 'storage/tmp'), type: false}617 ]618 yield instance.generateFolders(outputPath)619 for (const i in outputPaths) {620 let item = outputPaths[i],621 itemData = yield fs.lstat(item.path),622 isFile = itemData.isFile()623 if (isFile !== item.type) {624 assert.strictEqual(isFile, item.type, `bad value ${isFile} for the isFile check for item no. ${i}, expected ${item.type}`)625 }626 }627 yield fs.remove(outputPath)628 return true629 })630 })631 })632 },633 testGenerateLayoutFile: function() {634 const instance = this635 describe('codeGenerator.generateLayoutFile', function() {636 it('should execute successfully if all parameters are correct', function() {637 return co(function*() {638 let outputPath = path.join(__dirname, 'test/clients/site'),639 outputFilePath = path.join(outputPath, 'layout_local.pug')640 yield instance.generateLayoutFile(outputPath)641 let fileData = yield fs.lstat(outputFilePath)642 if (!fileData.isFile()) {643 try {644 yield fs.remove(outputFilePath)645 } catch (e) {646 }647 assert(false, 'no file generated')648 return false649 }650 yield fs.remove(outputFilePath)651 return true652 })653 })654 })655 },656 testGenerateTypescriptModels: function(ramster) {657 const instance = this658 let outputPath = path.join(__dirname, 'test/clients/site/models')659 describe('codeGenerator.generateTypescriptModels', function() {660 before(function() {661 return co(function*() {662 yield fs.mkdirp(outputPath)663 return true664 })665 })666 it('should execute successfully if all parameters are correct', function() {667 return co(function*() {668 yield instance.generateTypescriptModels(outputPath)669 let fileData = yield fs.lstat(outputFilePath)670 if (!fileData.isFile()) {671 assert(false, 'no file generated')672 return false673 }674 return true675 })676 })677 after(function() {678 return co(function*() {679 yield fs.remove(outputPath)680 return true681 })682 })683 })684 },685 testGenerateBlankProject: function() {686 const instance = this687 describe('codeGenerator.generateBlankProject', function() {688 it('should execute successfully if all parameters are correct', function() {689 return co(function*() {690 let outputPath = path.join(__dirname, './test'),691 outputPaths = [692 {path: path.join(outputPath, 'index.js'), type: true},693 {path: path.join(outputPath, 'webpackDevserver.js'), type: true},694 {path: path.join(outputPath, 'webpackBuild.js'), type: true},695 {path: path.join(outputPath, '.gitignore'), type: true},696 {path: path.join(outputPath, 'clients'), type: false},697 {path: path.join(outputPath, 'config/index.js'), type: true},698 {path: path.join(outputPath, 'config/common.js'), type: true},699 {path: path.join(outputPath, 'config/profiles'), type: false},700 {path: path.join(outputPath, 'config/profiles/local.js'), type: true},701 {path: path.join(outputPath, 'logs'), type: false},702 {path: path.join(outputPath, 'modules/db'), type: false},703 {path: path.join(outputPath, 'modules/clients'), type: false},704 {path: path.join(outputPath, 'modules/apis'), type: false},705 {path: path.join(outputPath, 'modules/emails/templates/sample.pug'), type: true},706 {path: path.join(outputPath, 'modules/migrations/seedFiles'), type: false},707 {path: path.join(outputPath, 'modules/migrations/syncHistory'), type: false},708 {path: path.join(outputPath, 'modules/migrations/backup'), type: false},709 {path: path.join(outputPath, 'modules/migrations/staticData'), type: false},710 {path: path.join(outputPath, 'public'), type: false},711 {path: path.join(outputPath, 'storage/importTemplates'), type: false},712 {path: path.join(outputPath, 'storage/tmp'), type: false}713 ]714 yield instance.generateBlankProject(outputPath)715 for (const i in outputPaths) {716 let item = outputPaths[i],717 itemData = yield fs.lstat(item.path),718 isFile = itemData.isFile()719 if (isFile !== item.type) {720 assert.strictEqual(isFile, item.type, `bad value ${isFile} for the isFile check for item no. ${i}, expected ${item.type}`)721 }722 }723 yield fs.remove(outputPath)724 return true725 })726 })727 })728 },729 testGenerateBasicProject: function() {730 const instance = this731 describe('codeGenerator.generateBasicProject', function() {732 it('should execute successfully if all parameters are correct', function() {733 return co(function*() {734 let outputPath = path.join(__dirname, './test'),735 outputPaths = [736 {path: path.join(outputPath, 'index.js'), type: true},737 {path: path.join(outputPath, 'webpackDevserver.js'), type: true},738 {path: path.join(outputPath, 'webpackBuild.js'), type: true},739 {path: path.join(outputPath, '.gitignore'), type: true},740 {path: path.join(outputPath, 'clients/site/layout_local.pug'), type: true},741 {path: path.join(outputPath, 'config/index.js'), type: true},742 {path: path.join(outputPath, 'config/common.js'), type: true},743 {path: path.join(outputPath, 'config/profiles'), type: false},744 {path: path.join(outputPath, 'config/profiles/local.js'), type: true},745 {path: path.join(outputPath, 'config/webpack/react.js'), type: true},746 {path: path.join(outputPath, 'logs'), type: false},747 {path: path.join(outputPath, 'modules/apis/mobile'), type: false},748 {path: path.join(outputPath, 'modules/clients'), type: false},749 {path: path.join(outputPath, 'modules/clients/site/layout/index.js'), type: true},750 {path: path.join(outputPath, 'modules/clients/site/layout/index.spec.js'), type: true},751 {path: path.join(outputPath, 'modules/clients/site/users/index.js'), type: true},752 {path: path.join(outputPath, 'modules/clients/site/users/index.spec.js'), type: true},753 {path: path.join(outputPath, 'modules/cronJobs/index.js'), type: true},754 {path: path.join(outputPath, 'modules/cronJobs/index.spec.js'), type: true},755 {path: path.join(outputPath, 'modules/db'), type: false},756 {path: path.join(outputPath, 'modules/db/globalConfig/index.js'), type: true},757 {path: path.join(outputPath, 'modules/db/globalConfig/index.spec.js'), type: true},758 {path: path.join(outputPath, 'modules/db/accessPoints/index.js'), type: true},759 {path: path.join(outputPath, 'modules/db/displayModuleCategories/index.js'), type: true},760 {path: path.join(outputPath, 'modules/db/displayModules/index.js'), type: true},761 {path: path.join(outputPath, 'modules/db/users/index.js'), type: true},762 {path: path.join(outputPath, 'modules/db/users/index.spec.js'), type: true},763 {path: path.join(outputPath, 'modules/db/userTypes/index.js'), type: true},764 {path: path.join(outputPath, 'modules/db/userTypes/index.spec.js'), type: true},765 {path: path.join(outputPath, 'modules/emails/templates/sample.pug'), type: true},766 {path: path.join(outputPath, 'modules/migrations/seedFiles'), type: false},767 {path: path.join(outputPath, 'modules/migrations/syncHistory'), type: false},768 {path: path.join(outputPath, 'modules/migrations/backup'), type: false},769 {path: path.join(outputPath, 'modules/migrations/staticData'), type: false},770 {path: path.join(outputPath, 'modules/migrations/staticData/staticData.json'), type: true},771 {path: path.join(outputPath, 'modules/migrations/staticData/mockStaticData.json'), type: true},772 {path: path.join(outputPath, 'public/site'), type: false},773 {path: path.join(outputPath, 'storage/importTemplates'), type: false},774 {path: path.join(outputPath, 'storage/tmp'), type: false},775 ]776 yield instance.generateBasicProject(outputPath)777 for (const i in outputPaths) {778 let item = outputPaths[i],779 itemData = yield fs.lstat(item.path),780 isFile = itemData.isFile()781 if (isFile !== item.type) {782 assert.strictEqual(isFile, item.type, `bad value ${isFile} for the isFile check for item no. ${i}, expected ${item.type}`)783 }784 }785 yield fs.remove(outputPath)786 return true787 })788 })789 })790 } ...

Full Screen

Full Screen

writeClient.ts

Source:writeClient.ts Github

copy

Full Screen

1import * as path from "path";2import { Client } from "../client/interfaces/Client";3import { HttpClient } from "../index";4import { copyFile, mkdir, rmdir } from "./fileSystem";5import { Templates } from "./registerHandlebarTemplates";6import { writeClientIndex } from "./writeClientIndex";7import { writeClientModels } from "./writeClientModels";8import { writeClientSchemas } from "./writeClientSchemas";9import { writeClientServices } from "./writeClientServices";10import { writeClientSettings } from "./writeClientSettings";11async function copySupportFile(12 filePath: string,13 outputPath: string14): Promise<void> {15 await copyFile(16 path.resolve(__dirname, `../src/templates/${filePath}`),17 path.resolve(outputPath, filePath)18 );19}20/**21 * Write our OpenAPI client, using the given templates at the given output path.22 * @param client Client object with all the models, services, etc.23 * @param templates Templates wrapper with all loaded Handlebars templates.24 * @param output Directory to write the generated files to.25 * @param httpClient The selected httpClient (fetch or XHR).26 * @param useOptions Use options or arguments functions.27 * @param exportCore: Generate core.28 * @param exportServices: Generate services.29 * @param exportModels: Generate models.30 * @param exportSchemas: Generate schemas.31 */32export async function writeClient(33 client: Client,34 templates: Templates,35 output: string,36 httpClient: HttpClient,37 useOptions: boolean,38 exportCore: boolean,39 exportServices: boolean,40 exportModels: boolean,41 exportSchemas: boolean42): Promise<void> {43 const outputPath = path.resolve(process.cwd(), output);44 const outputPathCore = path.resolve(outputPath, "core");45 const outputPathModels = path.resolve(outputPath, "models");46 const outputPathSchemas = path.resolve(outputPath, "schemas");47 const outputPathServices = path.resolve(outputPath, "services");48 // Clean output directory49 await rmdir(outputPath);50 await mkdir(outputPath);51 if (exportCore) {52 await mkdir(outputPathCore);53 await copySupportFile("core/ApiError.ts", outputPath);54 await copySupportFile("core/getFormData.ts", outputPath);55 await copySupportFile("core/getQueryString.ts", outputPath);56 await copySupportFile("core/isSuccess.ts", outputPath);57 await copySupportFile("core/request.ts", outputPath);58 await copySupportFile("core/RequestOptions.ts", outputPath);59 await copySupportFile("core/requestUsingFetch.ts", outputPath);60 await copySupportFile("core/requestUsingXHR.ts", outputPath);61 await copySupportFile("core/Result.ts", outputPath);62 }63 if (exportServices) {64 await mkdir(outputPathServices);65 await writeClientSettings(client, templates, outputPathCore, httpClient);66 await writeClientServices(67 client.services,68 templates,69 outputPathServices,70 useOptions71 );72 }73 if (exportSchemas) {74 await mkdir(outputPathSchemas);75 await writeClientSchemas(client.models, templates, outputPathSchemas);76 }77 if (exportModels) {78 await mkdir(outputPathModels);79 await copySupportFile("models/Dictionary.ts", outputPath);80 await writeClientModels(client.models, templates, outputPathModels);81 }82 await writeClientIndex(83 client,84 templates,85 outputPath,86 exportCore,87 exportServices,88 exportModels,89 exportSchemas90 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var argosyRpc = require('argosy-rpc')4var argosyPipeline = require('argosy-pipeline')5var argosyPath = require('argosy-path')6var argosyReceiver = require('argosy-receiver')7var argosySender = require('argosy-transport-http')8var argosyService = require('argosy-service')9var pipeline = argosyPipeline()10var service = argosyService()11var client = argosy()12client.pipe(argosyReceiver(argosySender({ path: '/argosy' }))).pipe(client)13client.use(argosyRpc({14 hello: argosyPattern.match.value('hello')15}))16client.rpc.hello(function (err, result) {17 console.log('client received result', result)18})19 .use(argosyPath())20 .use(function (req, res) {21 res.end('hello')22 })23var server = argosy()24server.pipe(argosyReceiver(argosySender({ path: '/argosy' }))).pipe(server)25server.use(argosyRpc({26 hello: argosyPattern.match.value('hello')27}))28server.rpc.hello(function (err, result) {29 console.log('server received result', result)30})31server.use(pipeline)32server.use(service)33server.listen(3000)

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var pattern = require('argosy-pattern')3var argosyService = argosy()4var argosyClient = argosy()5argosyService.accept(pattern({6}), function (msg, callback) {7 callback(null, msg.test)8})9argosyClient.pipe(argosyService).pipe(argosyClient)10argosyClient({test: 'hello'}, function (err, result) {11})12var pattern = require('argosy-pattern')13var myPattern = pattern({14})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyPatterns = require('argosy-patterns')3var argosyPacker = require('argosy-patterns/packer')4var argosyUnpacker = require('argosy-patterns/unpacker')5var argosyPacker = require('argosy-patterns/packer')6var argosyUnpacker = require('argosy-patterns/unpacker')7var through = require('through2')8var path = require('path')9var fs = require('fs')10var outputPath = path.join(__dirname, 'output.txt')11var argosyService = argosy()12argosyService.use(argosyPatterns({13 'test': function (data, callback) {14 console.log('test data: ', data)15 callback(null, data)16 }17}))18var argosyClient = argosy()19argosyClient.use(argosyPatterns({20 'test': function (data, callback) {21 console.log('test data: ', data)22 callback(null, data)23 }24}))25var testStream = through.obj()26var testStream2 = through.obj()27testStream.pipe(argosyPacker()).pipe(argosyClient).pipe(argosyUnpacker()).pipe(testStream2)28testStream.write({29})30testStream2.on('data', function (data) {31 console.log('received data: ', data)32})33testStream.write({34})

Full Screen

Using AI Code Generation

copy

Full Screen

1const argosy = require('argosy')2const pattern = require('argosy-pattern')3const service = argosy()4service.accept({5 hello: pattern.match('world')6})7service.on('error', console.error)8service.listen(8000, function () {9 console.log('listening on port 8000')10})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var path = require('path')3var fs = require('fs')4var test = require('tape')5var concat = require('concat-stream')6var through = require('through2')7var mkdirp = require('mkdirp')8var rimraf = require('rimraf')9var argosyPatterns = require('argosy-patterns')10var argosyRpc = require('argosy-rpc')11var argosyAccept = require('argosy-accept')12var argosyPath = require('../')13test('path', function (t) {14 t.plan(1)15 var outputPath = path.join(__dirname, 'output')16 var argosy = require('argosy')()17 argosy.pipe(argosy.accept({ outputPath: outputPath }))18 argosy.pipe(argosy.rpc({19 hello: function (name, cb) {20 cb(null, 'hello ' + name)21 }22 }))23 argosy.accept({ outputPath: outputPath }).hello('world', function (err, result) {24 if (err) t.fail(err)25 t.equal(result, 'hello world')26 rimraf.sync(outputPath)27 })28})29test('path', function (t) {30 t.plan(1)31 var outputPath = path.join(__dirname, 'output')32 var argosy = require('argosy')()33 argosy.pipe(argosy.accept({ outputPath: outputPath }))34 argosy.pipe(argosy.rpc({35 hello: function (name, cb) {36 cb(null, 'hello ' + name)37 }38 }))39 argosy.accept({ outputPath: outputPath }).hello('world', function (err, result) {40 if (err) t.fail(err)41 t.equal(result, 'hello world')42 rimraf.sync(outputPath)43 })44})45test('path', function (t) {46 t.plan(1)47 var outputPath = path.join(__dirname, 'output')48 var argosy = require('argosy')()49 argosy.pipe(argosy.accept({ outputPath: outputPath }))50 argosy.pipe(argosy.rpc({51 hello: function (name, cb) {52 cb(null, 'hello ' + name)53 }54 }))55 argosy.accept({ outputPath: outputPath }).hello('world', function (err,

Full Screen

Using AI Code Generation

copy

Full Screen

1const argosy = require('argosy')2const argosyPatterns = require('argosy-patterns')3const argosyPipeline = require('argosy-pipeline')4const argosyFile = require('argosy-file')5const argosyPack = require('argosy-pack')6const argosyJson = require('argosy-json')7const pipeline = argosyPipeline()8const pack = argosyPack()9const unpack = argosyPack({ unpack: true })10const json = argosyJson()11const file = argosyFile()12const service = argosy()13service.use('file', file)14service.use('json', json)15service.use('pack', pack)16service.use('unpack', unpack)17service.use('pipeline', pipeline)18service.pipe(argosy.acceptor()).pipe(service)19service.act('file:write', { path: outputPath, content: 'hello world' }, (err, result) => {20 if (err) return console.log('err', err)21 console.log('result', result)22})23service.act('file:read', { path: outputPath }, (err, result) => {24 if (err) return console.log('err', err)25 console.log('result', result)26})

Full Screen

Using AI Code Generation

copy

Full Screen

1const argosy = require('argosy')2const pattern = require('argosy-pattern')3const service = argosy()4const testPattern = pattern({5 test: pattern.outputPath('test')6})7service.accept({8 test: (input, cb) => {9 cb(null, input)10 }11})12 .act(testPattern)13 .on('error', console.error)14 .on('data', console.log)15 .end({16 })17const argosy = require('argosy')18const pattern = require('argosy-pattern')19const service = argosy()20const testPattern = pattern({21 test: pattern.object({22 test: pattern.outputPath('test')23 })24})25service.accept({26 test: (input, cb) => {27 cb(null, input)28 }29})30 .act(testPattern)31 .on('error', console.error)32 .on('data', console.log)33 .end({34 test: {35 }36 })37const argosy = require('argosy')38const pattern = require('argosy-pattern')39const service = argosy()40const testPattern = pattern({41 test: pattern.array([42 pattern.outputPath('test')43})44service.accept({45 test: (input, cb) => {46 cb(null, input)47 }48})49 .act(testPattern)50 .on('error', console.error)51 .on('data', console.log)52 .end({53 })54const argosy = require('argosy')55const pattern = require('argosy-pattern')56const service = argosy()57const testPattern = pattern({58 test: pattern.optional(59 pattern.outputPath('test')60})61service.accept({62 test: (input

Full Screen

Using AI Code Generation

copy

Full Screen

1var path = require('path');2var argosy = require('argosy');3var argosyPattern = require('argosy-pattern');4var outputPath = argosyPattern.outputPath;5var test = argosy();6test.pipe(outputPath(path.resolve(__dirname, 'test')))7 .pipe(test);8test.accept({role: 'test'}, function (msg, cb) {9 cb(null, {result: 'success'});10});11test.act({role: 'test', path: 'test.js'}, function (err, result) {12 if (err) throw err;13 console.log(result);14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosyPattern = require('argosy-pattern')2var pattern = argosyPattern({3})4console.log(pattern.outputPath('foo'))5console.log(pattern.outputPath('bar'))6console.log(pattern.outputPath('baz'))

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run argos automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful