Skip to content

Commit

Permalink
feat(@whook/example): using the body attribute to set open api config
Browse files Browse the repository at this point in the history
  • Loading branch information
nfroidure committed Apr 5, 2020
1 parent b730dc9 commit df1641e
Show file tree
Hide file tree
Showing 9 changed files with 498 additions and 297 deletions.
617 changes: 421 additions & 196 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/whook-example/package.json
Expand Up @@ -61,6 +61,7 @@
"precz": "npm run compile",
"prettier": "prettier --write 'src/**/*.ts'",
"preversion": "npm run compile",
"build": "npm run compile && NODE_ENV=${NODE_ENV:-development} node bin/build",
"start": "NODE_ENV=${NODE_ENV:-development} node bin/start",
"test": "NODE_ENV=test npm run build && npm run jest",
"types": "rimraf -f 'dist/**/*.d.ts' && tsc --project . --declaration --emitDeclarationOnly --outDir dist",
Expand Down
10 changes: 8 additions & 2 deletions packages/whook-example/src/build.test.ts
Expand Up @@ -4,12 +4,18 @@ describe('build should work', () => {
[
['getPing', '{}'],
['getOpenAPI', '{}'],
[
'getParameters',
'{ "aHeader": "true", "pathParam1":"4", "pathParam2":"a,b,c,d" }',
],
['getTime', '{}'],
['getDelay', '{ "duration": 1 }'],
['putEcho', '{"body": { "echo": "YOLO!" }}'],
].forEach(([operationId]) => {
].forEach(([operationId, parameters]) => {
it(`with ${operationId} http lambdas`, async () => {
await execCommand(`npx whook testHTTPLambda --name ${operationId}`);
await execCommand(
`npx whook testHTTPLambda --name ${operationId} -- parameters '${parameters}'`,
);
});
});

Expand Down
69 changes: 51 additions & 18 deletions packages/whook-example/src/commands/terraformValues.ts
Expand Up @@ -96,24 +96,8 @@ async function initTerraformValuesCommand({
pathsIndex: number;
lambdaType: string;
};
if (type === 'globals') {
const commitHash = await execAsync(`git rev-parse HEAD`);
const commitMessage = (
await execAsync(`git rev-list --format=%B --max-count=1 HEAD`)
).split('\n')[1];
const openapiHash = crypto
.createHash('md5')
.update(JSON.stringify(API))
.digest('hex');
const infos = {
commitHash,
commitMessage,
openapiHash,
};
log('info', JSON.stringify(infos));
return;
}
const configurations = getOpenAPIOperations(API).map(operation => {
const allOperations = await getOpenAPIOperations(API);
const configurations = allOperations.map(operation => {
const whookConfiguration = (operation['x-whook'] || {
type: 'http',
}) as WhookAWSLambdaBuildConfiguration;
Expand All @@ -124,6 +108,7 @@ async function initTerraformValuesCommand({
contentHandling: 'CONVERT_TO_TEXT',
description: operation.summary || '',
enabled: 'true',
operationId: operation.operationId,
sourceOperationId: operation.operationId,
suffix: '',
...Object.keys(whookConfiguration).reduce(
Expand Down Expand Up @@ -152,6 +137,54 @@ async function initTerraformValuesCommand({
};
});

if (type === 'globals') {
const commitHash = await execAsync(`git rev-parse HEAD`);
const commitMessage = (
await execAsync(`git rev-list --format=%B --max-count=1 HEAD`)
).split('\n')[1];
const openapi = JSON.stringify({
...API,
servers: [],
paths: configurations
.filter(({ type }) => !type || type === 'http')
.reduce((currentPaths, configuration) => {
return {
...currentPaths,
[configuration.path]: {
...(currentPaths[configuration.path] || {}),
[configuration.method.toLowerCase()]: {
...((API.paths[configuration.path] || {})[
configuration.method.toLowerCase()
] || {}),
operationId: configuration.qualifiedOperationId,
responses: {},
['x-amazon-apigateway-integration']: {
uri: `\${${configuration.qualifiedOperationId}}`,
httpMethod: 'POST',
contentHandling: 'CONVERT_TO_TEXT',
timeoutInMillis: parseInt(configuration.timeout, 10) * 1000,
type: 'aws_proxy',
},
},
},
};
}, {}),
});

const openapiHash = crypto
.createHash('md5')
.update(JSON.stringify(API))
.digest('hex');
const infos = {
commitHash,
commitMessage,
openapi,
openapiHash,
};
log('info', JSON.stringify(infos));
return;
}

if (type === 'lambdas') {
const lambdas = configurations
.filter(configuration =>
Expand Down
Expand Up @@ -33,12 +33,9 @@ Array [
"options /openAPI",
"options /ping",
"options /time",
<<<<<<< HEAD
"options /{pathParam1}/{pathParam2}",
=======
"post /consumer/messages",
"post /cron/minutes",
>>>>>>> feat(@whook/example): add AWS build to @whook/example
"put /echo",
]
`;
Expand Down
15 changes: 13 additions & 2 deletions packages/whook-example/terraform/api_gateway.tf
Expand Up @@ -9,6 +9,16 @@ resource "aws_internet_gateway" "api_gateway" {
}
}

data "template_file" "template_file" {
template = data.external.globals.result["openapi"]

vars = zipmap(
keys(data.external.api_lambdas.result),
[for key in keys(data.external.api_lambdas.result) : aws_lambda_function.lambda_function[key].invoke_arn]
)
}


resource "aws_api_gateway_rest_api" "api_gateway_rest_api" {
name = "Whook API (${terraform.workspace})"
description = "Whook API"
Expand All @@ -20,17 +30,18 @@ resource "aws_api_gateway_rest_api" "api_gateway_rest_api" {
"image/webp",
"application/pdf"
]
body = data.template_file.template_file.rendered
depends_on = [aws_lambda_function.lambda_function]
}

resource "aws_api_gateway_deployment" "api_gateway_deployment" {
rest_api_id = aws_api_gateway_rest_api.api_gateway_rest_api.id
rest_api_id = aws_api_gateway_rest_api.api_gateway_rest_api.id
# This has to be left empty to let api_gateway_stage
# manage the stage options
stage_name = ""
stage_description = "Deployment checksums ${data.external.globals.result["openapiHash"]}-${data.external.globals.result["commitHash"]}"
description = data.external.globals.result["commitMessage"]
depends_on = [aws_api_gateway_integration.api_gateway_integration]
depends_on = [aws_api_gateway_rest_api.api_gateway_rest_api]

lifecycle {
create_before_destroy = true
Expand Down
26 changes: 0 additions & 26 deletions packages/whook-example/terraform/api_lambdas.tf
Expand Up @@ -10,29 +10,3 @@ resource "aws_lambda_permission" "lambdas" {
function_name = aws_lambda_function.lambda_function[each.key].arn
principal = "apigateway.amazonaws.com"
}

resource "aws_api_gateway_method" "api_gateway_method" {
for_each = data.external.api_lambdas.result
rest_api_id = aws_api_gateway_rest_api.api_gateway_rest_api.id
resource_id = (
split("|", each.value)[1] == "0" ?
aws_api_gateway_resource.api_gateway_resource0[split("|", each.value)[0]].id :
aws_api_gateway_resource.api_gateway_resource1[split("|", each.value)[0]].id
)
http_method = data.external.lambdaConfigurations[each.key].result["method"]
authorization = "NONE"
}

resource "aws_api_gateway_integration" "api_gateway_integration" {
for_each = data.external.api_lambdas.result
rest_api_id = aws_api_gateway_rest_api.api_gateway_rest_api.id
resource_id = (
split("|", each.value)[1] == "0" ?
aws_api_gateway_resource.api_gateway_resource0[split("|", each.value)[0]].id :
aws_api_gateway_resource.api_gateway_resource1[split("|", each.value)[0]].id
)
http_method = aws_api_gateway_method.api_gateway_method[each.key].http_method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.lambda_function[each.key].invoke_arn
}
50 changes: 0 additions & 50 deletions packages/whook-example/terraform/api_paths.tf

This file was deleted.

4 changes: 4 additions & 0 deletions packages/whook-example/terraform/main.tf
Expand Up @@ -7,6 +7,10 @@ provider "archive" {
version = "~> 1.3"
}

provider "template" {
version = "~> 2.1.2"
}

output api_url {
value = aws_api_gateway_deployment.api_gateway_deployment.invoke_url
}
Expand Down

0 comments on commit df1641e

Please sign in to comment.