Skip to content

Commit

Permalink
First early version
Browse files Browse the repository at this point in the history
  • Loading branch information
YoruNoHikage committed Aug 22, 2016
0 parents commit ed3c903
Show file tree
Hide file tree
Showing 5 changed files with 257 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
npm-debug.log
node_modules/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2016 Alexis Launay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Apex API Gateway
================

`apex-api-gateway` helps you deploying your Apex project into API Gateway. This is an early version, only basic commands are available.
If you need more advanced features, you can use [AWS CLI](https://aws.amazon.com/fr/cli/).

Installation
------------

`npm install -g apex-api-gateway`

Usage
-----

```
Usage: apex-api-gateway <command> [options]
Commands:
create <name> [description] [cloneFrom] Create a new REST API on AWS API Gateway
update Update the REST API with the new Swagger definitions
Options:
-c, --config Apex project JSON file location
--help Display help [boolean]
```

To create an API and update Apex's configuration automatically, just simply do :

`apex-api-gateway create 'My Awesome API'`

Define swagger file in every `function.json` you have and main project.json (this should be done automatically later).
You can check out the [Apex API Gateway Boilerplate](https://github.com/YoruNoHikage/apex-api-gateway-boilerplate).

And to update API :

`apex-api-gateway update`
175 changes: 175 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const defaultsDeep = require('lodash.defaultsDeep');
const yargs = require('yargs');
const AWS = require('aws-sdk');
const apigateway = new AWS.APIGateway();

const args = yargs
.usage('Usage: $0 <command> [options]')
.alias('c', 'config')
.nargs('c', 1)
.describe('c', 'Apex project JSON file location')
.command('create <name> [description] [cloneFrom]', 'Create a new REST API on AWS API Gateway', {
force: { alias: 'f', describe: 'Force creating REST API overriding existing configuration' }
}, create)
.command('update', 'Update the REST API with the new Swagger definitions', {
stdout: { describe: 'Output swagger to console without deploying' },
}, update)
.help()
.argv;

function create({ name, description = null, cloneFrom = '', config = './project.json', force }) {
const projectConfig = loadConfig(config);

if(!force && projectConfig && projectConfig['x-api-gateway'] && projectConfig['x-api-gateway']['rest-api-id']) {
console.error('A REST API id is already defined the project.json, if you really want to override this use -f parameter');
return;
}

var params = {
name,
cloneFrom,
description,
};
apigateway.createRestApi(params, (err, data) => {
if (err) {
console.log(err, err.stack);
return;
}

const updatedConfig = JSON.stringify(
Object.assign({}, projectConfig, {
['x-api-gateway']: Object.assign({}, projectConfig['x-api-gateway'], {'rest-api-id': data.id})
}),
null,
2
);

fs.writeFile(config, updatedConfig, (err) => {
if (err) throw err;

console.log('Success! Now you can push your REST API using update command.');
});
});
}

function update({ config, stdout }) {
const projectConfig = loadConfig(config);

if(!projectConfig['x-api-gateway'] || !projectConfig['x-api-gateway']['rest-api-id']) {
throw new Error('Missing REST API id, you might want to use create command first.');
}

const restApiId = projectConfig['x-api-gateway']['rest-api-id'];

const renderMethod = (name, { description, ['x-api-gateway']: { parameters } }) => {
const template = projectConfig['x-api-gateway']['swagger-func-template'];
return defaultsDeep(
{
description,
['x-amazon-apigateway-integration']: {
httpMethod: 'post',
uri: template['x-amazon-apigateway-integration'].uri.replace('{{functionName}}', `${projectConfig.name}_${name}`),
},
parameters,
},
template
);
};

const renderPaths = (functions) => {
const paths = {};

functions.map(({ name, definition }) => {
const { path, method } = definition['x-api-gateway'];
if(!path || !method) {
return;
}

paths[path] = paths[path] || {};
paths[path][method] = renderMethod(name, definition);
});

return paths;
};

const functionsDefs = fs
.readdirSync(path.join(process.cwd(), './functions'))
.map((folder) => {
try {
const functionDef = require(path.join(process.cwd(), `./functions/${folder}/function.json`));

return {
name: folder,
definition: functionDef,
};
} catch(e) { return; }
});

const swagger = {
"swagger": "2.0",
"info": {
"version": (new Date()).toISOString(),
"title": projectConfig.name,
},
"basePath": projectConfig['x-api-gateway'].base_path,
"schemes": [
"https"
],
"paths": renderPaths(functionsDefs),
"securityDefinitions": {
"api_key": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
}
},
"definitions": {
"Empty": {
"type": "object"
}
}
};

if(stdout) {
process.stdout.write(JSON.stringify(swagger, null, 2));
return;
}

console.log('Pushing REST API...');

const params = {
body: JSON.stringify(swagger),
restApiId,
mode: 'overwrite',
};
apigateway.putRestApi(params, (err, data) => {
if (err) {
console.log(err, err.stack);
return;
}

console.log('Updated API with success!');
console.log('Deploying REST API...');

const params = {
restApiId,
stageName: projectConfig['x-api-gateway']['stage_name'],
};
apigateway.createDeployment(params, (err, data) => {
if (err) {
console.log(err, err.stack);
return;
}

console.log('API deployed successfully!');
});
});
}

function loadConfig(projectFile = './project.json') {
return require(path.join(process.cwd(), projectFile));
}
23 changes: 23 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "apex-api-gateway",
"version": "0.1.0",
"licence": "MIT",
"description": "Create and deploy your Apex project on AWS API Gateway using Swagger configuration",
"keywords": [
"apex",
"swagger",
"aws lambda",
"aws api gateway",
"cli"
],
"author": "Alexis Launay <[email protected]> (http://yorunohikage.fr)",
"repository": "YoruNoHikage/apex-api-gateway",
"dependencies": {
"aws-sdk": "^2.5.2",
"lodash.defaultsdeep": "^4.5.1",
"yargs": "^5.0.0"
},
"bin": {
"apex-api-gateway": "index.js"
}
}

0 comments on commit ed3c903

Please sign in to comment.