<repo_name>vedhashrees/generator-hapi-restful-version<file_sep>/generators/hapiApiService/index.js
const Path = require("path");
const config = require("konfig")({
    path: Path.join(__dirname, "../config")
}).app;
const baseName = Path.basename(__dirname);
const Generator = require('yeoman-generator');
const { prompt } = require('inquirer');
const Mkdirp = require("mkdirp");
const chalk = require('chalk');

module.exports = class extends Generator {
    constructor(args, opts) {
        super(args, opts);
    }
    askFor() {
        return this.prompt(config.q[baseName]).then((answers) => {
            if (answers.apiPort === "0000") {
                answers.apiPort = Math.floor(Math.random() * 10000 + 1);
            }
            Object.assign(this, answers);
        });
    }
    createProjectWithVersionDir() {
        this.destinationRoot(Path.join(this.appName, "v" + this.apiVersion));
        if (this.fs.exists(this.destinationPath("server.js"))) {
            console.log(chalk.red(`Already project ${chalk.cyan(this.appName)} has found in file system`));
            process.exit(1);
        }
    }
    copyProjectIndexes() {      
        this.fs.copyTpl(
            this.templatePath("_package.json"),
            this.destinationPath('package.json'),
            {
                appName: this.appName,
                appVersion: this.apiVersion
            }
        );
        this.fs.copyTpl(
            this.templatePath("_npm-shrinkwrap.json"),
            this.destinationPath('npm-shrinkwrap.json'),
            {
                appName: this.appName
            }
        );
        this.fs.copy(
            this.templatePath("_README.md"),
            this.destinationPath('README.md')
        );
        this.fs.copyTpl(
            this.templatePath("_server.js"),
            this.destinationPath('server.js'),
            {
                apiPort: this.apiPort,
                apiVersion: this.apiVersion
            }
        );
        this.fs.copy(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js')
        );
        this.fs.copy(
            this.templatePath('.retireignore.json'),
            this.destinationPath('.retireignore.json')
        );
        this.fs.copy(
            this.templatePath('.editorconfig'),
            this.destinationPath('.editorconfig')
        );
        this.fs.copy(
            this.templatePath('LICENSE'),
            this.destinationPath('LICENSE')
        );
    }
    copyDocsDir() {
        this.fs.copy(
            this.templatePath('docs'),
            this.destinationPath('docs')
          );
    }
    createAppConfDirAndCopyAll() {
        this.fs.copyTpl(
            this.templatePath("config/app.json"),
            this.destinationPath('config/app.json'),
            {                
                apiPort: this.apiPort,
                basePrefix: this.basePrefix,
                apiVersion: this.apiVersion
            }
        );
    }
    createAppDefaultModuleAndCopyAll() {
        const filesName = ["router", "validator", "controller", "model", "query"];
        for (let file in filesName) {
            this.fs.copyTpl(
                this.templatePath(`app/modules/default/default-${filesName[file]}.js`),
                this.destinationPath("app/modules/"+ this.defaultModule +"/"+ this.defaultModule + `-${filesName[file]}.js`),
                {   
                    defaultModule: this.defaultModule
                }
            );
        }
    }
    createAppRegisterDirAndCopyAll() {
        this.fs.copy(
            this.templatePath("app/register/app-register.js"),
            this.destinationPath('app/register/app-register.js')
        );
        this.fs.copyTpl(
            this.templatePath("app/register/app-router.js"),
            this.destinationPath('app/register/app-router.js'),
            {   
                defaultModule: this.defaultModule
            }
        );
        this.installDependencies();
    }
}
<file_sep>/generators/hapiApiService/templates/gulpfile.js
const gulp = require("gulp");
const { spawn } = require('child_process');
const gutil = require('gulp-util');

gulp.task("default", () => {
      var child = spawn('retire', [], {
        shell: true,
        cwd: process.cwd()
      });

      child.stdout.setEncoding('utf8');
      child.stdout.on('data', function (data) {
        gutil.log(data);
      });

      child.stderr.setEncoding('utf8');
      child.stderr.on('data', function (data) {
        gutil.log(gutil.colors.red(data));
        gutil.beep();
      });
});

gulp.task('retireWatch', ['default'], function (done) {
  // Watch all javascript files and package.json
  gulp.watch(['app/**/*.js', 'server.js', 'package.json'], ['default']);
});
<file_sep>/generators/hapiApiService/templates/app/modules/default/default-query.js
exports.<%= defaultModule %>Query = {    
    testQuery() {
        return "Hello World";
    }
}
<file_sep>/README.md
# generator-hapi-restful-version
>This is a *yeoman generator* utility module to generate a sample hapi api service project.

#### Note: This is tailored for our project requirements.

## Installation 
  Install the following two packages globally as below.
```sh
 $ npm install yo -g
 $ npm install retire -g
 $ npm install gulp -g
 $ npm install generator-hapi-restful-version -g
```

## Usage:
1) To generate the skeleton of a Hapi REST API service node project , use the following command

```sh
  $ yo hapi-restful-version:hapiApiService
```

![step1](https://user-images.githubusercontent.com/29759244/35551559-b042ce12-05b5-11e8-85ff-eab07e06bb85.PNG)


2) To generate a Hapi REST API service with a new version , use the following command

```sh
  $ yo hapi-restful-version:hapiApiVersion
```

![step2](https://user-images.githubusercontent.com/29759244/35551574-c16dfefa-05b5-11e8-9a67-3fe5d3b15c40.PNG)

3) To generate a Hapi REST API service with a new module , use the following command

```sh
  $ yo hapi-restful-version:hapiApiModule
```

![step3](https://user-images.githubusercontent.com/29759244/35551593-d0cf232e-05b5-11e8-961f-b5cd495c513d.PNG)


4) After the successful creation of new module `eg. auth` ,
goto `app-router.js` file in the folder path  `app/register` and add the following line as below as highlighted in red in the screenshot.

```javascript 
const {authRouter} = require(",,/modules/auth/auth-router");
```

Inside appRouter function add the following line.
```javascript
appRouter(server);
```

![step4](https://user-images.githubusercontent.com/29759244/35551897-5e8a3194-05b7-11e8-88e3-811dbbbf18e1.PNG)

####Note: any project related config values can be initialized in `config\app.json`
To get the configuration values in the project , use as below 
`eg . global.config.app.apiPort`

if the new config file is added in the name of user.json into config directory as `config\user.json`, then use as below  `eg . global.config.user.name`





<file_sep>/generators/hapiApiModule/index.js
const Path = require("path");
const config = require("konfig")({
    path: Path.join(__dirname, "../config")
}).app;
const baseName = Path.basename(__dirname);
const Generator = require('yeoman-generator');
const { prompt } = require('inquirer');
const Mkdirp = require("mkdirp");
const chalk = require('chalk');

module.exports = class extends Generator {
    constructor(args, opts) {
        super(args, opts);
    }
    askFor() {
        return this.prompt(config.q[baseName]).then((answers) => {
            if (answers.apiPort === "0000") {
                answers.apiPort = Math.floor(Math.random() * 10000 + 1);
            }
            Object.assign(this, answers);
        });
    }
    createProjectWithVersionDir() {
        this.destinationRoot();        
    }
    createAppDefaultModuleAndCopyAll() {
        if (this.fs.exists(this.destinationPath(this.defaultModule + "/" + this.defaultModule + `-router.js`))) {
            console.log(chalk.red(`Already api ${chalk.cyan(this.defaultModule)} module has found in file system.`));
            process.exit(1);
        }
        const filesName = ["router", "validator", "controller", "model", "query"];
        for (let file in filesName) {
            this.fs.copyTpl(
                this.templatePath(`app/modules/default/default-${filesName[file]}.js`),
                this.destinationPath(this.defaultModule +"/"+ this.defaultModule + `-${filesName[file]}.js`),
                {   
                    defaultModule: this.defaultModule
                }
            );
        }
    }
}
<file_sep>/generators/hapiApiVersion/templates/app/modules/default/default-model.js
const { <%= defaultModule %>Query } = require("./<%= defaultModule %>-query");
exports.<%= defaultModule %>Model = {
    testModel() {       
        return <%= defaultModule %>Query.testQuery();
    }
};
<file_sep>/generators/hapiApiModule/templates/app/modules/default/default-router.js
exports.<%= defaultModule %>Router = (server) => { 
    const { <%= defaultModule %>Controller } = require("./<%= defaultModule %>-controller");
    const { <%= defaultModule %>Validator } = require("./<%= defaultModule %>-validator");
    // Prefix grouping specific route
    server.realm.modifiers.route.prefix = global.config.app.basePrefix + "/" + global.config.app.apiVersion + "/<%= defaultModule %>";
    server.route([
        { 
            method: "GET",
            path: "/", 
            config: {
                handler: <%= defaultModule %>Controller.test
            }
        }
    ]);
};
<file_sep>/generators/hapiApiModule/templates/app/modules/default/default-validator.js
exports.<%= defaultModule %>Validator = {
    
}
<file_sep>/generators/hapiApiService/templates/app/modules/default/default-controller.js
const { <%= defaultModule %>Model } = require("./<%= defaultModule %>-model");
class <%= defaultModule %>Controller {
    constructor() {
        
    }
    test(request, response) { 
        response("Hello Home Controller v1.0" + <%= defaultModule %>Model.testModel());
    }
}
exports.<%= defaultModule %>Controller = new <%= defaultModule %>Controller();
