├── .gitignore ├── .jshintrc ├── .travis.yml ├── LICENSE ├── README.md ├── bin ├── swagger-project.js └── swagger.js ├── config └── index.js ├── docs ├── README.md ├── adding-paths.md ├── cli.md ├── configuration.md ├── controllers.md ├── images │ ├── overview.png │ ├── overview2.png │ ├── project-call.png │ ├── project-controller.png │ ├── project-create.png │ ├── project-editor.png │ ├── project-hello.png │ ├── project-server.png │ ├── project-start-editor.png │ ├── project-start.png │ ├── swagger-editor.png │ ├── swagger-icon.png │ └── swagger-install.png ├── install.md ├── introduction.md ├── mock-mode.md ├── modules.md ├── quick-start.md ├── release-notes.md ├── report-issues.md ├── swagger-about.md ├── swagger-file.md └── toc.md ├── lib ├── commands │ ├── commands.js │ └── project │ │ ├── project.js │ │ └── swagger_editor.js └── util │ ├── browser.js │ ├── cli.js │ ├── feedback.js │ ├── net.js │ └── spec.js ├── package.json ├── project-skeletons ├── connect │ ├── .gitignore │ ├── README.md │ ├── api │ │ ├── controllers │ │ │ ├── README.md │ │ │ └── hello_world.js │ │ ├── helpers │ │ │ └── README.md │ │ ├── mocks │ │ │ └── README.md │ │ └── swagger │ │ │ └── swagger.yaml │ ├── app.js │ ├── config │ │ ├── README.md │ │ └── default.yaml │ ├── package.json │ └── test │ │ └── api │ │ ├── controllers │ │ ├── README.md │ │ └── hello_world.js │ │ └── helpers │ │ └── README.md ├── express │ ├── app.js │ └── package.json ├── hapi │ ├── app.js │ └── package.json ├── restify │ ├── app.js │ └── package.json └── sails │ ├── .editorconfig │ ├── .gitignore │ ├── .sailsrc │ ├── Gruntfile.js │ ├── README.md │ ├── api │ ├── controllers │ │ ├── .gitkeep │ │ └── hello_world.js │ ├── mocks │ │ └── .gitkeep │ ├── models │ │ └── .gitkeep │ ├── policies │ │ └── sessionAuth.js │ ├── responses │ │ ├── badRequest.js │ │ ├── created.js │ │ ├── forbidden.js │ │ ├── notFound.js │ │ ├── ok.js │ │ └── serverError.js │ ├── services │ │ └── .gitkeep │ └── swagger │ │ └── swagger.yaml │ ├── app.js │ ├── assets │ ├── favicon.ico │ ├── images │ │ └── .gitkeep │ ├── js │ │ └── dependencies │ │ │ └── sails.io.js │ ├── robots.txt │ ├── styles │ │ └── importer.less │ └── templates │ │ └── .gitkeep │ ├── config │ ├── blueprints.js │ ├── bootstrap.js │ ├── connections.js │ ├── cors.js │ ├── csrf.js │ ├── default.yaml │ ├── env │ │ ├── development.js │ │ └── production.js │ ├── globals.js │ ├── http.js │ ├── i18n.js │ ├── local.js │ ├── locales │ │ ├── _README.md │ │ ├── de.json │ │ ├── en.json │ │ ├── es.json │ │ └── fr.json │ ├── log.js │ ├── models.js │ ├── policies.js │ ├── routes.js │ ├── session.js │ ├── sockets.js │ └── views.js │ ├── package.json │ ├── tasks │ ├── README.md │ ├── config │ │ ├── clean.js │ │ ├── coffee.js │ │ ├── concat.js │ │ ├── copy.js │ │ ├── cssmin.js │ │ ├── jst.js │ │ ├── less.js │ │ ├── sails-linker.js │ │ ├── sync.js │ │ ├── uglify.js │ │ └── watch.js │ ├── pipeline.js │ └── register │ │ ├── build.js │ │ ├── buildProd.js │ │ ├── compileAssets.js │ │ ├── default.js │ │ ├── linkAssets.js │ │ ├── linkAssetsBuild.js │ │ ├── linkAssetsBuildProd.js │ │ ├── prod.js │ │ └── syncAssets.js │ ├── test │ ├── api │ │ ├── controllers │ │ │ ├── README.md │ │ │ └── hello_world.js │ │ └── helpers │ │ │ └── README.md │ └── bootstrap.test.js │ └── views │ ├── 403.ejs │ ├── 404.ejs │ ├── 500.ejs │ ├── homepage.ejs │ └── layout.ejs └── test ├── commands ├── commands.js └── project │ ├── badswagger.yaml │ ├── project.js │ └── swagger_editor.js ├── config.js ├── helpers.js ├── project-skeletons ├── common.js └── helpers.js └── util ├── browser.js ├── cli.js └── net.js /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE files 2 | .idea 3 | .vscode 4 | 5 | # Logs 6 | logs 7 | *.log 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # Compiled binary addons (http://nodejs.org/api/addons.html) 24 | build/Release 25 | 26 | # Dependency directory 27 | # Commenting this out is preferred by some people, see 28 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 29 | node_modules 30 | 31 | # Users Environment Variables 32 | .lock-wscript 33 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "bitwise":true, 3 | "curly":true, 4 | "eqeqeq":true, 5 | "forin":true, 6 | "newcap":true, 7 | "noarg":true, 8 | "noempty":true, 9 | "nonew":true, 10 | "undef":true, 11 | "strict":true, 12 | "node":true, 13 | "indent":2, 14 | "expr":true, 15 | "globals" : { 16 | /* MOCHA */ 17 | "describe" : false, 18 | "it" : false, 19 | "before" : false, 20 | "beforeEach" : false, 21 | "after" : false, 22 | "afterEach" : false 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "stable" 4 | - "4" 5 | sudo: false 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Archived 2 | 3 | This GitHub repository has been archived. 4 | The npmjs package `swagger` may be re-used at a later date for a different project. 5 | https://swagger.io/ may have similar or alternative functionality if you depend(ed) on this project. 6 | 7 | 8 | [![Build Status](https://travis-ci.org/swagger-api/swagger-node.svg?branch=master)](https://travis-ci.org/swagger-api/swagger-node) 9 | [![NPM version](https://badge.fury.io/js/swagger.png)](http://badge.fury.io/js/swagger) 10 | [![Dependency Status](https://david-dm.org/swagger-api/swagger-node/status.svg)](https://david-dm.org/swagger-api/swagger-node) 11 | [![devDependency Status](https://david-dm.org/swagger-api/swagger-node/dev-status.svg)](https://david-dm.org/swagger-api/swagger-node#info=devDependencies) 12 | 13 | 14 | The `swagger` module provides tools for designing and building Swagger-compliant APIs entirely in Node.js. It integrates with popular Node.js servers, including Express, Hapi, Restify, and Sails, as well as any Connect-based middleware. With `swagger`, you can specify, build, and test your API from the very beginning, on your laptop. It allows you to change and iterate your design without rewriting the logic of your implementation. 15 | 16 | ![alt text](./docs/images/overview2.png) 17 | 18 | 19 | Remember, one great thing about this approach is that all of the Swagger validation logic is handled for you, and all of the routing logic is managed through the Swagger configuration. You don't have to code (or recode!) any of that stuff yourself. 20 | 21 | # Your swagger API in five steps 22 | 23 | ## 1. Install the swagger module 24 | 25 | Install using npm. For complete instructions, see the [install](./docs/install.md) page. 26 | 27 | ```bash 28 | $ npm install -g swagger 29 | ``` 30 | 31 | ## 2. Create a new swagger project 32 | 33 | Use the [CLI](./docs/cli.md) to create and manage projects. Learn more on the [quick start](./docs/quick-start.md) page. 34 | 35 | ```bash 36 | $ swagger project create hello-world 37 | ``` 38 | 39 | ## 3. Design your API in the Swagger Editor 40 | 41 | The interactive, browser-based [Swagger Editor](http://editor.swagger.io/) is built in. It provides Swagger 2.0 validation and endpoint routing, generates docs on the fly, and consumes easy-to-read YAML. 42 | 43 | ```bash 44 | $ swagger project edit 45 | ``` 46 | 47 | ![screenshot of project editor](./docs/images/project-editor.png) 48 | 49 | ## 4. Write controller code in Node.js 50 | 51 | Code your API's business logic in Node.js. 52 | 53 | ```js 54 | function hello(req, res) { 55 | var name = req.swagger.params.name.value || 'stranger'; 56 | var hello = util.format('Hello, %s!', name); 57 | res.json({ "message": hello }); 58 | } 59 | ``` 60 | 61 | If you look at the Swagger file in the editor (shown in step 3 above), the `x-swagger-router-controller` element (line 17 in the editor screenshot) specifies the name of the controller file associated with the `/hello` path. For example: 62 | 63 | ```yaml 64 | paths: 65 | /hello: 66 | x-swagger-router-controller: hello_world 67 | ``` 68 | 69 | Controller source code is always placed in `./api/controllers`. So, the controller source file for this project is `./api/controllers/hello_world.js`. 70 | 71 | The `operationId` element specifies which controller function to call. In this case (line 19), it is a function called `hello`. Learn [more](./docs/controllers.md). 72 | 73 | ## 5. Run the server 74 | 75 | Run the project server. 76 | 77 | ```bash 78 | $ swagger project start 79 | ``` 80 | 81 | ## Now, call the API! 82 | 83 | It just works! 84 | 85 | ```bash 86 | $ curl http://127.0.0.1:10010/hello?name=Scott 87 | { "message": "Hello, Scott!" } 88 | ``` 89 | 90 | # Installing the swagger module 91 | 92 | See the [Installing swagger](./docs/install.md) for details. 93 | 94 | # Using the swagger module 95 | 96 | Go to the [swagger module doc page](./docs/README.md). It includes all the information you need to get started. 97 | 98 | # About this project 99 | 100 | This initiative grew out of Apigee-127, an API design-first development framework using Swagger. 101 | Apigee donated the code to create the swagger-node project in 2015. 102 | 103 | >Copyright 2016 Apigee Corporation 104 | 105 | >Licensed under the Apache License, Version 2.0 (the "License"); 106 | you may not use this file except in compliance with the License. 107 | You may obtain a copy of the License at 108 | 109 | >http://www.apache.org/licenses/LICENSE-2.0 110 | 111 | >Unless required by applicable law or agreed to in writing, software 112 | distributed under the License is distributed on an "AS IS" BASIS, 113 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 114 | See the License for the specific language governing permissions and 115 | limitations under the License. 116 | 117 | --- 118 | 119 | -------------------------------------------------------------------------------- /bin/swagger-project.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /**************************************************************************** 3 | Copyright 2016 Apigee Corporation 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | ****************************************************************************/ 17 | 'use strict'; 18 | 19 | var app = require('commander'); 20 | var project = require('../lib/commands/project/project'); 21 | var cli = require('../lib/util/cli'); 22 | var execute = cli.execute; 23 | var frameworks = Object.keys(project.frameworks).join('|'); 24 | var assertiontypes = project.assertiontypes.join('|'); 25 | var testmodules = project.testmodules.join('|'); 26 | 27 | app 28 | .command('create [name]') 29 | .description('Create a folder containing a Swagger project') 30 | .option('-f, --framework ', 'one of: ' + frameworks) 31 | .action(execute(project.create)); 32 | 33 | app 34 | .command('start [directory]') 35 | .description('Start the project in this or the specified directory') 36 | .option('-d, --debug [port]', 'start in remote debug mode') 37 | .option('-b, --debug-brk [port]', 'start in remote debug mode, wait for debugger connect') 38 | .option('-m, --mock', 'start in mock mode') 39 | .option('-o, --open', 'open browser as client to the project') 40 | .option('-n, --node-args ', 'run node with extra arguments (like --node-args \"--harmony\")') 41 | .action(execute(project.start)); 42 | 43 | app 44 | .command('verify [directory]') 45 | .description('Verify that the project is correct (swagger, config, etc)') 46 | .option('-j, --json', 'output as JSON') 47 | .action(execute(project.verify)); 48 | 49 | app 50 | .command('edit [directory]') 51 | .description('open Swagger editor for this project or the specified project directory') 52 | .option('-s, --silent', 'do not open the browser') 53 | .option('--host ', 'the hostname the editor is served from') 54 | .option('-p, --port ', 'the port the editor is served from') 55 | .action(execute(project.edit)); 56 | 57 | app 58 | .command('open [directory]') 59 | .description('open browser as client to the project') 60 | .action(execute(project.open)); 61 | 62 | app 63 | .command('test [directory_or_file]') 64 | .description('Run project tests') 65 | .option('-d, --debug [port]', 'start in remote debug mode') 66 | .option('-b, --debug-brk [port]', 'start in remote debug mode, wait for debugger connect') 67 | .option('-m, --mock', 'run in mock mode') 68 | .action(execute(project.test)); 69 | 70 | app 71 | .command('generate-test [directory]') 72 | .description('Generate the test template') 73 | .option('-p, --path-name [path]', 'a specific path of the api, also supports regular expression') 74 | .option('-f, --test-module ', 'one of: ' + testmodules) 75 | .option('-t, --assertion-format ', 'one of: ' + assertiontypes) 76 | .option('-o, --force', 'allow overwriting of all existing test files matching those generated') 77 | .option('-l, --load-test [path]', 'generate load-tests for specified operations') 78 | .action(execute(project.generateTest)); 79 | 80 | app.parse(process.argv); 81 | cli.validate(app); 82 | -------------------------------------------------------------------------------- /bin/swagger.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /**************************************************************************** 3 | Copyright 2016 Apigee Corporation 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | ****************************************************************************/ 17 | 'use strict'; 18 | 19 | var app = require('commander'); 20 | var browser = require('../lib/util/browser'); 21 | var rootCommands = require('../lib/commands/commands'); 22 | var cli = require('../lib/util/cli'); 23 | var execute = cli.execute; 24 | 25 | app.version(require('../lib/util/cli').version()); 26 | 27 | app 28 | .command('project ', 'project actions'); 29 | 30 | app 31 | .command('docs') 32 | .description('open Swagger documentation') 33 | .action(function() { 34 | browser.open('https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md', function() { 35 | process.exit(0); 36 | }); 37 | }); 38 | 39 | app 40 | .command('validate [swaggerFile]') 41 | .description('validate a Swagger document (supports unix piping)') 42 | .option('-j, --json', 'output as JSON') 43 | .action(execute(rootCommands.validate)); 44 | 45 | app 46 | .command('convert [apiDeclarations...]') 47 | .description('Converts Swagger 1.2 documents to a Swagger 2.0 document') 48 | .option('-o, --output-file ', 'specify an output-file to write to') 49 | .action(execute(rootCommands.convert)); 50 | 51 | app.parse(process.argv); 52 | cli.validate(app); -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var path = require('path'); 19 | var _ = require('lodash'); 20 | var debug = require('debug')('swagger'); 21 | 22 | var config = { 23 | rootDir: path.resolve(__dirname, '..'), 24 | userHome: process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], 25 | debug: !!process.env.DEBUG 26 | }; 27 | config.nodeModules = path.resolve(config.rootDir, 'node_modules'); 28 | 29 | module.exports = config; 30 | 31 | // swagger editor // 32 | 33 | config.swagger = { 34 | fileName: 'api/swagger/swagger.yaml', 35 | editorDir: path.resolve(config.nodeModules, 'swagger-editor'), 36 | editorConfig: { 37 | analytics: { google: { id: null } }, 38 | disableCodeGen: true, 39 | disableNewUserIntro: true, 40 | examplesFolder: '/spec-files/', 41 | exampleFiles: [], 42 | autocompleteExtension: {}, 43 | useBackendForStorage: true, 44 | backendEndpoint: '/editor/spec', 45 | backendHealthCheckTimeout: 5000, 46 | useYamlBackend: true, 47 | disableFileMenu: true, 48 | enableTryIt: true, 49 | headerBranding: false, 50 | brandingCssClass: null, 51 | schemaUrl: '/schema/swagger.json', 52 | importProxyUrl: 'https://cors-it.herokuapp.com/?url=' 53 | } 54 | }; 55 | 56 | // project // 57 | 58 | config.project = { 59 | port: process.env.PORT || 10010, 60 | skeletonsDir: path.resolve(__dirname, '..', 'project-skeletons') 61 | }; 62 | 63 | // load env vars // 64 | 65 | _.each(process.env, function(value, key) { 66 | var split = key.split('_'); 67 | if (split[0] === 'swagger') { 68 | var configItem = config; 69 | for (var i = 1; i < split.length; i++) { 70 | var subKey = split[i]; 71 | if (i < split.length - 1) { 72 | if (!configItem[subKey]) { configItem[subKey] = {}; } 73 | configItem = configItem[subKey]; 74 | } else { 75 | configItem[subKey] = value; 76 | } 77 | } 78 | debug('loaded env var: %s = %s', split.slice(1).join('.'), value); 79 | } 80 | }); 81 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Welcome to Swagger! 5 | 6 | ![alt text](./images/swagger-icon.png) 7 | 8 | * [Introduction](./introduction.md) 9 | * [Installation](./install.md) 10 | * [Quick start](./quick-start.md) 11 | * [Configuration](./configuration.md) 12 | * [CLI reference](./cli.md) 13 | * [About Swagger](./swagger-about.md) 14 | * [About the swagger.yaml file](./swagger-file.md) 15 | * [Adding paths](./adding-paths.md) 16 | * [Writing controllers](./controllers.md) 17 | * [Using mock mode](./mock-mode.md) 18 | * [Modules and dependencies](./modules.md) 19 | * [Reporting issues](./report-issues.md) 20 | * [Release Notes](./release-notes.md) 21 | -------------------------------------------------------------------------------- /docs/cli.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Command-line interface reference 5 | 6 | Create, run, and manage Swagger projects from the command line. 7 | 8 | * [swagger](#swagger) 9 | * [project create](#create) 10 | * [project start](#start) 11 | * [project verify](#verify) 12 | * [project edit](#edit) 13 | * [project open](#open) 14 | * [project test](#test) 15 | * [docs](#docs) 16 | 17 | #### swagger 18 | 19 | Options: 20 | 21 | * -h, --help: Outputs usage information. 22 | * -V, --version: Outputs the swagger cli version number. 23 | 24 | Example: 25 | 26 | swagger -V 27 | 0.2.0 28 | 29 | 30 | #### swagger project create [options] [name] 31 | 32 | Creates a folder with the specified [name] containing a new Swagger project. A project skeleton is downloaded from GitHub and installed in the new folder. 33 | 34 | Options: 35 | 36 | * -h, --help: Outputs usage information. 37 | * -f, --framework : Specifies an API framework to use with the project. Choices are connect, express, hapi, restify, or sails. 38 | 39 | Example: 40 | 41 | swagger project create -f express sn-express 42 | ls sn-express 43 | README.md api app.js config node_modules package.json test 44 | 45 | 46 | #### swagger project start [options] [directory] 47 | 48 | Starts the Swagger project in the current (or specified) directory. The server automatically restarts when you make changes to the project. You can also force a restart by typing `rs` on the server command line. 49 | 50 | Options: 51 | 52 | * -h, --help: Outputs usage information. 53 | * -d, --debug : Start in remote debug mode so you can connect to it with a debugger. 54 | * -b, --debug-brk : Start in remote debug mode, wait for debugger. 55 | * -m, --mock: Start in mock mode. For more information, see [Running in mock mode](./mock-mode.md). 56 | * -o, --open: Open the default browser as a client to the project. 57 | * -n, --node-args : Pass extra arguments to node. E.g. `swagger project start --node-args "--harmony"` will run node with [ES6 a.k.a harmony features](https://github.com/joyent/node/wiki/ES6-%28a.k.a.-Harmony%29-Features-Implemented-in-V8-and-Available-in-Node) enabled. 58 | 59 | Example: 60 | 61 | cd ./myproject 62 | swagger project start -m 63 | 64 | 65 | #### swagger project verify [options] [project root directory] 66 | 67 | Verifies that the project in the current (or specified) directory is correct. Reports errors and warnings from the Swagger model, project configuration, etc. 68 | 69 | Options: 70 | 71 | * -h, --help: Outputs usage information. 72 | * -j, --json: Output information in JSON format. 73 | 74 | Example: 75 | 76 | cd ./myproject 77 | swagger project verify 78 | Project Errors 79 | -------------- 80 | #/: Missing required property: paths 81 | #/: Additional properties not allowed: aths 82 | Results: 2 errors, 0 warnings 83 | 84 | 85 | 86 | #### swagger project edit [options] [directory] 87 | 88 | Opens the project in the current (or specified) directory in the [Swagger Editor](https://github.com/swagger-api/swagger-editor). 89 | 90 | ![alt text](./images/swagger-editor.png) 91 | 92 | Options: 93 | 94 | * -h, --help: Outputs usage information. 95 | * -s, --silent: Do not open the browser. 96 | * --host : The hostname the editor is served from (default: 127.0.0.1). 97 | * -p, --port : The port the editor is served from (default: random port). 98 | 99 | Example: 100 | 101 | cd ./myproject 102 | swagger project edit 103 | 104 | 105 | #### swagger project open [directory] 106 | 107 | Opens the browser as a client to the current or specified project. 108 | 109 | Options: 110 | 111 | * -h, --help: Outputs usage information. 112 | 113 | Example: 114 | 115 | `swagger project open ./myproject` 116 | 117 | 118 | 119 | #### swagger project test [options] [directory-or-file] 120 | 121 | Runs project tests. 122 | 123 | Options: 124 | 125 | * -h, --help: Outputs usage information. 126 | * -d, --debug : Start in remote debug mode so you can connect to it with a debugger. 127 | * -b, --debug-brk : Start in remote debug mode, wait for debugger. 128 | * -m, --mock: Start in mock mode. For more information, see [Running in mock mode](./mock-mode.md). 129 | 130 | Example: 131 | 132 | `swagger project test` 133 | 134 | controllers 135 | hello_world 136 | GET /hello 137 | ✓ should return a default string 138 | ✓ should accept a name parameter 139 | 2 passing (27ms) 140 | 141 | 142 | ##### swagger docs 143 | 144 | Opens the OpenAPI 2.0 Specification in your browser. 145 | 146 | Example: 147 | 148 | swagger docs 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /docs/controllers.md: -------------------------------------------------------------------------------- 1 | 2 | ## About controllers 3 | 4 | * [Implementing a controller](#implementing) 5 | * [Using query parameters](#query) 6 | * [Weather API example](#weather) 7 | 8 | ### Implementing a controller 9 | 10 | This topic explains how to implement a controller. The `x-swagger-router-controller` Swagger extension element is used to specify the name of a controller file. The quick start example defines a `hello_world` controller file, which is by default in `api/controllers/hello_world.js`. 11 | 12 | ```yaml 13 | paths: 14 | /hello: 15 | # binds swagger app logic to a route 16 | x-swagger-router-controller: hello_world 17 | ``` 18 | 19 | By default, controller method names map to the HTTP operation names, like get() or post(). But you can specify any name you wish with the `operationId` element. In the following example, a GET request results in calling the hello() method in the controller. 20 | 21 | ```yaml 22 | get: 23 | description: Returns 'Hello' to the caller 24 | # used as the method name of the controller 25 | operationId: hello 26 | ``` 27 | 28 | Here is the `hello_world.js` implementation for the quick start example. It retrieves the query parameter value and returns a response. 29 | 30 | ```javascript 31 | var util = require('util'); 32 | 33 | module.exports = { 34 | hello: hello 35 | }; 36 | 37 | function hello(req, res) { 38 | var name = req.swagger.params.name.value || 'stranger'; 39 | var hello = util.format('Hello, %s!', name); 40 | res.json({ "message": hello }); 41 | } 42 | ``` 43 | 44 | ### Using query parameters 45 | 46 | In the controller code, we obtained the value of a query parameter and echoed it back in the response. We used the `req.swagger` object to obtain access to the query parameters. You declare query parameters in the paths section of the project's Swagger definition. For example: 47 | 48 | ```yaml 49 | parameters: 50 | - name: name 51 | in: query 52 | description: The name of the person to whom to say hello 53 | required: false 54 | type: string 55 | ``` 56 | 57 | The req.swagger object is populated by the swagger-tools middleware component of swagger. To read more about this object, see the [Swagger tools middleware documentation](https://github.com/apigee-127/swagger-tools/blob/master/docs/Middleware.md). 58 | 59 | ### Weather API example 60 | 61 | Let's look at an example controller for a simple weather API. 62 | 63 | The Weather API requires a controller function that takes in request and response objects, queries the Open Weather Map API using the `city` query parameter and returns the current weather conditions. 64 | 65 | Note that Open Weather returns a JSON object. Also, we'll need to export the controller function so that it is available to the outside world. 66 | 67 | We will use the `request` library to make the request. So, ensure it is installed and added to `package.json`: 68 | 69 | ``` 70 | npm install request --save 71 | ``` 72 | 73 | >Note: If a controller requires additional Node.js modules, be sure to add them to your `package.json` file and execute `npm install`. 74 | 75 | In the Swagger file, you can see that when a GET is performed on `/weather`, the target controller file is `api/controllers/weather.js`, and the target method to call is `getWeatherByCity()`: 76 | 77 | ```yaml 78 | paths: 79 | /weather: 80 | x-swagger-router-controller: weather 81 | get: 82 | description: "Returns current weather in the specified city to the caller" 83 | operationId: getWeatherByCity 84 | parameters: 85 | - name: city 86 | in: query 87 | description: "The city you want weather for in the form city,state,country" 88 | required: true 89 | type: "string" 90 | ``` 91 | 92 | Here is the controller implementation for the `getWeatherByCity` function: 93 | 94 | ```javascript 95 | 'use strict'; 96 | 97 | var util = require('util'); 98 | var request = require('request'); 99 | 100 | module.exports = { 101 | getWeatherByCity: getWeatherByCity 102 | } 103 | 104 | function getWeatherByCity(req, res) { 105 | var city = req.swagger.params.city.value; 106 | var url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&units=imperial"; 107 | console.log('Executing request: '+url); 108 | request.get(url).pipe(res); 109 | }; 110 | ``` 111 | 112 | 113 | Here is how you call the Weather API, which returns data for a specified city. 114 | 115 | ```bash 116 | curl http://localhost:10010/weather\?city\=San%20Jose,CA 117 | ``` 118 | 119 | -------------------------------------------------------------------------------- /docs/images/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/overview.png -------------------------------------------------------------------------------- /docs/images/overview2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/overview2.png -------------------------------------------------------------------------------- /docs/images/project-call.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-call.png -------------------------------------------------------------------------------- /docs/images/project-controller.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-controller.png -------------------------------------------------------------------------------- /docs/images/project-create.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-create.png -------------------------------------------------------------------------------- /docs/images/project-editor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-editor.png -------------------------------------------------------------------------------- /docs/images/project-hello.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-hello.png -------------------------------------------------------------------------------- /docs/images/project-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-server.png -------------------------------------------------------------------------------- /docs/images/project-start-editor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-start-editor.png -------------------------------------------------------------------------------- /docs/images/project-start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/project-start.png -------------------------------------------------------------------------------- /docs/images/swagger-editor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/swagger-editor.png -------------------------------------------------------------------------------- /docs/images/swagger-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/swagger-icon.png -------------------------------------------------------------------------------- /docs/images/swagger-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/docs/images/swagger-install.png -------------------------------------------------------------------------------- /docs/install.md: -------------------------------------------------------------------------------- 1 | 2 | ## Installing swagger 3 | 4 | * [Prerequisites](#prereqs) 5 | * [Installing with npm](#install) 6 | * [Using npm without sudo](#nosudo) 7 | * [Configuring the default browser in Linux](#defaultbrowser) 8 | 9 | ### Prerequisites 10 | 11 | * [Node.js](http://nodejs.org/download/) (v0.10.24+) 12 | * [npm](https://docs.npmjs.com/getting-started/installing-node) (v1.3.0+) 13 | 14 | ### Installing with npm 15 | 16 | The `swagger` module is designed for Node.js and is available through npm. 17 | 18 | #### Installing on Linux / Mac 19 | 20 | Here's how you install with `sudo`. If you do not wish to use `sudo`, see [Using npm without sudo](#nosudo) below. 21 | 22 | 1. Open a terminal. 23 | 2. Run the install: 24 | 25 | `sudo npm install -g swagger` 26 | 27 | **Note**: `sudo` may or may not be required with the `-g` option depending on your configuration. If you do not use `-g`, you may need to add the `swagger/bin` directory to your PATH manually. On Unix-based machines 28 | the bin directory will often be found here: `/usr/local/lib/node_modules/swagger/bin`. 29 | 30 | #### Installing on Windows 31 | 32 | 1. Open a terminal. 33 | 2. Run the install: 34 | 35 | `npm install -g swagger` 36 | 37 | ## Using npm without sudo 38 | 39 | If you don't want to use sudo to install swagger on your system, follow the instructions in this section. 40 | 41 | #### Overview 42 | 43 | By default npm will place 'global' modules installed with the `-g` flag in `/usr/local/lib/node_modules` using the default prefix of `/usr/local`. Global executables would be placed in `/usr/local/bin` using the same default prefix, thereby putting them on the default PATH in most cases. In order to write to both of these directories root permissions are required. 44 | 45 | Many Node.js developers choose to use a different prefix such that they do not need to use root permissions to install modules using the `-g` flag (rightfully so - you should always be wary about things that 'require root permissions'!). Using root permissions is effectively a shortcut. In order to use executables installed using a different prefix you need to add an element to your path. 46 | 47 | #### Steps 48 | 49 | 1. Set the 'prefix' for npm by using the following command (documented here: [npm-config](https://www.npmjs.org/doc/misc/npm-config.html). This will create a file `~/.npmrc` that contains configuration information for npm. 50 | 51 | ```bash 52 | npm set prefix ~/npm 53 | ``` 54 | 55 | 2. Edit your `.bash_profile` or the appropriate shell initialization script to add `~/npm` to your `PATH` by adding the following line (or placing the single line in the new file if it does not exist): 56 | 57 | ```bash 58 | PATH=~/npm/bin:$PATH 59 | ``` 60 | 61 | This will enable you to easily use executable scripts installed using `-g` through npm - both for swagger and for other tools as well! 62 | 63 | ###Configuring the default browser on Linux 64 | 65 | On Linux platforms, you need to specify your browser path before using the Swagger editor. 66 | 67 | 1. Create or open the following file in a text editor: 68 | 69 | `~/.a127/config.js` 70 | 71 | 2. Add the following contents to the file: 72 | 73 | ```javascript 74 | module.exports = { 75 | browser: 'the/path/to/your/browser' 76 | }; 77 | ``` 78 | -------------------------------------------------------------------------------- /docs/introduction.md: -------------------------------------------------------------------------------- 1 | ## What is the swagger module? 2 | The swagger module provides tools for designing and building APIs entirely in Node.js. It integrates with popular Node.js servers, including Express, hapi, restify, and Sails, as well as any Connect-based middleware. With swagger, you can specify, build, and test your API from the very beginning, and it allows you to make changes to your design without rewriting the logic of your implementation. It explicitly isolates the design of your interfaces from writing your controller code, leading to a much better software development lifecycle. 3 | 4 | * [The API-First Development Process](#sdlc) 5 | * [Reporting issues](#gethelp) 6 | 7 | ### The API-First Development Process 8 | API design is a discovery process. Swagger development begins with design tooling, and it expects that you will evolve your interface over time. It gracefully handles the routing of interfaces to controllers so that you can make changes to your interfaces without clobbering any of your implementation logic. 9 | 10 | Designing an API specification is like writing a contract. As you write the spec in YAML using [Swagger 2.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md), your API documentation is generated in real-time, allowing the client and server teams to agree on how their systems will work together. 11 | 12 | Once you have defined your first operation, it drives a mock server, which enables client development happen in parallel with server development. As you build the client, you will discover further changes you'll need to make to your APIs, meaning another iteration of the specification. 13 | 14 | * Defining your API specification using the Swagger Editor (included with swagger). 15 | 16 | *The Swagger Editor* 17 | ![alt text](./images/swagger-editor.png) 18 | 19 | Write your specification in YAML on the left, and see the API documentation in real-time on the right. Auto-completion makes it easy to learn the syntax, and validation helps you correct any syntactic or semantic errors you might make along the way. 20 | 21 | * Use the `x-swagger-router-controller` extension to annotating your paths and operations. This maps the interface onto the name of the controller file that implements the logic behind the operation. For example: 22 | 23 | ```yaml 24 | paths: 25 | /hello: 26 | x-swagger-router-controller: "hello_world" 27 | ``` 28 | 29 | * Use the operationId property to specify which controller method to call for the given path: 30 | 31 | ```yaml 32 | get: 33 | description: "Returns 'Hello' to the caller" 34 | operationId: "hello" 35 | ``` 36 | 37 | * Implement your controller files in Node.js and place them in `/api/controllers`. For example: `/api/controllers/hello_world.js` 38 | 39 | * Behind the scenes, swagger wires up your app, routing HTTP requests to specific Node.js controller files. 40 | 41 | * At runtime swagger-tools middleware validates the request before sending it to the `hello` operation of the `hello_world` controller. 42 | 43 | * Finally, the controller logic associated with the requested path is executed. 44 | 45 | ### Reporting issues 46 | Have an issue to report? See the [Reporting issues](./report-issues.md). 47 | -------------------------------------------------------------------------------- /docs/modules.md: -------------------------------------------------------------------------------- 1 | ## swagger modules and dependencies 2 | 3 | This topic briefly describes the relevant Node.js modules on which a swagger project depends. 4 | 5 | * [swagger](#swagger) 6 | * [skeleton](#skeleton) 7 | * [swagger-editor](#swagger-editor) 8 | * [swagger-tools](#swagger-tools) 9 | 10 | ### swagger 11 | 12 | The `swagger` npm module provides everything you need to create new projects, including the Swagger editor, Swagger Tools middleware, sample project skeletons, and the `swagger` command-line tools. 13 | 14 | #### Installation 15 | For installation instructions, see "[Installation](./install.md)". 16 | 17 | #### Documentation 18 | 19 | The main source of documentation for the swagger module and related components is in the swagger-node repository on GitHub. 20 | 21 | #### Installation 22 | 23 | The swagger command-line tools are installed with swagger. 24 | 25 | #### Documentation 26 | 27 | [swagger command-line reference](./cli.md) 28 | 29 | 30 | ### skeleton 31 | 32 | A basic, "hello world" swagger project. This project automatically cloned when you create a new swagger project by executing `swagger project create`. Skeleton projects are implemented for specific API frameworks, such as express, restify, or others. 33 | 34 | #### Documentation 35 | 36 | See the swagger "[Quick start](./quick-start.md)" to see how easy it is to get a new swagger API project up and running. 37 | 38 | ### swagger-editor 39 | 40 | The Swagger Editor lets you design your API specification and interactively preview its documentation for your swagger API project. 41 | 42 | #### Installation 43 | 44 | Standard npm install. Installed with swagger. 45 | 46 | #### Documentation 47 | 48 | See "[Swagger Editor](https://github.com/swagger-api/swagger-editor)" on GitHub. 49 | 50 | ### swagger-tools 51 | 52 | Middleware for Node.js including Message Validation, Authorization and Routing. 53 | 54 | #### Installation 55 | 56 | Standard npm install. Installed with swagger. 57 | 58 | #### Documentation 59 | 60 | See the `swagger-tools` [README](https://github.com/apigee-127/swagger-tools) on GitHub. 61 | 62 | 63 | #### Swagger Tools middleware components 64 | 65 | Swagger tools provides these middleware components. They provide services for message validation, authorization, and routing. 66 | 67 | * swagger-metadata 68 | * swagger-router 69 | * swagger-validator 70 | -------------------------------------------------------------------------------- /docs/quick-start.md: -------------------------------------------------------------------------------- 1 | ## Quick start 2 | 3 | Let's see how easily and quickly you can get a simple API up and running using swagger. 4 | 5 | * [Get an API up and running](#upandrunning) 6 | * [Check out the main Node.js app file](#main) 7 | * [Open the Swagger editor](#openeditor) 8 | * [Windows users](#windows) 9 | 10 | ### Get an API up and running 11 | 12 | First, we create a new swagger project and test a simple "hello world" API. 13 | 14 | 1. Install swagger, as described in the [installation guide](install.md). 15 | 16 | 2. Create swagger project directory and cd to it. This is where you'll create your first project. 17 | 18 | 3. Execute the project create command: 19 | 20 | `swagger project create hello-world` 21 | 22 | 4. Pick the API framework you want to use. We're going to pick express, but you can pick any of the listed frameworks: 23 | ``` 24 | ? Framework? (Use arrow keys) 25 | connect 26 | ❯ express 27 | hapi 28 | restify 29 | sails 30 | ``` 31 | Note: You must enter the number of the option. 32 | 33 | 5. swagger creates a skeleton project that's pre-configured to use your selected framework (in this example, Express). It then runs `npm install` to pick up the dependencies. 34 | 35 | Note: Windows users see the [note below](#windows-note) regarding npm. 36 | 37 | 6. Change to the new project directory: `cd hello-world` 38 | 39 | 7. Type `swagger project start` to start your API. You now have an API running with swagger! 40 | 41 | 8. In another terminal, run this command: 42 | 43 | `curl http://127.0.0.1:10010/hello?name=Scott` 44 | 45 | And, you'll get back the response `{ "message": "Hello, Scott!" }`. 46 | 47 | That's it - You have now created, started and tested your first API project with swagger! 48 | 49 | ### Check out the main Node.js app file 50 | 51 | Open /app.js in an editor. This is the main Node.js app that installs middleware and requires the API framework that you chose when you created your project. 52 | 53 | The middleware modules perform tasks like OpenAPI Specification validation and endpoint routing. For more information, see [swagger modules and dependencies](./modules.md). 54 | 55 | ### Open the Swagger editor 56 | 57 | The Swagger editor lets you design and test your API interactively. While you design and test, the API documentation is generated automatically for you. 58 | 59 | Now that we've got our basic API running, let's open the Swagger editor. 60 | 61 | 1. Be sure you're in your project root directory: `./hello-world`. 62 | 63 | 2. Fire up the editor: `swagger project edit` 64 | 65 | *The Swagger editor* 66 | ![alt text](./images/swagger-editor.png) 67 | 68 | ### Running Swagger Node in a Deployment 69 | 70 | When you run a swagger-node based application in a proper deployment, you should use `node ` (typically, `node app.js`) as opposed to using the swagger cli tooling. 71 | 72 | ### Windows users 73 | For some versions of npm on Windows will have problems on the `npm install` step of `swagger project create`. They are related to a `debug` module on npm not being managed properly. The following steps should resolve this issue: 74 | 75 | 1. In the project directory, execute the following commands: 76 | 1. `npm install yamljs` 77 | 2. `npm install debug` 78 | 3. `npm install swagger-tools` 79 | 80 | Now, when you run `swagger project start` your project should start successfully. 81 | -------------------------------------------------------------------------------- /docs/release-notes.md: -------------------------------------------------------------------------------- 1 | ## Release Notes 2 | 3 | ### swagger-node 0.7.0, swagger-node-runner 0.5.0 4 | 5 | #### New features 6 | 7 | * Request handing pipeline is now fully configurable 8 | * Application configuration is now driven by the [config module](https://github.com/lorenwest/node-config/wiki/Configuration-Files) to allow a ton of flexibility in setting up configurations and routes based on environment. 9 | * Supports plugins such as [volos-swagger-oauth](https://www.npmjs.com/package/volos-swagger-oauth) and [volos-swagger-apply](https://www.npmjs.com/package/volos-swagger-apply) 10 | * Custom security handlers can be declared in config in app.js. Example: 11 | 12 | ```javascript 13 | config.swaggerSecurityHandlers = { 14 | oauth2: function securityHandler1(req, authOrSecDef, scopesOrApiKey, cb) { 15 | // your security code 16 | cb(); 17 | } 18 | }; 19 | ``` 20 | 21 | #### Bug Fixes 22 | 23 | * json_error_handler should work in all container environments (mapErrorsToJson did not) 24 | 25 | #### Breaking Changes 26 | 27 | * `mapErrorsToJson` config option is now configured as an onError handler: `onError: json_error_handler` 28 | * `docEndpoints` raw config option is now declared in Swagger and handled via a pipe: `swagger_raw` 29 | 30 | #### Converting From Previous Version 31 | 32 | 1. Update your package.json to use the new middleware versions: "^0.1.0". (eg. `"swagger-express-mw": "^0.1.0"`) 33 | 2. Update your application dependencies: `npm update`. 34 | 3. Existing config should generally work, but you should update your config to the [new format](https://github.com/swagger-api/swagger-node/blob/master/docs/cli.md/configuration.md). 35 | -------------------------------------------------------------------------------- /docs/report-issues.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Reporting issues with swagger 4 | 5 | swagger is an open source project and we use GitHub issues for tracking problems with the code: 6 | 7 | ### Swagger Editor 8 | **Issue Tracker:** https://github.com/wordnik/swagger-editor/issues 9 | 10 | ### Swagger Tools 11 | **Issue Tracker:** https://github.com/apigee-127/swagger-tools/issues 12 | 13 | ### Swagger Command Line 14 | **Issue Tracker:** https://github.com/swagger-api/swagger-node/issues 15 | -------------------------------------------------------------------------------- /docs/swagger-about.md: -------------------------------------------------------------------------------- 1 | ## About swagger 2 | 3 | * [What is Swagger?](#whatisswagger) 4 | * [How does the swagger module use Swagger?](#howdoes) 5 | * [Help me with YAML](#helpwith) 6 | * [Next step](#nextstep) 7 | 8 | 9 | ### What is Swagger? 10 | 11 | [Swagger™ ](http://swagger.io) is a specification and framework implementation for describing, producing, consuming, and visualizing RESTful web services. 12 | 13 | To read more about Swagger, refer to: 14 | 15 | * [The Swagger website](http://swagger.io) 16 | * [Swagger on GitHub](https://github.com/swagger-api) 17 | 18 | 19 | ### How does the swagger module use Swagger? 20 | 21 | The Swagger Editor lets you design your API specification and preview its documentation for your swagger API. The editor is installed with swagger. 22 | 23 | A swagger.yaml file is installed into every new swagger project, and lives in `/api/swagger/swagger.yaml`. It conforms to the [OpenAPI 2.0 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md). 24 | 25 | Behind the scenes, Swagger middleware validates and processes the Swagger configuration file, and routes API operation endpoints to controller files. All **you** need to do is implement your custom API controller logic. 26 | 27 | >Note: The editor is served locally and automatically saves your work *as you edit*. In addition, if the project is running (`swagger project start`), it is automatically restarted each time the editor saves. Just be careful if you kill the editor, that you do not lose unsaved work. 28 | 29 | **Try it:** 30 | 31 | 1. `swagger project create test-project` 32 | 2. `cd test-project` 33 | 2. `swagger project edit` 34 | 35 | *The Swagger editor* 36 | ![alt text](./images/swagger-editor.png) 37 | 38 | 39 | ### Help me with YAML 40 | 41 | YAML is a data serialization/representation standard. If you're new to YAML, check out [www.yaml.org](http://www.yaml.org). Another excellent introduction is the [Wikipedia YAML entry](http://en.wikipedia.org/wiki/YAML). 42 | 43 | YAML is intended to be easy for humans to read. Every swagger project includes a Swagger 2.0 compliant configuration file that is written in YAML. 44 | 45 | ### Next step 46 | 47 | For a more detailed look the Swagger configurations, see "[The OpenAPI Specification file](./swagger-file.md)". 48 | -------------------------------------------------------------------------------- /docs/swagger-file.md: -------------------------------------------------------------------------------- 1 | ## Understanding the OpenAPI Specification file 2 | 3 | * [Intro](#intro) 4 | * [Default swagger project file](#default) 5 | * [OpenAPI Specification elements](#reference) 6 | 7 | ### Intro 8 | 9 | When you execute `swagger project create myproject`, a default Swagger model is placed in `myproject/api/swagger/swagger.yaml`. This model conforms to the [OpenAPI 2.0 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md). 10 | 11 | >Note: For a quick intro to swagger, see "[What is Swagger](./swagger-about.md)". 12 | 13 | ### Default swagger project file 14 | 15 | Here is the entire `swagger.yaml` file that is provisioned for a new swagger project: 16 | 17 | ```yaml 18 | swagger: "2.0" 19 | info: 20 | version: "0.0.1" 21 | title: Hello World App 22 | # during dev, should point to your local machine 23 | host: localhost 24 | # basePath prefixes all resource paths 25 | basePath: / 26 | # 27 | schemes: 28 | # tip: remove http to make production-grade 29 | - http 30 | - https 31 | # format of bodies a client can send (Content-Type) 32 | consumes: 33 | - application/json 34 | # format of the responses to the client (Accepts) 35 | produces: 36 | - application/json 37 | paths: 38 | /hello: 39 | # binds swagger app logic to a route 40 | x-swagger-router-controller: hello_world 41 | get: 42 | description: Returns 'Hello' to the caller 43 | # used as the method name of the controller 44 | operationId: hello 45 | parameters: 46 | - name: name 47 | in: query 48 | description: The name of the person to whom to say hello 49 | required: false 50 | type: string 51 | responses: 52 | "200": 53 | description: Success 54 | schema: 55 | # a pointer to a definition 56 | ``` 57 | 58 | 59 | ### OpenAPI Specification elements 60 | 61 | The Swagger file includes a number of standard OpenAPI 2.0 Specification elements. You can read about them in the [OpenAPI 2.0 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md). 62 | 63 | Here's a brief description of the elements in a swagger project file: 64 | 65 | * **swagger: 2.0** - (Required) Identifies the version of the OpenAPI Specification (2.0). 66 | 67 | * **info:** - (Required) Provides metadata about the API. 68 | 69 | * **host:** - (Optional) The host serving the API. By default, a new project connects to a server running locally on port 10010. 70 | 71 | * **basePath:** - (Optional) The base path on which the API is served, which is relative to the host. 72 | 73 | * **schemes:** - (Optional) A list of transfer protocol(s) of the API. 74 | 75 | * **consumes:** - (Optional) A list of MIME types the APIs can consume. 76 | 77 | * **produces:** - (Optional) A list of MIME types the APIs can produce. 78 | 79 | * **paths:** - (Required) Defines the available operations on the API. You'll spend most of your time configuring the paths part of the file. You can read about the path element in the [OpenAPI 2.0 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md). In general, the paths section specifies an operation's verb (like `get`), the endpoint for an API operation (like `/hello`), query parameters, and responses. 80 | 81 | * **definitions:** - (Optional) These represent the structure of complex objects such as request and response bodies. For example, you might have a collection of `/users` that returns an array of `user` objects. You would describe these with two definitions: 1) to describe the `User` object, and 2) the definition of the `Users` array. Swagger uses [JSON-schema](http://json-schema.org/). 82 | 83 | * **x-swagger-router-controller:** - (Optional) This extension specifies the name of the controller file (hello_world.js) that will execute when this API operation is called. Controller files reside in `apis/controllers` in your swagger project. This extension is provided through the [`swagger-tools`](https://github.com/apigee-127/swagger-tools) middleware module. 84 | 85 | -------------------------------------------------------------------------------- /docs/toc.md: -------------------------------------------------------------------------------- 1 | 2 | ## Table of contents 3 | 4 | ![alt text](./images/swagger-icon.png) 5 | 6 | * [Introduction](./introduction.md) 7 | * [Installation](./install.md) 8 | * [Quick start](./quick-start.md) 9 | * [CLI reference](./cli.md) 10 | * [About Swagger](./swagger-about.md) 11 | * [About the swagger.yaml file](./swagger-file.md) 12 | * [Adding paths](./adding-paths.md) 13 | * [Writing controllers](./controllers.md) 14 | * [Using mock mode](./mock-mode.md) 15 | * [Modules and dependencies](./modules.md) 16 | * [Reporting issues](./report-issues.md) -------------------------------------------------------------------------------- /lib/commands/commands.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /**************************************************************************** 3 | Copyright 2016 Apigee Corporation 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | ****************************************************************************/ 17 | 'use strict'; 18 | 19 | var swaggerConverter = require('swagger-converter'); 20 | var swaggerSpec = require('../util/spec'); 21 | var yaml = require('js-yaml'); 22 | var join = require('path').join; 23 | var fs = require('fs'); 24 | 25 | var convert = function convert(filePath, apiDeclarations, options, cb) { 26 | if (filePath) { 27 | if (!fs.existsSync(join(process.cwd(), filePath))) { 28 | return cb(error); 29 | } 30 | 31 | var resource = fs.readFileSync(join(process.cwd(), filePath), 'utf8'); 32 | var json; 33 | 34 | try { 35 | json = JSON.parse(resource); 36 | } catch (error) { 37 | return cb(error); 38 | } 39 | 40 | var declarations = []; 41 | var tempJson; 42 | 43 | apiDeclarations.forEach(function(currentValue) { 44 | if (!fs.existsSync(join(process.cwd(), currentValue))) { 45 | return cb(error); 46 | } 47 | 48 | try { 49 | tempJson = JSON.parse(fs.readFileSync(join(process.cwd(), currentValue), 'utf8')) 50 | } catch (error) { 51 | return cb(error); 52 | } 53 | 54 | declarations.push(tempJson); 55 | }); 56 | 57 | var swagger2 = yaml.safeDump(swaggerConverter(json, declarations)); 58 | 59 | if (options.outputFile) { 60 | fs.writeFile(join(process.cwd(), options.outputFile), swagger2, function(err) { 61 | if (err) {return cb(err);} 62 | }); 63 | } else { 64 | cb(null, swagger2); 65 | } 66 | } 67 | } 68 | 69 | var validate = function validate(file, options, cb) { 70 | 71 | if (!file) { // check stream 72 | process.stdin.resume(); 73 | process.stdin.setEncoding('utf8'); 74 | process.stdin.on('data', function(data) { 75 | if (!data) { process.exit(1); } 76 | swaggerSpec.validateSwagger(parse(data), options, cb); 77 | }); 78 | } else { 79 | var data = fs.readFileSync(file, 'utf8'); 80 | swaggerSpec.validateSwagger(parse(data), options, cb); 81 | } 82 | } 83 | 84 | function parse(data) { 85 | if (isJSON(data)) { 86 | return JSON.parse(data); 87 | } else { 88 | return yaml.safeLoad(data); 89 | } 90 | } 91 | 92 | function isJSON(data) { 93 | return data.match(/^\s*\{/); 94 | } 95 | 96 | module.exports = { 97 | convert: convert, 98 | validate: validate 99 | } 100 | -------------------------------------------------------------------------------- /lib/commands/project/swagger_editor.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var config = require('../../../config'); 19 | var emit = require('../../util/feedback').emit; 20 | var browser = require('../../util/browser'); 21 | var util = require('util'); 22 | var path = require('path'); 23 | var serveStatic = require('serve-static'); 24 | var fs = require('fs'); 25 | 26 | // swagger-editor must be served from root 27 | var SWAGGER_EDITOR_SERVE_PATH = '/'; 28 | 29 | // swagger-editor expects to GET the file here 30 | var SWAGGER_EDITOR_LOAD_PATH = '/editor/spec'; 31 | 32 | // swagger-editor PUTs the file back here 33 | var SWAGGER_EDITOR_SAVE_PATH = '/editor/spec'; 34 | 35 | // swagger-editor GETs the configuration files 36 | var SWAGGER_EDITOR_CONFIG_PATH = '/config/defaults.json'; 37 | 38 | module.exports = { 39 | edit: edit 40 | }; 41 | 42 | function edit(project, options, cb) { 43 | 44 | var swaggerFile = path.resolve(project.dirname, config.swagger.fileName); 45 | var app = require('connect')(); 46 | 47 | // save the file from swagger-editor 48 | app.use(SWAGGER_EDITOR_SAVE_PATH, function(req, res, next) { 49 | if (req.method !== 'PUT') { return next(); } 50 | var stream = fs.createWriteStream(swaggerFile); 51 | req.pipe(stream); 52 | 53 | stream.on('finish', function() { 54 | res.end('ok'); 55 | }) 56 | }); 57 | 58 | // retrieve the project swagger file for the swagger-editor 59 | app.use(SWAGGER_EDITOR_LOAD_PATH, serveStatic(swaggerFile) ); 60 | 61 | app.use(SWAGGER_EDITOR_CONFIG_PATH, function(req, res, next) { 62 | if (req.method !== 'GET') { return next(); } 63 | res.end(JSON.stringify(config.swagger.editorConfig)); 64 | }); 65 | 66 | // serve swagger-editor 67 | app.use(SWAGGER_EDITOR_SERVE_PATH, serveStatic(config.swagger.editorDir)); 68 | 69 | 70 | // start // 71 | 72 | var http = require('http'); 73 | var server = http.createServer(app); 74 | var port = options.port || 0; 75 | var hostname = options.host || '127.0.0.1'; 76 | server.listen(port, hostname, function() { 77 | port = server.address().port; 78 | var editorUrl = util.format('http://%s:%d/#/edit', hostname, port); 79 | var editApiUrl = util.format('http://%s:%d/editor/spec', hostname, port); 80 | var dontKillMessage = 'Do not terminate this process or close this window until finished editing.'; 81 | emit('Starting Swagger Editor.'); 82 | 83 | if (!options.silent) { 84 | browser.open(editorUrl, function(err) { 85 | if (err) { return cb(err); } 86 | emit(dontKillMessage); 87 | }); 88 | } else { 89 | emit('Running Swagger Editor API server. You can make GET and PUT calls to %s', editApiUrl); 90 | emit(dontKillMessage) 91 | } 92 | }); 93 | } 94 | -------------------------------------------------------------------------------- /lib/util/browser.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var Child = require('child_process'); 19 | var config = require('../../config'); 20 | var emit = require('./feedback').emit; 21 | 22 | var platformOpeners = { 23 | 24 | darwin: 25 | function(url, cb) { 26 | var browser = escape(config.browser); 27 | if (browser) { 28 | open('open -a ' + browser, url, cb); 29 | } else { 30 | open('open', url, cb); 31 | } 32 | }, 33 | 34 | win32: 35 | function(url, cb) { 36 | var browser = escape(config.browser); 37 | if (browser) { 38 | open('start "" "' + browser + '"', url, cb); 39 | } else { 40 | open('start ""', url, cb); 41 | } 42 | }, 43 | 44 | linux: 45 | function(url, cb) { 46 | var browser = escape(config.browser); 47 | if (browser) { 48 | open(browser, url, cb); 49 | } else { 50 | open('xdg-open', url, cb); 51 | } 52 | }, 53 | 54 | other: 55 | function(url, cb) { 56 | var browser = escape(config.browser); 57 | if (browser) { 58 | open(browser, url, cb); 59 | } else { 60 | cb(new Error('must specify browser in config')); 61 | } 62 | } 63 | }; 64 | 65 | module.exports = { 66 | open: platformOpen 67 | }; 68 | 69 | // note: platform parameter is just for testing... 70 | function platformOpen(url, cb, platform) { 71 | platform = platform || process.platform; 72 | if (!platformOpeners[platform]) { platform = 'other'; } 73 | platformOpeners[platform](url, cb); 74 | } 75 | 76 | function open(command, url, cb) { 77 | if (config.debug) { emit('command: ' + command); } 78 | emit('Opening browser to: ' + url); 79 | Child.exec(command + ' "' + escape(url) + '"', cb); 80 | } 81 | 82 | function escape(s) { 83 | if (!s) { return s; } 84 | return s.replace(/"/g, '\\\"'); 85 | } 86 | -------------------------------------------------------------------------------- /lib/util/feedback.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var EventEmitter = require('events').EventEmitter; 19 | var feedback = new EventEmitter(); 20 | var CHANNEL = 'feedback'; 21 | var util = require('util'); 22 | var _ = require('lodash'); 23 | 24 | module.exports = { 25 | 26 | on: function(cb) { 27 | feedback.on(CHANNEL, function(feedback) { 28 | cb(feedback); 29 | }); 30 | }, 31 | 32 | emit: function(string) { 33 | if (Buffer.isBuffer(string)) { string = string.toString(); } 34 | if (arguments.length > 1 && _.isString(string)) { 35 | string = util.format.apply(this, arguments); 36 | } 37 | feedback.emit(CHANNEL, string); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /lib/util/net.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var net = require('net'); 19 | var debug = require('debug')('swagger'); 20 | var http = require('http'); 21 | var https = require('https'); 22 | var fs = require('fs'); 23 | var _ = require('lodash'); 24 | 25 | var DEFAULT_TIMEOUT = 100; 26 | 27 | module.exports = { 28 | isPortOpen: isPortOpen 29 | }; 30 | 31 | function isPortOpen(port, timeout, cb) { 32 | if (!cb) { cb = timeout; timeout = DEFAULT_TIMEOUT; } 33 | cb = _.once(cb); 34 | 35 | var s = new net.Socket(); 36 | 37 | s.setTimeout(timeout, function() { 38 | s.destroy(); 39 | cb(null, false); 40 | }); 41 | s.connect(port, function() { 42 | cb(null, true); 43 | }); 44 | 45 | s.on('error', function(err) { 46 | s.destroy(); 47 | if (err.code === 'ECONNREFUSED') { err = null; } 48 | cb(err, false); 49 | }); 50 | } 51 | -------------------------------------------------------------------------------- /lib/util/spec.js: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | Copyright 2016 Apigee Corporation 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ****************************************************************************/ 16 | 'use strict'; 17 | 18 | var emit = require('./feedback').emit; 19 | var swaggerSpec = require('swagger-tools').specs.v2_0; 20 | 21 | module.exports = { 22 | validateSwagger: validateSwagger 23 | }; 24 | 25 | function validateSwagger(swagger, options, cb) { 26 | 27 | swaggerSpec.validate(swagger, function(err, results) { 28 | if (err) { return cb(err); } 29 | 30 | var toJsonPointer = function (path) { 31 | // http://tools.ietf.org/html/rfc6901#section-4 32 | return '#/' + path.map(function (part) { 33 | return part.replace(/\//g, '~1'); 34 | }).join('/'); 35 | }; 36 | 37 | if (results) { 38 | if (options.json) { 39 | cb(null, JSON.stringify(results, null, ' ')); 40 | } else { 41 | if (results.errors.length > 0) { 42 | emit('\nProject Errors'); 43 | emit('--------------'); 44 | 45 | results.errors.forEach(function (vErr) { 46 | emit(toJsonPointer(vErr.path) + ': ' + vErr.message); 47 | }); 48 | } 49 | 50 | if (results.warnings.length > 0) { 51 | emit('\nProject Warnings'); 52 | emit('----------------'); 53 | 54 | results.warnings.forEach(function (vWarn) { 55 | emit(toJsonPointer(vWarn.path) + ': ' + vWarn.message); 56 | }); 57 | } 58 | 59 | cb(null, 'Results: ' + results.errors.length + ' errors, ' + results.warnings.length + ' warnings'); 60 | } 61 | } else { 62 | if (options.json) { 63 | cb(null, ''); 64 | } else { 65 | cb(null, 'Results: 0 errors, 0 warnings'); 66 | } 67 | } 68 | }); 69 | } 70 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger", 3 | "version": "0.7.5", 4 | "description": "The Swagger command-line. Provides Swagger utilities and project lifecycle support.", 5 | "keywords": [ 6 | "swagger", 7 | "api", 8 | "apis", 9 | "connect", 10 | "express" 11 | ], 12 | "author": "Scott Ganyo ", 13 | "license": "Apache 2.0", 14 | "preferGlobal": true, 15 | "main": "index.js", 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/swagger-api/swagger-node.git" 19 | }, 20 | "dependencies": { 21 | "async": "^2.1.4", 22 | "commander": "^2.7.1", 23 | "connect": "^3.3.5", 24 | "debug": "^2.1.3", 25 | "fs-extra": "^1.0.0", 26 | "inquirer": "^1.2.3", 27 | "js-yaml": "^3.3.0", 28 | "lodash": "^4.17.2", 29 | "mocha": "^3.2.0", 30 | "nodemon": "^1.3.7", 31 | "serve-static": "^1.9.2", 32 | "swagger-converter": "^1.4.1", 33 | "swagger-editor": "^2.9.2", 34 | "swagger-test-templates": "^1.2.0", 35 | "swagger-tools": "^0.10.1" 36 | }, 37 | "devDependencies": { 38 | "chai": "^3.0.0", 39 | "mock-stdin": "^0.3.0", 40 | "proxyquire": "^1.4.0", 41 | "should": "^11.1.1", 42 | "sinon": "^1.15.4", 43 | "superagent": "^3.1.0", 44 | "supertest": "^2.0.1", 45 | "tmp": "^0.0.31", 46 | "z-schema": "^3.14.0" 47 | }, 48 | "scripts": { 49 | "test": "mocha -u exports -R spec test/config.js test/util test/commands test/commands/project test/project-skeletons", 50 | "coverage": "istanbul cover _mocha -- -u exports -R spec test/config.js test/util test/commands test/commands/project test/project-skeletons", 51 | "start": "node app.js" 52 | }, 53 | "bin": { 54 | "swagger": "bin/swagger.js", 55 | "swagger-project": "bin/swagger-project.js" 56 | } 57 | } -------------------------------------------------------------------------------- /project-skeletons/connect/.gitignore: -------------------------------------------------------------------------------- 1 | # IDE files 2 | .idea 3 | 4 | # Logs 5 | logs 6 | *.log 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 20 | .grunt 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # Commenting this out is preferred by some people, see 27 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 28 | node_modules 29 | 30 | # Users Environment Variables 31 | .lock-wscript 32 | 33 | # Runtime configuration for swagger app 34 | config/runtime.yaml 35 | -------------------------------------------------------------------------------- /project-skeletons/connect/README.md: -------------------------------------------------------------------------------- 1 | # Skeleton project for Swagger 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/api/controllers/README.md: -------------------------------------------------------------------------------- 1 | Place your controllers in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/api/controllers/hello_world.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* 3 | 'use strict' is not required but helpful for turning syntactical errors into true errors in the program flow 4 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode 5 | */ 6 | 7 | /* 8 | Modules make it possible to import JavaScript files into your application. Modules are imported 9 | using 'require' statements that give you a reference to the module. 10 | 11 | It is a good idea to list the modules that your application depends on in the package.json in the project root 12 | */ 13 | var util = require('util'); 14 | 15 | /* 16 | Once you 'require' a module you can reference the things that it exports. These are defined in module.exports. 17 | 18 | For a controller in a127 (which this is) you should export the functions referenced in your Swagger document by name. 19 | 20 | Either: 21 | - The HTTP Verb of the corresponding operation (get, put, post, delete, etc) 22 | - Or the operationId associated with the operation in your Swagger document 23 | 24 | In the starter/skeleton project the 'get' operation on the '/hello' path has an operationId named 'hello'. Here, 25 | we specify that in the exports of this module that 'hello' maps to the function named 'hello' 26 | */ 27 | module.exports = { 28 | hello: hello 29 | }; 30 | 31 | /* 32 | Functions in a127 controllers used for operations should take two parameters: 33 | 34 | Param 1: a handle to the request object 35 | Param 2: a handle to the response object 36 | */ 37 | function hello(req, res) { 38 | // variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name} 39 | var name = req.swagger.params.name.value || 'stranger'; 40 | var hello = util.format('Hello, %s!', name); 41 | 42 | // this sends back a JSON response which is a single string 43 | res.json({ "message": hello }); 44 | } 45 | -------------------------------------------------------------------------------- /project-skeletons/connect/api/helpers/README.md: -------------------------------------------------------------------------------- 1 | Place helper files in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/api/mocks/README.md: -------------------------------------------------------------------------------- 1 | Place controllers for mock mode in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/api/swagger/swagger.yaml: -------------------------------------------------------------------------------- 1 | swagger: "2.0" 2 | info: 3 | version: "0.0.1" 4 | title: Hello World App 5 | # during dev, should point to your local machine 6 | host: localhost:10010 7 | # basePath prefixes all resource paths 8 | basePath: / 9 | # 10 | schemes: 11 | # tip: remove http to make production-grade 12 | - http 13 | - https 14 | # format of bodies a client can send (Content-Type) 15 | consumes: 16 | - application/json 17 | # format of the responses to the client (Accepts) 18 | produces: 19 | - application/json 20 | paths: 21 | /hello: 22 | # binds a127 app logic to a route 23 | x-swagger-router-controller: hello_world 24 | get: 25 | description: Returns 'Hello' to the caller 26 | # used as the method name of the controller 27 | operationId: hello 28 | parameters: 29 | - name: name 30 | in: query 31 | description: The name of the person to whom to say hello 32 | required: false 33 | type: string 34 | responses: 35 | "200": 36 | description: Success 37 | schema: 38 | # a pointer to a definition 39 | $ref: "#/definitions/HelloWorldResponse" 40 | # responses may fall through to errors 41 | default: 42 | description: Error 43 | schema: 44 | $ref: "#/definitions/ErrorResponse" 45 | /swagger: 46 | x-swagger-pipe: swagger_raw 47 | # complex objects have schema definitions 48 | definitions: 49 | HelloWorldResponse: 50 | type: string 51 | ErrorResponse: 52 | required: 53 | - message 54 | properties: 55 | message: 56 | type: string 57 | -------------------------------------------------------------------------------- /project-skeletons/connect/app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var SwaggerConnect = require('swagger-connect'); 4 | var app = require('connect')(); 5 | // export setup Promis for testing 6 | module.exports = new Promise(function (resolve, reject) { 7 | var config = { 8 | appRoot: __dirname // required config 9 | }; 10 | 11 | SwaggerConnect.create(config, function (err, swaggerConnect) { 12 | if (err) { throw err; } 13 | 14 | // install middleware 15 | swaggerConnect.register(app); 16 | 17 | var port = process.env.PORT || 10010; 18 | app.listen(port); 19 | 20 | if (swaggerConnect.runner.swagger.paths['/hello']) { 21 | console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott'); 22 | } 23 | resolve(app); 24 | }); 25 | }); -------------------------------------------------------------------------------- /project-skeletons/connect/config/README.md: -------------------------------------------------------------------------------- 1 | Place configuration files in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/config/default.yaml: -------------------------------------------------------------------------------- 1 | # swagger configuration file 2 | 3 | # values in the swagger hash are system configuration for swagger-node 4 | swagger: 5 | 6 | fittingsDirs: [ api/fittings ] 7 | defaultPipe: null 8 | swaggerControllerPipe: swagger_controllers # defines the standard processing pipe for controllers 9 | 10 | # values defined in the bagpipes key are the bagpipes pipes and fittings definitions 11 | # (see https://github.com/apigee-127/bagpipes) 12 | bagpipes: 13 | 14 | _router: 15 | name: swagger_router 16 | mockMode: false 17 | mockControllersDirs: [ api/mocks ] 18 | controllersDirs: [ api/controllers ] 19 | 20 | _swagger_validate: 21 | name: swagger_validator 22 | validateResponse: true 23 | 24 | # pipe for all swagger-node controllers 25 | swagger_controllers: 26 | - onError: json_error_handler 27 | - cors 28 | - swagger_params_parser 29 | - swagger_security 30 | - _swagger_validate 31 | - express_compatibility 32 | - _router 33 | 34 | # pipe to serve swagger (endpoint is in swagger.yaml) 35 | swagger_raw: 36 | name: swagger_raw 37 | 38 | # any other values in this file are just loaded into the config for application access... 39 | -------------------------------------------------------------------------------- /project-skeletons/connect/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-app", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "New Swagger API Project", 6 | "keywords": [], 7 | "author": "", 8 | "license": "", 9 | "main": "app.js", 10 | "dependencies": { 11 | "connect": "^3.6.0", 12 | "swagger-connect": "^0.7.0" 13 | }, 14 | "devDependencies": { 15 | "should": "^11.2.1", 16 | "supertest": "^3.0.0" 17 | }, 18 | "scripts": { 19 | "start": "node app.js", 20 | "test": "swagger project test" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /project-skeletons/connect/test/api/controllers/README.md: -------------------------------------------------------------------------------- 1 | Place your controller tests in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/connect/test/api/controllers/hello_world.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | var request = require('supertest'); 3 | var server = require('../../../app'); 4 | 5 | describe('controllers', function() { 6 | 7 | describe('hello_world', function() { 8 | 9 | describe('GET /hello', function() { 10 | 11 | it('should return a default string', function(done) { 12 | 13 | request(server) 14 | .get('/hello') 15 | .set('Accept', 'application/json') 16 | .expect('Content-Type', /json/) 17 | .expect(200) 18 | .end(function(err, res) { 19 | should.not.exist(err); 20 | 21 | res.body.should.eql({ "message": "Hello, stranger!" }); 22 | 23 | done(); 24 | }); 25 | }); 26 | 27 | it('should accept a name parameter', function(done) { 28 | 29 | request(server) 30 | .get('/hello') 31 | .query({ name: 'Scott'}) 32 | .set('Accept', 'application/json') 33 | .expect('Content-Type', /json/) 34 | .expect(200) 35 | .end(function(err, res) { 36 | should.not.exist(err); 37 | 38 | res.body.should.eql({ "message": "Hello, Scott!" }); 39 | 40 | done(); 41 | }); 42 | }); 43 | 44 | }); 45 | 46 | }); 47 | 48 | }); 49 | -------------------------------------------------------------------------------- /project-skeletons/connect/test/api/helpers/README.md: -------------------------------------------------------------------------------- 1 | Place your helper tests in this directory. 2 | -------------------------------------------------------------------------------- /project-skeletons/express/app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var SwaggerExpress = require('swagger-express-mw'); 4 | var app = require('express')(); 5 | // export setup Promis for testing 6 | module.exports = new Promise(function (resolve, reject) { 7 | 8 | var config = { 9 | appRoot: __dirname // required config 10 | }; 11 | 12 | SwaggerExpress.create(config, function (err, swaggerExpress) { 13 | if (err) { throw err; } 14 | 15 | // install middleware 16 | swaggerExpress.register(app); 17 | 18 | var port = process.env.PORT || 10010; 19 | app.listen(port, function() { 20 | if (swaggerExpress.runner.swagger.paths['/hello']) { 21 | console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott'); 22 | } 23 | resolve(app); 24 | }); 25 | }); 26 | }); -------------------------------------------------------------------------------- /project-skeletons/express/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-app", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "New Swagger API Project", 6 | "keywords": [], 7 | "author": "", 8 | "license": "", 9 | "main": "app.js", 10 | "dependencies": { 11 | "express": "^4.15.2", 12 | "swagger-express-mw": "^0.7.0" 13 | }, 14 | "devDependencies": { 15 | "should": "^11.2.1", 16 | "supertest": "^3.0.0" 17 | }, 18 | "scripts": { 19 | "start": "node app.js", 20 | "test": "swagger project test" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /project-skeletons/hapi/app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var SwaggerHapi = require('swagger-hapi'); 4 | var Hapi = require('hapi'); 5 | var app = new Hapi.Server(); 6 | 7 | // export setup Promis for testing 8 | module.exports = new Promise(function (resolve, reject) { 9 | 10 | var config = { 11 | appRoot: __dirname // required config 12 | }; 13 | 14 | SwaggerHapi.create(config, function (err, swaggerHapi) { 15 | if (err) { throw err; } 16 | 17 | var port = process.env.PORT || 10010; 18 | app.connection({ port: port }); 19 | app.address = function () { 20 | return { port: port }; 21 | }; 22 | 23 | app.register(swaggerHapi.plugin, function (err) { 24 | if (err) { 25 | console.error('Failed to load plugin:', err); 26 | reject(err); 27 | } 28 | app.start(function () { 29 | if (swaggerHapi.runner.swagger.paths['/hello']) { 30 | console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott'); 31 | } 32 | resolve(app); 33 | }); 34 | }); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /project-skeletons/hapi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-app", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "New Swagger API Project", 6 | "keywords": [], 7 | "author": "", 8 | "license": "", 9 | "main": "app.js", 10 | "dependencies": { 11 | "hapi": "^16.1.1", 12 | "swagger-hapi": "^0.7.0" 13 | }, 14 | "devDependencies": { 15 | "should": "^11.2.1", 16 | "supertest": "^3.0.0" 17 | }, 18 | "scripts": { 19 | "start": "node app.js", 20 | "test": "swagger project test" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /project-skeletons/restify/app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var SwaggerRestify = require('swagger-restify-mw'); 4 | var restify = require('restify'); 5 | var app = restify.createServer(); 6 | 7 | // export setup Promis for testing 8 | module.exports = new Promise(function (resolve, reject) { 9 | 10 | var config = { 11 | appRoot: __dirname // required config 12 | }; 13 | 14 | SwaggerRestify.create(config, function (err, swaggerRestify) { 15 | if (err) { throw err; } 16 | 17 | swaggerRestify.register(app); 18 | 19 | var port = process.env.PORT || 10010; 20 | app.listen(port, function () { 21 | if (swaggerRestify.runner.swagger.paths['/hello']) { 22 | console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott'); 23 | } 24 | resolve(app); 25 | }); 26 | }); 27 | }); -------------------------------------------------------------------------------- /project-skeletons/restify/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-app", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "New Swagger API Project", 6 | "keywords": [], 7 | "author": "", 8 | "license": "", 9 | "main": "app.js", 10 | "dependencies": { 11 | "restify": "^4.3.0", 12 | "swagger-restify-mw": "^0.7.0" 13 | }, 14 | "devDependencies": { 15 | "should": "^11.2.1", 16 | "supertest": "^3.0.0" 17 | }, 18 | "scripts": { 19 | "start": "node app.js", 20 | "test": "swagger project test" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /project-skeletons/sails/.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | -------------------------------------------------------------------------------- /project-skeletons/sails/.gitignore: -------------------------------------------------------------------------------- 1 | ################################################ 2 | ############### .gitignore ################## 3 | ################################################ 4 | # 5 | # This file is only relevant if you are using git. 6 | # 7 | # Files which match the splat patterns below will 8 | # be ignored by git. This keeps random crap and 9 | # sensitive credentials from being uploaded to 10 | # your repository. It allows you to configure your 11 | # app for your machine without accidentally 12 | # committing settings which will smash the local 13 | # settings of other developers on your team. 14 | # 15 | # Some reasonable defaults are included below, 16 | # but, of course, you should modify/extend/prune 17 | # to fit your needs! 18 | ################################################ 19 | 20 | 21 | 22 | 23 | ################################################ 24 | # Local Configuration 25 | # 26 | # Explicitly ignore files which contain: 27 | # 28 | # 1. Sensitive information you'd rather not push to 29 | # your git repository. 30 | # e.g., your personal API keys or passwords. 31 | # 32 | # 2. Environment-specific configuration 33 | # Basically, anything that would be annoying 34 | # to have to change every time you do a 35 | # `git pull` 36 | # e.g., your local development database, or 37 | # the S3 bucket you're using for file uploads 38 | # development. 39 | # 40 | ################################################ 41 | 42 | config/local.js 43 | 44 | 45 | 46 | 47 | 48 | ################################################ 49 | # Dependencies 50 | # 51 | # When releasing a production app, you may 52 | # consider including your node_modules and 53 | # bower_components directory in your git repo, 54 | # but during development, its best to exclude it, 55 | # since different developers may be working on 56 | # different kernels, where dependencies would 57 | # need to be recompiled anyway. 58 | # 59 | # More on that here about node_modules dir: 60 | # http://www.futurealoof.com/posts/nodemodules-in-git.html 61 | # (credit Mikeal Rogers, @mikeal) 62 | # 63 | # About bower_components dir, you can see this: 64 | # http://addyosmani.com/blog/checking-in-front-end-dependencies/ 65 | # (credit Addy Osmani, @addyosmani) 66 | # 67 | ################################################ 68 | 69 | node_modules 70 | bower_components 71 | 72 | 73 | 74 | 75 | ################################################ 76 | # Sails.js / Waterline / Grunt 77 | # 78 | # Files generated by Sails and Grunt, or related 79 | # tasks and adapters. 80 | ################################################ 81 | .tmp 82 | dump.rdb 83 | 84 | 85 | 86 | 87 | 88 | ################################################ 89 | # Node.js / NPM 90 | # 91 | # Common files generated by Node, NPM, and the 92 | # related ecosystem. 93 | ################################################ 94 | lib-cov 95 | *.seed 96 | *.log 97 | *.out 98 | *.pid 99 | npm-debug.log 100 | 101 | 102 | 103 | 104 | 105 | ################################################ 106 | # Miscellaneous 107 | # 108 | # Common files generated by text editors, 109 | # operating systems, file systems, etc. 110 | ################################################ 111 | 112 | *~ 113 | *# 114 | .DS_STORE 115 | .netbeans 116 | nbproject 117 | .idea 118 | .node_history 119 | .vscode 120 | .DS_STORE -------------------------------------------------------------------------------- /project-skeletons/sails/.sailsrc: -------------------------------------------------------------------------------- 1 | { 2 | "generators": { 3 | "modules": {} 4 | } 5 | } -------------------------------------------------------------------------------- /project-skeletons/sails/Gruntfile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Gruntfile 3 | * 4 | * This Node script is executed when you run `grunt` or `sails lift`. 5 | * It's purpose is to load the Grunt tasks in your project's `tasks` 6 | * folder, and allow you to add and remove tasks as you see fit. 7 | * For more information on how this works, check out the `README.md` 8 | * file that was generated in your `tasks` folder. 9 | * 10 | * WARNING: 11 | * Unless you know what you're doing, you shouldn't change this file. 12 | * Check out the `tasks` directory instead. 13 | */ 14 | 15 | module.exports = function(grunt) { 16 | 17 | 18 | // Load the include-all library in order to require all of our grunt 19 | // configurations and task registrations dynamically. 20 | var includeAll; 21 | try { 22 | includeAll = require('include-all'); 23 | } catch (e0) { 24 | try { 25 | includeAll = require('sails/node_modules/include-all'); 26 | } catch (e1) { 27 | console.error('Could not find `include-all` module.'); 28 | console.error('Skipping grunt tasks...'); 29 | console.error('To fix this, please run:'); 30 | console.error('npm install include-all --save`'); 31 | console.error(); 32 | 33 | grunt.registerTask('default', []); 34 | return; 35 | } 36 | } 37 | 38 | 39 | /** 40 | * Loads Grunt configuration modules from the specified 41 | * relative path. These modules should export a function 42 | * that, when run, should either load/configure or register 43 | * a Grunt task. 44 | */ 45 | function loadTasks(relPath) { 46 | return includeAll({ 47 | dirname: require('path').resolve(__dirname, relPath), 48 | filter: /(.+)\.js$/, 49 | excludeDirs: /^\.(git|svn)$/ 50 | }) || {}; 51 | } 52 | 53 | /** 54 | * Invokes the function from a Grunt configuration module with 55 | * a single argument - the `grunt` object. 56 | */ 57 | function invokeConfigFn(tasks) { 58 | for (var taskName in tasks) { 59 | if (tasks.hasOwnProperty(taskName)) { 60 | tasks[taskName](grunt); 61 | } 62 | } 63 | } 64 | 65 | 66 | 67 | // Load task functions 68 | var taskConfigurations = loadTasks('./tasks/config'), 69 | registerDefinitions = loadTasks('./tasks/register'); 70 | 71 | // (ensure that a default task exists) 72 | if (!registerDefinitions.default) { 73 | registerDefinitions.default = function(grunt) { 74 | grunt.registerTask('default', []); 75 | }; 76 | } 77 | 78 | // Run task functions to configure Grunt. 79 | invokeConfigFn(taskConfigurations); 80 | invokeConfigFn(registerDefinitions); 81 | 82 | }; 83 | -------------------------------------------------------------------------------- /project-skeletons/sails/README.md: -------------------------------------------------------------------------------- 1 | # A [Swagger](https://www.npmjs.com/package/swagger) / [Sails](http://sailsjs.org) application 2 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/controllers/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/api/controllers/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/api/controllers/hello_world.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* 3 | 'use strict' is not required but helpful for turning syntactical errors into true errors in the program flow 4 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode 5 | */ 6 | 7 | /* 8 | Modules make it possible to import JavaScript files into your application. Modules are imported 9 | using 'require' statements that give you a reference to the module. 10 | 11 | It is a good idea to list the modules that your application depends on in the package.json in the project root 12 | */ 13 | var util = require('util'); 14 | 15 | /* 16 | Once you 'require' a module you can reference the things that it exports. These are defined in module.exports. 17 | 18 | For a controller in a127 (which this is) you should export the functions referenced in your Swagger document by name. 19 | 20 | Either: 21 | - The HTTP Verb of the corresponding operation (get, put, post, delete, etc) 22 | - Or the operationId associated with the operation in your Swagger document 23 | 24 | In the starter/skeleton project the 'get' operation on the '/hello' path has an operationId named 'hello'. Here, 25 | we specify that in the exports of this module that 'hello' maps to the function named 'hello' 26 | */ 27 | module.exports = { 28 | hello: hello 29 | }; 30 | 31 | /* 32 | Functions in a127 controllers used for operations should take two parameters: 33 | 34 | Param 1: a handle to the request object 35 | Param 2: a handle to the response object 36 | */ 37 | function hello(req, res) { 38 | // variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name} 39 | var name = req.swagger.params.name.value || 'stranger'; 40 | var hello = util.format('Hello, %s!', name); 41 | 42 | // this sends back a JSON response which is a single string 43 | res.json({ "message": hello }); 44 | } 45 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/mocks/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/api/mocks/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/api/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/api/models/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/api/policies/sessionAuth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * sessionAuth 3 | * 4 | * @module :: Policy 5 | * @description :: Simple policy to allow any authenticated user 6 | * Assumes that your login action in one of your controllers sets `req.session.authenticated = true;` 7 | * @docs :: http://sailsjs.org/#!/documentation/concepts/Policies 8 | * 9 | */ 10 | module.exports = function(req, res, next) { 11 | 12 | // User is allowed, proceed to the next policy, 13 | // or if this is the last policy, the controller 14 | if (req.session.authenticated) { 15 | return next(); 16 | } 17 | 18 | // User is not allowed 19 | // (default res.forbidden() behavior can be overridden in `config/403.js`) 20 | return res.forbidden('You are not permitted to perform this action.'); 21 | }; 22 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/badRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 400 (Bad Request) Handler 3 | * 4 | * Usage: 5 | * return res.badRequest(); 6 | * return res.badRequest(data); 7 | * return res.badRequest(data, 'some/specific/badRequest/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.badRequest( 12 | * 'Please choose a valid `password` (6-12 characters)', 13 | * 'trial/signup' 14 | * ); 15 | * ``` 16 | */ 17 | 18 | module.exports = function badRequest(data, options) { 19 | 20 | // Get access to `req`, `res`, & `sails` 21 | var req = this.req; 22 | var res = this.res; 23 | var sails = req._sails; 24 | 25 | // Set status code 26 | res.status(400); 27 | 28 | // Log error to console 29 | if (data !== undefined) { 30 | sails.log.verbose('Sending 400 ("Bad Request") response: \n',data); 31 | } 32 | else sails.log.verbose('Sending 400 ("Bad Request") response'); 33 | 34 | // Only include errors in response if application environment 35 | // is not set to 'production'. In production, we shouldn't 36 | // send back any identifying information about errors. 37 | if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { 38 | data = undefined; 39 | } 40 | 41 | // If the user-agent wants JSON, always respond with JSON 42 | // If views are disabled, revert to json 43 | if (req.wantsJSON || sails.config.hooks.views === false) { 44 | return res.jsonx(data); 45 | } 46 | 47 | // If second argument is a string, we take that to mean it refers to a view. 48 | // If it was omitted, use an empty object (`{}`) 49 | options = (typeof options === 'string') ? { view: options } : options || {}; 50 | 51 | // Attempt to prettify data for views, if it's a non-error object 52 | var viewData = data; 53 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 54 | try { 55 | viewData = require('util').inspect(data, {depth: null}); 56 | } 57 | catch(e) { 58 | viewData = undefined; 59 | } 60 | } 61 | 62 | // If a view was provided in options, serve it. 63 | // Otherwise try to guess an appropriate view, or if that doesn't 64 | // work, just send JSON. 65 | if (options.view) { 66 | return res.view(options.view, { data: viewData, title: 'Bad Request' }); 67 | } 68 | 69 | // If no second argument provided, try to serve the implied view, 70 | // but fall back to sending JSON(P) if no view can be inferred. 71 | else return res.guessView({ data: viewData, title: 'Bad Request' }, function couldNotGuessView () { 72 | return res.jsonx(data); 73 | }); 74 | 75 | }; 76 | 77 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/created.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 201 (CREATED) Response 3 | * 4 | * Usage: 5 | * return res.created(); 6 | * return res.created(data); 7 | * return res.created(data, 'auth/login'); 8 | * 9 | * @param {Object} data 10 | * @param {String|Object} options 11 | * - pass string to render specified view 12 | */ 13 | 14 | module.exports = function created (data, options) { 15 | 16 | // Get access to `req`, `res`, & `sails` 17 | var req = this.req; 18 | var res = this.res; 19 | var sails = req._sails; 20 | 21 | sails.log.silly('res.created() :: Sending 201 ("CREATED") response'); 22 | 23 | // Set status code 24 | res.status(201); 25 | 26 | // If appropriate, serve data as JSON(P) 27 | // If views are disabled, revert to json 28 | if (req.wantsJSON || sails.config.hooks.views === false) { 29 | return res.jsonx(data); 30 | } 31 | 32 | // If second argument is a string, we take that to mean it refers to a view. 33 | // If it was omitted, use an empty object (`{}`) 34 | options = (typeof options === 'string') ? { view: options } : options || {}; 35 | 36 | // Attempt to prettify data for views, if it's a non-error object 37 | var viewData = data; 38 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 39 | try { 40 | viewData = require('util').inspect(data, {depth: null}); 41 | } 42 | catch(e) { 43 | viewData = undefined; 44 | } 45 | } 46 | 47 | // If a view was provided in options, serve it. 48 | // Otherwise try to guess an appropriate view, or if that doesn't 49 | // work, just send JSON. 50 | if (options.view) { 51 | return res.view(options.view, { data: viewData, title: 'Created' }); 52 | } 53 | 54 | // If no second argument provided, try to serve the implied view, 55 | // but fall back to sending JSON(P) if no view can be inferred. 56 | else return res.guessView({ data: viewData, title: 'Created' }, function couldNotGuessView () { 57 | return res.jsonx(data); 58 | }); 59 | 60 | }; 61 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/forbidden.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 403 (Forbidden) Handler 3 | * 4 | * Usage: 5 | * return res.forbidden(); 6 | * return res.forbidden(err); 7 | * return res.forbidden(err, 'some/specific/forbidden/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.forbidden('Access denied.'); 12 | * ``` 13 | */ 14 | 15 | module.exports = function forbidden (data, options) { 16 | 17 | // Get access to `req`, `res`, & `sails` 18 | var req = this.req; 19 | var res = this.res; 20 | var sails = req._sails; 21 | 22 | // Set status code 23 | res.status(403); 24 | 25 | // Log error to console 26 | if (data !== undefined) { 27 | sails.log.verbose('Sending 403 ("Forbidden") response: \n',data); 28 | } 29 | else sails.log.verbose('Sending 403 ("Forbidden") response'); 30 | 31 | // Only include errors in response if application environment 32 | // is not set to 'production'. In production, we shouldn't 33 | // send back any identifying information about errors. 34 | if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { 35 | data = undefined; 36 | } 37 | 38 | // If the user-agent wants JSON, always respond with JSON 39 | // If views are disabled, revert to json 40 | if (req.wantsJSON || sails.config.hooks.views === false) { 41 | return res.jsonx(data); 42 | } 43 | 44 | // If second argument is a string, we take that to mean it refers to a view. 45 | // If it was omitted, use an empty object (`{}`) 46 | options = (typeof options === 'string') ? { view: options } : options || {}; 47 | 48 | // Attempt to prettify data for views, if it's a non-error object 49 | var viewData = data; 50 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 51 | try { 52 | viewData = require('util').inspect(data, {depth: null}); 53 | } 54 | catch(e) { 55 | viewData = undefined; 56 | } 57 | } 58 | 59 | // If a view was provided in options, serve it. 60 | // Otherwise try to guess an appropriate view, or if that doesn't 61 | // work, just send JSON. 62 | if (options.view) { 63 | return res.view(options.view, { data: viewData, title: 'Forbidden' }); 64 | } 65 | 66 | // If no second argument provided, try to serve the default view, 67 | // but fall back to sending JSON(P) if any errors occur. 68 | else return res.view('403', { data: viewData, title: 'Forbidden' }, function (err, html) { 69 | 70 | // If a view error occured, fall back to JSON(P). 71 | if (err) { 72 | // 73 | // Additionally: 74 | // • If the view was missing, ignore the error but provide a verbose log. 75 | if (err.code === 'E_VIEW_FAILED') { 76 | sails.log.verbose('res.forbidden() :: Could not locate view for error page (sending JSON instead). Details: ',err); 77 | } 78 | // Otherwise, if this was a more serious error, log to the console with the details. 79 | else { 80 | sails.log.warn('res.forbidden() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 81 | } 82 | return res.jsonx(data); 83 | } 84 | 85 | return res.send(html); 86 | }); 87 | 88 | }; 89 | 90 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/notFound.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 404 (Not Found) Handler 3 | * 4 | * Usage: 5 | * return res.notFound(); 6 | * return res.notFound(err); 7 | * return res.notFound(err, 'some/specific/notfound/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.notFound(); 12 | * ``` 13 | * 14 | * NOTE: 15 | * If a request doesn't match any explicit routes (i.e. `config/routes.js`) 16 | * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()` 17 | * automatically. 18 | */ 19 | 20 | module.exports = function notFound (data, options) { 21 | 22 | // Get access to `req`, `res`, & `sails` 23 | var req = this.req; 24 | var res = this.res; 25 | var sails = req._sails; 26 | 27 | // Set status code 28 | res.status(404); 29 | 30 | // Log error to console 31 | if (data !== undefined) { 32 | sails.log.verbose('Sending 404 ("Not Found") response: \n',data); 33 | } 34 | else sails.log.verbose('Sending 404 ("Not Found") response'); 35 | 36 | // Only include errors in response if application environment 37 | // is not set to 'production'. In production, we shouldn't 38 | // send back any identifying information about errors. 39 | if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { 40 | data = undefined; 41 | } 42 | 43 | // If the user-agent wants JSON, always respond with JSON 44 | // If views are disabled, revert to json 45 | if (req.wantsJSON || sails.config.hooks.views === false) { 46 | return res.jsonx(data); 47 | } 48 | 49 | // If second argument is a string, we take that to mean it refers to a view. 50 | // If it was omitted, use an empty object (`{}`) 51 | options = (typeof options === 'string') ? { view: options } : options || {}; 52 | 53 | // Attempt to prettify data for views, if it's a non-error object 54 | var viewData = data; 55 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 56 | try { 57 | viewData = require('util').inspect(data, {depth: null}); 58 | } 59 | catch(e) { 60 | viewData = undefined; 61 | } 62 | } 63 | 64 | // If a view was provided in options, serve it. 65 | // Otherwise try to guess an appropriate view, or if that doesn't 66 | // work, just send JSON. 67 | if (options.view) { 68 | return res.view(options.view, { data: viewData, title: 'Not Found' }); 69 | } 70 | 71 | // If no second argument provided, try to serve the default view, 72 | // but fall back to sending JSON(P) if any errors occur. 73 | else return res.view('404', { data: viewData, title: 'Not Found' }, function (err, html) { 74 | 75 | // If a view error occured, fall back to JSON(P). 76 | if (err) { 77 | // 78 | // Additionally: 79 | // • If the view was missing, ignore the error but provide a verbose log. 80 | if (err.code === 'E_VIEW_FAILED') { 81 | sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err); 82 | } 83 | // Otherwise, if this was a more serious error, log to the console with the details. 84 | else { 85 | sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 86 | } 87 | return res.jsonx(data); 88 | } 89 | 90 | return res.send(html); 91 | }); 92 | 93 | }; 94 | 95 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/ok.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 200 (OK) Response 3 | * 4 | * Usage: 5 | * return res.ok(); 6 | * return res.ok(data); 7 | * return res.ok(data, 'auth/login'); 8 | * 9 | * @param {Object} data 10 | * @param {String|Object} options 11 | * - pass string to render specified view 12 | */ 13 | 14 | module.exports = function sendOK (data, options) { 15 | 16 | // Get access to `req`, `res`, & `sails` 17 | var req = this.req; 18 | var res = this.res; 19 | var sails = req._sails; 20 | 21 | sails.log.silly('res.ok() :: Sending 200 ("OK") response'); 22 | 23 | // Set status code 24 | res.status(200); 25 | 26 | // If appropriate, serve data as JSON(P) 27 | // If views are disabled, revert to json 28 | if (req.wantsJSON || sails.config.hooks.views === false) { 29 | return res.jsonx(data); 30 | } 31 | 32 | // If second argument is a string, we take that to mean it refers to a view. 33 | // If it was omitted, use an empty object (`{}`) 34 | options = (typeof options === 'string') ? { view: options } : options || {}; 35 | 36 | // Attempt to prettify data for views, if it's a non-error object 37 | var viewData = data; 38 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 39 | try { 40 | viewData = require('util').inspect(data, {depth: null}); 41 | } 42 | catch(e) { 43 | viewData = undefined; 44 | } 45 | } 46 | 47 | // If a view was provided in options, serve it. 48 | // Otherwise try to guess an appropriate view, or if that doesn't 49 | // work, just send JSON. 50 | if (options.view) { 51 | return res.view(options.view, { data: viewData, title: 'OK' }); 52 | } 53 | 54 | // If no second argument provided, try to serve the implied view, 55 | // but fall back to sending JSON(P) if no view can be inferred. 56 | else return res.guessView({ data: viewData, title: 'OK' }, function couldNotGuessView () { 57 | return res.jsonx(data); 58 | }); 59 | 60 | }; 61 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/responses/serverError.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 500 (Server Error) Response 3 | * 4 | * Usage: 5 | * return res.serverError(); 6 | * return res.serverError(err); 7 | * return res.serverError(err, 'some/specific/error/view'); 8 | * 9 | * NOTE: 10 | * If something throws in a policy or controller, or an internal 11 | * error is encountered, Sails will call `res.serverError()` 12 | * automatically. 13 | */ 14 | 15 | module.exports = function serverError (data, options) { 16 | 17 | // Get access to `req`, `res`, & `sails` 18 | var req = this.req; 19 | var res = this.res; 20 | var sails = req._sails; 21 | 22 | // Set status code 23 | res.status(500); 24 | 25 | // Log error to console 26 | if (data !== undefined) { 27 | sails.log.error('Sending 500 ("Server Error") response: \n',data); 28 | } 29 | else sails.log.error('Sending empty 500 ("Server Error") response'); 30 | 31 | // Only include errors in response if application environment 32 | // is not set to 'production'. In production, we shouldn't 33 | // send back any identifying information about errors. 34 | if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { 35 | data = undefined; 36 | } 37 | 38 | // If the user-agent wants JSON, always respond with JSON 39 | // If views are disabled, revert to json 40 | if (req.wantsJSON || sails.config.hooks.views === false) { 41 | return res.jsonx(data); 42 | } 43 | 44 | // If second argument is a string, we take that to mean it refers to a view. 45 | // If it was omitted, use an empty object (`{}`) 46 | options = (typeof options === 'string') ? { view: options } : options || {}; 47 | 48 | // Attempt to prettify data for views, if it's a non-error object 49 | var viewData = data; 50 | if (!(viewData instanceof Error) && 'object' == typeof viewData) { 51 | try { 52 | viewData = require('util').inspect(data, {depth: null}); 53 | } 54 | catch(e) { 55 | viewData = undefined; 56 | } 57 | } 58 | 59 | // If a view was provided in options, serve it. 60 | // Otherwise try to guess an appropriate view, or if that doesn't 61 | // work, just send JSON. 62 | if (options.view) { 63 | return res.view(options.view, { data: viewData, title: 'Server Error' }); 64 | } 65 | 66 | // If no second argument provided, try to serve the default view, 67 | // but fall back to sending JSON(P) if any errors occur. 68 | else return res.view('500', { data: viewData, title: 'Server Error' }, function (err, html) { 69 | 70 | // If a view error occured, fall back to JSON(P). 71 | if (err) { 72 | // 73 | // Additionally: 74 | // • If the view was missing, ignore the error but provide a verbose log. 75 | if (err.code === 'E_VIEW_FAILED') { 76 | sails.log.verbose('res.serverError() :: Could not locate view for error page (sending JSON instead). Details: ',err); 77 | } 78 | // Otherwise, if this was a more serious error, log to the console with the details. 79 | else { 80 | sails.log.warn('res.serverError() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 81 | } 82 | return res.jsonx(data); 83 | } 84 | 85 | return res.send(html); 86 | }); 87 | 88 | }; 89 | 90 | -------------------------------------------------------------------------------- /project-skeletons/sails/api/services/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/api/services/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/api/swagger/swagger.yaml: -------------------------------------------------------------------------------- 1 | swagger: "2.0" 2 | info: 3 | version: "0.0.1" 4 | title: Hello World App 5 | # during dev, should point to your local machine 6 | host: localhost:10010 7 | # basePath prefixes all resource paths 8 | basePath: / 9 | # 10 | schemes: 11 | # tip: remove http to make production-grade 12 | - http 13 | - https 14 | # format of bodies a client can send (Content-Type) 15 | consumes: 16 | - application/json 17 | # format of the responses to the client (Accepts) 18 | produces: 19 | - application/json 20 | paths: 21 | /hello: 22 | # binds a127 app logic to a route 23 | x-swagger-router-controller: hello_world 24 | get: 25 | description: Returns 'Hello' to the caller 26 | # used as the method name of the controller 27 | operationId: hello 28 | parameters: 29 | - name: name 30 | in: query 31 | description: The name of the person to whom to say hello 32 | required: false 33 | type: string 34 | responses: 35 | "200": 36 | description: Success 37 | schema: 38 | # a pointer to a definition 39 | $ref: "#/definitions/HelloWorldResponse" 40 | # responses may fall through to errors 41 | default: 42 | description: Error 43 | schema: 44 | $ref: "#/definitions/ErrorResponse" 45 | /swagger: 46 | x-swagger-pipe: swagger_raw 47 | # complex objects have schema definitions 48 | definitions: 49 | HelloWorldResponse: 50 | required: 51 | - message 52 | properties: 53 | message: 54 | type: string 55 | ErrorResponse: 56 | required: 57 | - message 58 | properties: 59 | message: 60 | type: string 61 | -------------------------------------------------------------------------------- /project-skeletons/sails/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * app.js 3 | * 4 | * Use `app.js` to run your app without `sails lift`. 5 | * To start the server, run: `node app.js`. 6 | * 7 | * This is handy in situations where the sails CLI is not relevant or useful. 8 | * 9 | * For example: 10 | * => `node app.js` 11 | * => `forever start app.js` 12 | * => `node debug app.js` 13 | * => `modulus deploy` 14 | * => `heroku scale` 15 | * 16 | * 17 | * The same command-line arguments are supported, e.g.: 18 | * `node app.js --silent --port=80 --prod` 19 | */ 20 | 21 | 22 | // Ensure we're in the project directory, so cwd-relative paths work as expected 23 | // no matter where we actually lift from. 24 | // > Note: This is not required in order to lift, but it is a convenient default. 25 | process.chdir(__dirname); 26 | 27 | // Attempt to import `sails`. 28 | var sails; 29 | try { 30 | sails = require('sails'); 31 | } catch (e) { 32 | console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.'); 33 | console.error('To do that, run `npm install sails`'); 34 | console.error(''); 35 | console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.'); 36 | console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,'); 37 | console.error('but if it doesn\'t, the app will run with the global sails instead!'); 38 | return; 39 | } 40 | 41 | // --• 42 | // Try to get `rc` dependency (for loading `.sailsrc` files). 43 | var rc; 44 | try { 45 | rc = require('rc'); 46 | } catch (e0) { 47 | try { 48 | rc = require('sails/node_modules/rc'); 49 | } catch (e1) { 50 | console.error('Could not find dependency: `rc`.'); 51 | console.error('Your `.sailsrc` file(s) will be ignored.'); 52 | console.error('To resolve this, run:'); 53 | console.error('npm install rc --save'); 54 | rc = function () { return {}; }; 55 | } 56 | } 57 | 58 | 59 | // Start server 60 | sails.lift(rc('sails')); 61 | -------------------------------------------------------------------------------- /project-skeletons/sails/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/assets/favicon.ico -------------------------------------------------------------------------------- /project-skeletons/sails/assets/images/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/assets/images/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/assets/robots.txt: -------------------------------------------------------------------------------- 1 | # The robots.txt file is used to control how search engines index your live URLs. 2 | # See http://sailsjs.org/documentation/anatomy/my-app/assets/robots-txt for more information. 3 | 4 | 5 | 6 | # To prevent search engines from seeing the site altogether, uncomment the next two lines: 7 | # User-Agent: * 8 | # Disallow: / 9 | -------------------------------------------------------------------------------- /project-skeletons/sails/assets/styles/importer.less: -------------------------------------------------------------------------------- 1 | /** 2 | * importer.less 3 | * 4 | * By default, new Sails projects are configured to compile this file 5 | * from LESS to CSS. Unlike CSS files, LESS files are not compiled and 6 | * included automatically unless they are imported below. 7 | * 8 | * The LESS files imported below are compiled and included in the order 9 | * they are listed. Mixins, variables, etc. should be imported first 10 | * so that they can be accessed by subsequent LESS stylesheets. 11 | * 12 | * (Just like the rest of the asset pipeline bundled in Sails, you can 13 | * always omit, customize, or replace this behavior with SASS, SCSS, 14 | * or any other Grunt tasks you like.) 15 | */ 16 | 17 | 18 | 19 | // For example: 20 | // 21 | // @import 'variables/colors.less'; 22 | // @import 'mixins/foo.less'; 23 | // @import 'mixins/bar.less'; 24 | // @import 'mixins/baz.less'; 25 | // 26 | // @import 'styleguide.less'; 27 | // @import 'pages/login.less'; 28 | // @import 'pages/signup.less'; 29 | // 30 | // etc. 31 | -------------------------------------------------------------------------------- /project-skeletons/sails/assets/templates/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-node/fc777a61ccaf54076d0a3ffcfafedc347abc15ba/project-skeletons/sails/assets/templates/.gitkeep -------------------------------------------------------------------------------- /project-skeletons/sails/config/bootstrap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Bootstrap 3 | * (sails.config.bootstrap) 4 | * 5 | * An asynchronous bootstrap function that runs before your Sails app gets lifted. 6 | * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. 7 | * 8 | * For more information on bootstrapping your app, check out: 9 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html 10 | */ 11 | 12 | module.exports.bootstrap = function(cb) { 13 | 14 | // It's very important to trigger this callback method when you are finished 15 | // with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap) 16 | cb(); 17 | }; 18 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/cors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Cross-Origin Resource Sharing (CORS) Settings 3 | * (sails.config.cors) 4 | * 5 | * CORS is like a more modern version of JSONP-- it allows your server/API 6 | * to successfully respond to requests from client-side JavaScript code 7 | * running on some other domain (e.g. google.com) 8 | * Unlike JSONP, it works with POST, PUT, and DELETE requests 9 | * 10 | * For more information on CORS, check out: 11 | * http://en.wikipedia.org/wiki/Cross-origin_resource_sharing 12 | * 13 | * Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis 14 | * by adding a "cors" object to the route configuration: 15 | * 16 | * '/get foo': { 17 | * controller: 'foo', 18 | * action: 'bar', 19 | * cors: { 20 | * origin: 'http://foobar.com,https://owlhoot.com' 21 | * } 22 | * } 23 | * 24 | * For more information on this configuration file, see: 25 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html 26 | * 27 | */ 28 | 29 | module.exports.cors = { 30 | 31 | /*************************************************************************** 32 | * * 33 | * Allow CORS on all routes by default? If not, you must enable CORS on a * 34 | * per-route basis by either adding a "cors" configuration object to the * 35 | * route config, or setting "cors:true" in the route config to use the * 36 | * default settings below. * 37 | * * 38 | ***************************************************************************/ 39 | 40 | // allRoutes: false, 41 | 42 | /*************************************************************************** 43 | * * 44 | * Which domains which are allowed CORS access? This can be a * 45 | * comma-delimited list of hosts (beginning with http:// or https://) or * 46 | * "*" to allow all domains CORS access. * 47 | * * 48 | ***************************************************************************/ 49 | 50 | // origin: '*', 51 | 52 | /*************************************************************************** 53 | * * 54 | * Allow cookies to be shared for CORS requests? * 55 | * * 56 | ***************************************************************************/ 57 | 58 | // credentials: true, 59 | 60 | /*************************************************************************** 61 | * * 62 | * Which methods should be allowed for CORS requests? This is only used in * 63 | * response to preflight requests (see article linked above for more info) * 64 | * * 65 | ***************************************************************************/ 66 | 67 | // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD', 68 | 69 | /*************************************************************************** 70 | * * 71 | * Which headers should be allowed for CORS requests? This is only used in * 72 | * response to preflight requests. * 73 | * * 74 | ***************************************************************************/ 75 | 76 | // headers: 'content-type' 77 | 78 | }; 79 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/csrf.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Cross-Site Request Forgery Protection Settings 3 | * (sails.config.csrf) 4 | * 5 | * CSRF tokens are like a tracking chip. While a session tells the server that a user 6 | * "is who they say they are", a csrf token tells the server "you are where you say you are". 7 | * 8 | * When enabled, all non-GET requests to the Sails server must be accompanied by 9 | * a special token, identified as the '_csrf' parameter. 10 | * 11 | * This option protects your Sails app against cross-site request forgery (or CSRF) attacks. 12 | * A would-be attacker needs not only a user's session cookie, but also this timestamped, 13 | * secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain. 14 | * 15 | * This allows us to have certainty that our users' requests haven't been hijacked, 16 | * and that the requests they're making are intentional and legitimate. 17 | * 18 | * This token has a short-lived expiration timeline, and must be acquired by either: 19 | * 20 | * (a) For traditional view-driven web apps: 21 | * Fetching it from one of your views, where it may be accessed as 22 | * a local variable, e.g.: 23 | *
24 | * 25 | *
26 | * 27 | * or (b) For AJAX/Socket-heavy and/or single-page apps: 28 | * Sending a GET request to the `/csrfToken` route, where it will be returned 29 | * as JSON, e.g.: 30 | * { _csrf: 'ajg4JD(JGdajhLJALHDa' } 31 | * 32 | * 33 | * Enabling this option requires managing the token in your front-end app. 34 | * For traditional web apps, it's as easy as passing the data from a view into a form action. 35 | * In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token. 36 | * 37 | * For more information on CSRF, check out: 38 | * http://en.wikipedia.org/wiki/Cross-site_request_forgery 39 | * 40 | * For more information on this configuration file, including info on CSRF + CORS, see: 41 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.csrf.html 42 | * 43 | */ 44 | 45 | /**************************************************************************** 46 | * * 47 | * Enabled CSRF protection for your site? * 48 | * * 49 | ****************************************************************************/ 50 | 51 | // module.exports.csrf = false; 52 | 53 | /**************************************************************************** 54 | * * 55 | * You may also specify more fine-grained settings for CSRF, including the * 56 | * domains which are allowed to request the CSRF token via AJAX. These * 57 | * settings override the general CORS settings in your config/cors.js file. * 58 | * * 59 | ****************************************************************************/ 60 | 61 | // module.exports.csrf = { 62 | // grantTokenViaAjax: true, 63 | // origin: '' 64 | // } 65 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/default.yaml: -------------------------------------------------------------------------------- 1 | # swagger configuration file 2 | 3 | # values in the swagger hash are system configuration for swagger-node 4 | swagger: 5 | 6 | fittingsDirs: [ api/fittings ] 7 | defaultPipe: null 8 | swaggerControllerPipe: swagger_controllers # defines the standard processing pipe for controllers 9 | 10 | # values defined in the bagpipes key are the bagpipes pipes and fittings definitions 11 | # (see https://github.com/apigee-127/bagpipes) 12 | bagpipes: 13 | 14 | _router: 15 | name: swagger_router 16 | mockMode: false 17 | mockControllersDirs: [ api/mocks ] 18 | controllersDirs: [ api/controllers ] 19 | 20 | _swagger_validate: 21 | name: swagger_validator 22 | validateResponse: true 23 | 24 | # pipe for all swagger-node controllers 25 | swagger_controllers: 26 | - onError: json_error_handler 27 | - cors 28 | - swagger_params_parser 29 | - swagger_security 30 | - _swagger_validate 31 | - express_compatibility 32 | - _router 33 | 34 | # pipe to serve swagger (endpoint is in swagger.yaml) 35 | swagger_raw: 36 | name: swagger_raw 37 | 38 | # any other values in this file are just loaded into the config for application access... 39 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/env/development.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Development environment settings 3 | * 4 | * This file can include shared settings for a development team, 5 | * such as API keys or remote database passwords. If you're using 6 | * a version control solution for your Sails app, this file will 7 | * be committed to your repository unless you add it to your .gitignore 8 | * file. If your repository will be publicly viewable, don't add 9 | * any private information to this file! 10 | * 11 | */ 12 | 13 | module.exports = { 14 | 15 | /*************************************************************************** 16 | * Set the default database connection for models in the development * 17 | * environment (see config/connections.js and config/models.js ) * 18 | ***************************************************************************/ 19 | 20 | port: 10010 21 | 22 | // models: { 23 | // connection: 'someMongodbServer' 24 | // } 25 | 26 | }; 27 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/env/production.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Production environment settings 3 | * 4 | * This file can include shared settings for a production environment, 5 | * such as API keys or remote database passwords. If you're using 6 | * a version control solution for your Sails app, this file will 7 | * be committed to your repository unless you add it to your .gitignore 8 | * file. If your repository will be publicly viewable, don't add 9 | * any private information to this file! 10 | * 11 | */ 12 | 13 | module.exports = { 14 | 15 | /*************************************************************************** 16 | * Set the default database connection for models in the production * 17 | * environment (see config/connections.js and config/models.js ) * 18 | ***************************************************************************/ 19 | 20 | // models: { 21 | // connection: 'someMysqlServer' 22 | // }, 23 | 24 | /*************************************************************************** 25 | * Set the port in the production environment to 80 * 26 | ***************************************************************************/ 27 | 28 | // port: 80, 29 | 30 | /*************************************************************************** 31 | * Set the log level in production environment to "silent" * 32 | ***************************************************************************/ 33 | 34 | // log: { 35 | // level: "silent" 36 | // } 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/globals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Global Variable Configuration 3 | * (sails.config.globals) 4 | * 5 | * Configure which global variables which will be exposed 6 | * automatically by Sails. 7 | * 8 | * For more information on configuration, check out: 9 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html 10 | */ 11 | module.exports.globals = { 12 | 13 | /**************************************************************************** 14 | * * 15 | * Expose the lodash installed in Sails core as a global variable. If this * 16 | * is disabled, like any other node module you can always run npm install * 17 | * lodash --save, then var _ = require('lodash') at the top of any file. * 18 | * * 19 | ****************************************************************************/ 20 | 21 | // _: true, 22 | 23 | /**************************************************************************** 24 | * * 25 | * Expose the async installed in Sails core as a global variable. If this is * 26 | * disabled, like any other node module you can always run npm install async * 27 | * --save, then var async = require('async') at the top of any file. * 28 | * * 29 | ****************************************************************************/ 30 | 31 | // async: true, 32 | 33 | /**************************************************************************** 34 | * * 35 | * Expose the sails instance representing your app. If this is disabled, you * 36 | * can still get access via req._sails. * 37 | * * 38 | ****************************************************************************/ 39 | 40 | // sails: true, 41 | 42 | /**************************************************************************** 43 | * * 44 | * Expose each of your app's services as global variables (using their * 45 | * "globalId"). E.g. a service defined in api/models/NaturalLanguage.js * 46 | * would have a globalId of NaturalLanguage by default. If this is disabled, * 47 | * you can still access your services via sails.services.* * 48 | * * 49 | ****************************************************************************/ 50 | 51 | // services: true, 52 | 53 | /**************************************************************************** 54 | * * 55 | * Expose each of your app's models as global variables (using their * 56 | * "globalId"). E.g. a model defined in api/models/User.js would have a * 57 | * globalId of User by default. If this is disabled, you can still access * 58 | * your models via sails.models.*. * 59 | * * 60 | ****************************************************************************/ 61 | 62 | // models: true 63 | }; 64 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/http.js: -------------------------------------------------------------------------------- 1 | /** 2 | * HTTP Server Settings 3 | * (sails.config.http) 4 | * 5 | * Configuration for the underlying HTTP server in Sails. 6 | * Only applies to HTTP requests (not WebSockets) 7 | * 8 | * For more information on configuration, check out: 9 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html 10 | */ 11 | 12 | module.exports.http = { 13 | 14 | /**************************************************************************** 15 | * * 16 | * Express middleware to use for every Sails request. To add custom * 17 | * middleware to the mix, add a function to the middleware config object and * 18 | * add its key to the "order" array. The $custom key is reserved for * 19 | * backwards-compatibility with Sails v0.9.x apps that use the * 20 | * `customMiddleware` config option. * 21 | * * 22 | ****************************************************************************/ 23 | 24 | middleware: { 25 | 26 | /*************************************************************************** 27 | * * 28 | * The order in which middleware should be run for HTTP request. (the Sails * 29 | * router is invoked by the "router" middleware below.) * 30 | * * 31 | ***************************************************************************/ 32 | 33 | // order: [ 34 | // 'startRequestTimer', 35 | // 'cookieParser', 36 | // 'session', 37 | // 'myRequestLogger', 38 | // 'bodyParser', 39 | // 'handleBodyParserError', 40 | // 'compress', 41 | // 'methodOverride', 42 | // 'poweredBy', 43 | // '$custom', 44 | // 'router', 45 | // 'www', 46 | // 'favicon', 47 | // '404', 48 | // '500' 49 | // ], 50 | 51 | /**************************************************************************** 52 | * * 53 | * Example custom middleware; logs each request to the console. * 54 | * * 55 | ****************************************************************************/ 56 | 57 | // myRequestLogger: function (req, res, next) { 58 | // console.log("Requested :: ", req.method, req.url); 59 | // return next(); 60 | // } 61 | 62 | 63 | /*************************************************************************** 64 | * * 65 | * The body parser that will handle incoming multipart HTTP requests. By * 66 | * default as of v0.10, Sails uses * 67 | * [skipper](http://github.com/balderdashy/skipper). See * 68 | * http://www.senchalabs.org/connect/multipart.html for other options. * 69 | * * 70 | * Note that Sails uses an internal instance of Skipper by default; to * 71 | * override it and specify more options, make sure to "npm install skipper" * 72 | * in your project first. You can also specify a different body parser or * 73 | * a custom function with req, res and next parameters (just like any other * 74 | * middleware function). * 75 | * * 76 | ***************************************************************************/ 77 | 78 | // bodyParser: require('skipper')({strict: true}) 79 | 80 | }, 81 | 82 | /*************************************************************************** 83 | * * 84 | * The number of seconds to cache flat files on disk being served by * 85 | * Express static middleware (by default, these files are in `.tmp/public`) * 86 | * * 87 | * The HTTP static cache is only active in a 'production' environment, * 88 | * since that's the only time Express will cache flat-files. * 89 | * * 90 | ***************************************************************************/ 91 | 92 | // cache: 31557600000 93 | }; 94 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/i18n.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Internationalization / Localization Settings 3 | * (sails.config.i18n) 4 | * 5 | * If your app will touch people from all over the world, i18n (or internationalization) 6 | * may be an important part of your international strategy. 7 | * 8 | * 9 | * For more informationom i18n in Sails, check out: 10 | * http://sailsjs.org/#!/documentation/concepts/Internationalization 11 | * 12 | * For a complete list of i18n options, see: 13 | * https://github.com/mashpie/i18n-node#list-of-configuration-options 14 | * 15 | * 16 | */ 17 | 18 | module.exports.i18n = { 19 | 20 | /*************************************************************************** 21 | * * 22 | * Which locales are supported? * 23 | * * 24 | ***************************************************************************/ 25 | 26 | // locales: ['en', 'es', 'fr', 'de'], 27 | 28 | /**************************************************************************** 29 | * * 30 | * What is the default locale for the site? Note that this setting will be * 31 | * overridden for any request that sends an "Accept-Language" header (i.e. * 32 | * most browsers), but it's still useful if you need to localize the * 33 | * response for requests made by non-browser clients (e.g. cURL). * 34 | * * 35 | ****************************************************************************/ 36 | 37 | // defaultLocale: 'en', 38 | 39 | /**************************************************************************** 40 | * * 41 | * Automatically add new keys to locale (translation) files when they are * 42 | * encountered during a request? * 43 | * * 44 | ****************************************************************************/ 45 | 46 | // updateFiles: false, 47 | 48 | /**************************************************************************** 49 | * * 50 | * Path (relative to app root) of directory to store locale (translation) * 51 | * files in. * 52 | * * 53 | ****************************************************************************/ 54 | 55 | // localesDirectory: '/config/locales' 56 | 57 | }; 58 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/local.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Local environment settings 3 | * 4 | * Use this file to specify configuration settings for use while developing 5 | * the app on your personal system: for example, this would be a good place 6 | * to store database or email passwords that apply only to you, and shouldn't 7 | * be shared with others in your organization. 8 | * 9 | * These settings take precedence over all other config files, including those 10 | * in the env/ subfolder. 11 | * 12 | * PLEASE NOTE: 13 | * local.js is included in your .gitignore, so if you're using git 14 | * as a version control solution for your Sails app, keep in mind that 15 | * this file won't be committed to your repository! 16 | * 17 | * Good news is, that means you can specify configuration for your local 18 | * machine in this file without inadvertently committing personal information 19 | * (like database passwords) to the repo. Plus, this prevents other members 20 | * of your team from commiting their local configuration changes on top of yours. 21 | * 22 | * In a production environment, you probably want to leave this file out 23 | * entirely and leave all your settings in env/production.js 24 | * 25 | * 26 | * For more information, check out: 27 | * http://sailsjs.org/#!/documentation/anatomy/myApp/config/local.js.html 28 | */ 29 | 30 | module.exports = { 31 | 32 | /*************************************************************************** 33 | * Your SSL certificate and key, if you want to be able to serve HTTP * 34 | * responses over https:// and/or use websockets over the wss:// protocol * 35 | * (recommended for HTTP, strongly encouraged for WebSockets) * 36 | * * 37 | * In this example, we'll assume you created a folder in your project, * 38 | * `config/ssl` and dumped your certificate/key files there: * 39 | ***************************************************************************/ 40 | 41 | // ssl: { 42 | // ca: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl_gd_bundle.crt'), 43 | // key: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl.key'), 44 | // cert: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl.crt') 45 | // }, 46 | 47 | /*************************************************************************** 48 | * The `port` setting determines which TCP port your app will be * 49 | * deployed on. * 50 | * * 51 | * Ports are a transport-layer concept designed to allow many different * 52 | * networking applications run at the same time on a single computer. * 53 | * More about ports: * 54 | * http://en.wikipedia.org/wiki/Port_(computer_networking) * 55 | * * 56 | * By default, if it's set, Sails uses the `PORT` environment variable. * 57 | * Otherwise it falls back to port 1337. * 58 | * * 59 | * In env/production.js, you'll probably want to change this setting * 60 | * to 80 (http://) or 443 (https://) if you have an SSL certificate * 61 | ***************************************************************************/ 62 | 63 | // port: process.env.PORT || 1337, 64 | 65 | /*************************************************************************** 66 | * The runtime "environment" of your Sails app is either typically * 67 | * 'development' or 'production'. * 68 | * * 69 | * In development, your Sails app will go out of its way to help you * 70 | * (for instance you will receive more descriptive error and * 71 | * debugging output) * 72 | * * 73 | * In production, Sails configures itself (and its dependencies) to * 74 | * optimize performance. You should always put your app in production mode * 75 | * before you deploy it to a server. This helps ensure that your Sails * 76 | * app remains stable, performant, and scalable. * 77 | * * 78 | * By default, Sails sets its environment using the `NODE_ENV` environment * 79 | * variable. If NODE_ENV is not set, Sails will run in the * 80 | * 'development' environment. * 81 | ***************************************************************************/ 82 | 83 | // environment: process.env.NODE_ENV || 'development' 84 | 85 | }; 86 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/locales/_README.md: -------------------------------------------------------------------------------- 1 | # Internationalization / Localization Settings 2 | 3 | > Also see the official docs on internationalization/localization: 4 | > http://links.sailsjs.org/docs/config/locales 5 | 6 | ## Locales 7 | All locale files live under `config/locales`. Here is where you can add translations 8 | as JSON key-value pairs. The name of the file should match the language that you are supporting, which allows for automatic language detection based on request headers. 9 | 10 | Here is an example locale stringfile for the Spanish language (`config/locales/es.json`): 11 | ```json 12 | { 13 | "Hello!": "Hola!", 14 | "Hello %s, how are you today?": "¿Hola %s, como estas?", 15 | } 16 | ``` 17 | ## Usage 18 | Locales can be accessed in controllers/policies through `res.i18n()`, or in views through the `__(key)` or `i18n(key)` functions. 19 | Remember that the keys are case sensitive and require exact key matches, e.g. 20 | 21 | ```ejs 22 |

<%= __('Welcome to PencilPals!') %>

23 |

<%= i18n('Hello %s, how are you today?', 'Pencil Maven') %>

24 |

<%= i18n('That\'s right-- you can use either i18n() or __()') %>

25 | ``` 26 | 27 | ## Configuration 28 | Localization/internationalization config can be found in `config/i18n.js`, from where you can set your supported locales. 29 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/locales/de.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Willkommen", 3 | "A brand new app.": "Eine neue App." 4 | } 5 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/locales/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Welcome", 3 | "A brand new app.": "A brand new app." 4 | } 5 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/locales/es.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Bienvenido", 3 | "A brand new app.": "Una nueva aplicación." 4 | } 5 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/locales/fr.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Bienvenue", 3 | "A brand new app.": "Une toute nouvelle application." 4 | } 5 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/log.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Built-in Log Configuration 3 | * (sails.config.log) 4 | * 5 | * Configure the log level for your app, as well as the transport 6 | * (Underneath the covers, Sails uses Winston for logging, which 7 | * allows for some pretty neat custom transports/adapters for log messages) 8 | * 9 | * For more information on the Sails logger, check out: 10 | * http://sailsjs.org/#!/documentation/concepts/Logging 11 | */ 12 | 13 | module.exports.log = { 14 | 15 | /*************************************************************************** 16 | * * 17 | * Valid `level` configs: i.e. the minimum log level to capture with * 18 | * sails.log.*() * 19 | * * 20 | * The order of precedence for log levels from lowest to highest is: * 21 | * silly, verbose, info, debug, warn, error * 22 | * * 23 | * You may also set the level to "silent" to suppress all logs. * 24 | * * 25 | ***************************************************************************/ 26 | 27 | // level: 'info' 28 | 29 | }; 30 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/models.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Default model configuration 3 | * (sails.config.models) 4 | * 5 | * Unless you override them, the following properties will be included 6 | * in each of your models. 7 | * 8 | * For more info on Sails models, see: 9 | * http://sailsjs.org/#!/documentation/concepts/ORM 10 | */ 11 | 12 | module.exports.models = { 13 | 14 | /*************************************************************************** 15 | * * 16 | * Your app's default connection. i.e. the name of one of your app's * 17 | * connections (see `config/connections.js`) * 18 | * * 19 | ***************************************************************************/ 20 | // connection: 'localDiskDb', 21 | 22 | /*************************************************************************** 23 | * * 24 | * How and whether Sails will attempt to automatically rebuild the * 25 | * tables/collections/etc. in your schema. * 26 | * * 27 | * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * 28 | * * 29 | ***************************************************************************/ 30 | // migrate: 'alter' 31 | 32 | }; 33 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/policies.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Policy Mappings 3 | * (sails.config.policies) 4 | * 5 | * Policies are simple functions which run **before** your controllers. 6 | * You can apply one or more policies to a given controller, or protect 7 | * its actions individually. 8 | * 9 | * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed 10 | * below by its filename, minus the extension, (e.g. "authenticated") 11 | * 12 | * For more information on how policies work, see: 13 | * http://sailsjs.org/#!/documentation/concepts/Policies 14 | * 15 | * For more information on configuring policies, check out: 16 | * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html 17 | */ 18 | 19 | 20 | module.exports.policies = { 21 | 22 | /*************************************************************************** 23 | * * 24 | * Default policy for all controllers and actions (`true` allows public * 25 | * access) * 26 | * * 27 | ***************************************************************************/ 28 | 29 | // '*': true, 30 | 31 | /*************************************************************************** 32 | * * 33 | * Here's an example of mapping some policies to run before a controller * 34 | * and its actions * 35 | * * 36 | ***************************************************************************/ 37 | // RabbitController: { 38 | 39 | // Apply the `false` policy as the default for all of RabbitController's actions 40 | // (`false` prevents all access, which ensures that nothing bad happens to our rabbits) 41 | // '*': false, 42 | 43 | // For the action `nurture`, apply the 'isRabbitMother' policy 44 | // (this overrides `false` above) 45 | // nurture : 'isRabbitMother', 46 | 47 | // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies 48 | // before letting any users feed our rabbits 49 | // feed : ['isNiceToAnimals', 'hasRabbitFood'] 50 | // } 51 | }; 52 | -------------------------------------------------------------------------------- /project-skeletons/sails/config/routes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Route Mappings 3 | * (sails.config.routes) 4 | * 5 | * Your routes map URLs to views and controllers. 6 | * 7 | * If Sails receives a URL that doesn't match any of the routes below, 8 | * it will check for matching files (images, scripts, stylesheets, etc.) 9 | * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` 10 | * might match an image file: `/assets/images/foo.jpg` 11 | * 12 | * Finally, if those don't match either, the default 404 handler is triggered. 13 | * See `api/responses/notFound.js` to adjust your app's 404 logic. 14 | * 15 | * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies 16 | * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or 17 | * CoffeeScript for the front-end. 18 | * 19 | * For more information on configuring custom routes, check out: 20 | * http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html 21 | */ 22 | 23 | module.exports.routes = { 24 | 25 | /*************************************************************************** 26 | * * 27 | * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * 28 | * etc. depending on your default view engine) your home page. * 29 | * * 30 | * (Alternatively, remove this and add an `index.html` file in your * 31 | * `assets` directory) * 32 | * * 33 | ***************************************************************************/ 34 | 35 | '/': { 36 | view: 'homepage' 37 | } 38 | 39 | /*************************************************************************** 40 | * * 41 | * Custom routes here... * 42 | * * 43 | * If a request to a URL doesn't match any of the custom routes above, it * 44 | * is matched against Sails route blueprints. See `config/blueprints.js` * 45 | * for configuration options and examples. * 46 | * * 47 | ***************************************************************************/ 48 | 49 | }; 50 | -------------------------------------------------------------------------------- /project-skeletons/sails/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-app", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "New Swagger API Project", 6 | "keywords": [], 7 | "author": "", 8 | "license": "", 9 | "main": "app.js", 10 | "dependencies": { 11 | "ejs": "2.5.5", 12 | "grunt": "1.0.1", 13 | "grunt-contrib-clean": "1.0.0", 14 | "grunt-contrib-coffee": "1.0.0", 15 | "grunt-contrib-concat": "1.0.1", 16 | "grunt-contrib-copy": "1.0.0", 17 | "grunt-contrib-cssmin": "1.0.1", 18 | "grunt-contrib-jst": "1.0.0", 19 | "grunt-contrib-less": "1.3.0", 20 | "grunt-contrib-uglify": "1.0.1", 21 | "grunt-contrib-watch": "1.0.0", 22 | "grunt-sails-linker": "~0.10.1", 23 | "grunt-sync": "0.5.2", 24 | "include-all": "^1.0.0", 25 | "rc": "1.0.1", 26 | "sails": "~0.12.13", 27 | "sails-disk": "~0.10.9", 28 | "swagger-sails-hook": "^0.7.0" 29 | }, 30 | "devDependencies": { 31 | "should": "^11.2.1", 32 | "supertest": "^3.0.0" 33 | }, 34 | "scripts": { 35 | "start": "node app.js", 36 | "debug": "node debug app.js", 37 | "test": "swagger project test" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/README.md: -------------------------------------------------------------------------------- 1 | # About the `tasks` folder 2 | 3 | The `tasks` directory is a suite of Grunt tasks and their configurations, bundled for your convenience. The Grunt integration is mainly useful for bundling front-end assets, (like stylesheets, scripts, & markup templates) but it can also be used to run all kinds of development tasks, from browserify compilation to database migrations. 4 | 5 | If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, read on! 6 | 7 | 8 | ### How does this work? 9 | 10 | The asset pipeline bundled in Sails is a set of Grunt tasks configured with conventional defaults designed to make your project more consistent and productive. 11 | 12 | The entire front-end asset workflow in Sails is completely customizable-- while it provides some suggestions out of the box, Sails makes no pretense that it can anticipate all of the needs you'll encounter building the browser-based/front-end portion of your application. Who's to say you're even building an app for a browser? 13 | 14 | 15 | 16 | ### What tasks does Sails run automatically? 17 | 18 | Sails runs some of these tasks (the ones in the `tasks/register` folder) automatically when you run certain commands. 19 | 20 | ###### `sails lift` 21 | 22 | Runs the `default` task (`tasks/register/default.js`). 23 | 24 | ###### `sails lift --prod` 25 | 26 | Runs the `prod` task (`tasks/register/prod.js`). 27 | 28 | ###### `sails www` 29 | 30 | Runs the `build` task (`tasks/register/build.js`). 31 | 32 | ###### `sails www --prod` (production) 33 | 34 | Runs the `buildProd` task (`tasks/register/buildProd.js`). 35 | 36 | 37 | ### Can I customize this for SASS, Angular, client-side Jade templates, etc? 38 | 39 | You can modify, omit, or replace any of these Grunt tasks to fit your requirements. You can also add your own Grunt tasks- just add a `someTask.js` file in the `grunt/config` directory to configure the new task, then register it with the appropriate parent task(s) (see files in `grunt/register/*.js`). 40 | 41 | 42 | ### Do I have to use Grunt? 43 | 44 | Nope! To disable Grunt integration in Sails, just delete your Gruntfile or disable the Grunt hook. 45 | 46 | 47 | ### What if I'm not building a web frontend? 48 | 49 | That's ok! A core tenant of Sails is client-agnosticism-- it's especially designed for building APIs used by all sorts of clients; native Android/iOS/Cordova, serverside SDKs, etc. 50 | 51 | You can completely disable Grunt by following the instructions above. 52 | 53 | If you still want to use Grunt for other purposes, but don't want any of the default web front-end stuff, just delete your project's `assets` folder and remove the front-end oriented tasks from the `grunt/register` and `grunt/config` folders. You can also run `sails new myCoolApi --no-frontend` to omit the `assets` folder and front-end-oriented Grunt tasks for future projects. You can also replace your `sails-generate-frontend` module with alternative community generators, or create your own. This allows `sails new` to create the boilerplate for native iOS apps, Android apps, Cordova apps, SteroidsJS apps, etc. 54 | 55 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/clean.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `clean` 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Remove the files and folders in your Sails app's web root 7 | * (conventionally a hidden directory called `.tmp/public`). 8 | * 9 | * For usage docs see: 10 | * https://github.com/gruntjs/grunt-contrib-clean 11 | * 12 | */ 13 | module.exports = function(grunt) { 14 | 15 | grunt.config.set('clean', { 16 | dev: ['.tmp/public/**'], 17 | build: ['www'] 18 | }); 19 | 20 | grunt.loadNpmTasks('grunt-contrib-clean'); 21 | }; 22 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/coffee.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `coffee` 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Compile CoffeeScript files located in `assets/js` into Javascript 7 | * and generate new `.js` files in `.tmp/public/js`. 8 | * 9 | * For usage docs see: 10 | * https://github.com/gruntjs/grunt-contrib-coffee 11 | * 12 | */ 13 | module.exports = function(grunt) { 14 | 15 | grunt.config.set('coffee', { 16 | dev: { 17 | options: { 18 | bare: true, 19 | sourceMap: true, 20 | sourceRoot: './' 21 | }, 22 | files: [{ 23 | expand: true, 24 | cwd: 'assets/js/', 25 | src: ['**/*.coffee'], 26 | dest: '.tmp/public/js/', 27 | ext: '.js' 28 | }] 29 | } 30 | }); 31 | 32 | grunt.loadNpmTasks('grunt-contrib-coffee'); 33 | }; 34 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/concat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `concat` 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Concatenates the contents of multiple JavaScript and/or CSS files 7 | * into two new files, each located at `concat/production.js` and 8 | * `concat/production.css` respectively in `.tmp/public/concat`. 9 | * 10 | * This is used as an intermediate step to generate monolithic files 11 | * that can then be passed in to `uglify` and/or `cssmin` for minification. 12 | * 13 | * For usage docs see: 14 | * https://github.com/gruntjs/grunt-contrib-concat 15 | * 16 | */ 17 | module.exports = function(grunt) { 18 | 19 | grunt.config.set('concat', { 20 | js: { 21 | src: require('../pipeline').jsFilesToInject, 22 | dest: '.tmp/public/concat/production.js' 23 | }, 24 | css: { 25 | src: require('../pipeline').cssFilesToInject, 26 | dest: '.tmp/public/concat/production.css' 27 | } 28 | }); 29 | 30 | grunt.loadNpmTasks('grunt-contrib-concat'); 31 | }; 32 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/copy.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `copy` 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Copy files and/or folders from your `assets/` directory into 7 | * the web root (`.tmp/public`) so they can be served via HTTP, 8 | * and also for further pre-processing by other Grunt tasks. 9 | * 10 | * #### Normal usage (`sails lift`) 11 | * Copies all directories and files (except CoffeeScript and LESS) 12 | * from the `assets/` folder into the web root -- conventionally a 13 | * hidden directory located `.tmp/public`. 14 | * 15 | * #### Via the `build` tasklist (`sails www`) 16 | * Copies all directories and files from the .tmp/public directory into a www directory. 17 | * 18 | * For usage docs see: 19 | * https://github.com/gruntjs/grunt-contrib-copy 20 | * 21 | */ 22 | module.exports = function(grunt) { 23 | 24 | grunt.config.set('copy', { 25 | dev: { 26 | files: [{ 27 | expand: true, 28 | cwd: './assets', 29 | src: ['**/*.!(coffee|less)'], 30 | dest: '.tmp/public' 31 | }] 32 | }, 33 | build: { 34 | files: [{ 35 | expand: true, 36 | cwd: '.tmp/public', 37 | src: ['**/*'], 38 | dest: 'www' 39 | }] 40 | } 41 | }); 42 | 43 | grunt.loadNpmTasks('grunt-contrib-copy'); 44 | }; 45 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/cssmin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Compress CSS files. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Minify the intermediate concatenated CSS stylesheet which was 7 | * prepared by the `concat` task at `.tmp/public/concat/production.css`. 8 | * 9 | * Together with the `concat` task, this is the final step that minifies 10 | * all CSS files from `assets/styles/` (and potentially your LESS importer 11 | * file from `assets/styles/importer.less`) 12 | * 13 | * For usage docs see: 14 | * https://github.com/gruntjs/grunt-contrib-cssmin 15 | * 16 | */ 17 | module.exports = function(grunt) { 18 | 19 | grunt.config.set('cssmin', { 20 | dist: { 21 | src: ['.tmp/public/concat/production.css'], 22 | dest: '.tmp/public/min/production.min.css' 23 | } 24 | }); 25 | 26 | grunt.loadNpmTasks('grunt-contrib-cssmin'); 27 | }; 28 | -------------------------------------------------------------------------------- /project-skeletons/sails/tasks/config/jst.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `jst` 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Precompile HTML templates using Underscore/Lodash notation into 7 | * functions, creating a `.jst` file. This can be brought into your HTML 8 | * via a