A repo for charging billing plan resources.
npm install cardx-billing-plans1. Install dependencies in the root folder
npm install
2. Example of creating a lambda without an authorizer
#### ./lambda/src/index.js/
``javascript
const handler = require("@cardx/lambda-handler");
/**
* @param {Object} event - API Gateway Lambda Proxy Event
* @returns {Object} object - API Gateway Lambda Proxy Response
*/
const helloCDKHandler = handler("HelloCDKHandler", async event => {
handler.log.info(JSON.stringify(event, null, 3));
return {
statusCode: 200,
body: {
model: event.pathParameters.model,
action: event.pathParameters.action,
data: "Success CDK Call!",
env: process.env.SAMPLE_ENV
}
};
});
module.exports = {
helloCDKHandler
};
`
#### ./lib/cloud-development-kit-stack.js
`javascript
/**
* Creation process of lambda w/out an authorizer
*/
// 1 - Declare and initiate the Lambda Function
const helloCdk = new lambda.Function(this, "ReportsHandler", {
vpc,
timeout: Duration.seconds(30),
runtime: lambda.Runtime.NODEJS_10_X,
code: lambda.Code.asset("lambda/src"), // Path to the script holding this lambda
handler: "index.helloCDKHandler", // Specific handler to connect to this lambda
environment: {
SAMPLE_ENV: "Sample_Env_Variable"
}
});
// 2 - Attach EC2 Network Policy to Lambda
helloCdk.addToRolePolicy(ec2NetworkPolicy);
// 3 - Create Lambda Integration w/ API Gateway
const helloCdkIntegration = new apigw.LambdaIntegration(helloCdk);
// 4 - We'll create sample resources to invoke the helloCdk lambda
const helloCdkResource = v1.addResource("hello-cdk");
const helloCdkModel = helloCdkResource.addResource("{model}"); // 'model' is a variable within pathParameters
const helloCdkAction = helloCdkModel.addResource("{action}"); // action is a variable within pathParameters
// 5 - Add methods to the resources we declared above
helloCdkAction.addMethod("ANY", helloCdkIntegration, {});
helloCdkAction.addMethod("GET", helloCdkIntegration, {}); // Apply a lambda integration for a specific HTTP method
`
3. Deployment // TODO This still has to be finished
Note: The "*" character is a wildcard symbol in the table below. For tags, these are usually commit hashes. For feature branches, these are usually tied to the Jira story you are working on.
| Environment | Pipeline Branch Trigger | Pipeline Tag Trigger |
| ----------- | ----------------------- | -------------------- |
| SBX-SBX | Branch feature/ | Tag sandbox- |main
| NPD-EDG | Branch | Tag develop-* |beta-*
| NPD-BTA | N/A | Tag |demo-*
| PRD-DMO | N/A | Tag |v0.*
| PRD-TST | N/A | Tag |v0.*
| PRD-PRD | N/A | Tag |
*
- Connect this project to the repo you created above, if not done so already
- Deployment is based off environment. For example, to push up to the sandbox environment, either push to a branch named feature/ or push up a tag of sandbox-npm minor
- When deploying to production, run to automatically apply a tag of v0.* for the current version, then push up this tag
Connecting to Bitbucket
- cd to your local git repo
- In the console, input git add --allgit commit
- Then input and give a proper messagesource
- In Bitbucket, inside the new Bitbucket repo, you created, naviagate to .Get your local Git repository on Bitbucket
- You will see in the section , in step 2 a command that starts with git remote add origingit push -u origin main
- Copy this line to your command line and run it
- Afterwards, input in the command,
- Your local repo will be connected to the git repo afterwards
Tagging Process
- In the console, input git add --allgit commit
- Then input and give a proper messagegit tag
- Input followed by the tag you want for the commit. Tags would usually have a commit hash attached. An example is git tag sandbox-h7438jregit push --tags
- Afterwards, to push up the tags to bitbucket, input
---
- In the Root folder, run in the console, 'npm run migrate:make'
- Inside lambda/src/database/migrations, you should see a timestamp of today followed by "\_schema.js"
- Below is a sample snippet of creating a table with columns of different types
#### ./lambda/src/database/migrations/20200218155641_schema.js
`javascript
exports.up = function (knex) {
return knex.schema.createTable(HELLO_CDK_TABLE, table => {
table.increments("id").primary(); // Primary Key - Every table should have this
table.string("example_string_column"); // Example of a string column
table.index(
["example_string_column"],
idx_${HELLO_CDK_TABLE}_example_string_column
); // Example of an index on a column
table.date("example_date_column"); // Example of a date column
table.decimal("example_decimal_column", 13, 2); // Example of a decimal column
table.bigInteger("example_big_integer_column", 13, 2); // Example of a big integer column
// These three lines are timestamp we need for the tables we creat here in CardX
table.timestamp("created_at").defaultTo(knex.raw("CURRENT_TIMESTAMP"));
table
.timestamp("updated_at")
.defaultTo(knex.raw(UPDATED_AT_DEFAULT_TO_RAW));
table.timestamp("deleted_at").nullable();
});
};
// Exports.down basically does the inverse of what was made in the exports.up
exports.down = function (knex) {
return knex.schema.dropTable(HELLO_CDK_TABLE);
};
`
NOTE: Seeds are only run in the SBX & NPD Environment! They are disabled for the PRD environment!
- In the directory ./lambda/src/database/var/, create a file for what you will seed. The name does not matter here, but a good convention is to have the name of the table be followed by _seed.js. So if a table was named hello_cdk_sample_table, the file you will have here is hello_cdk_sample_table_seed.js
- Below is an example of what seed file will look like
#### ./lambda/src/database/var/hello_cdk_sample_table_seed.js
`javascript`
// An array is exported with individual objects as rows that have a property as the column name and the value of that column for that particular row
module.exports = [
{
id: 1, // Ex. Column = id, Value = 1
example_string_column: "Ketchup", // Ex. Column = example_string_column, Value = "Ketchup"
example_date_column: "2020-04-01",
example_decimal_column: 0.35,
example_big_integer_column: 9464649494
}
];
- Afterwards, in the directory ./lambda/src/database/seeds/ create the file that will run the seed for the specific table you want. A naming scheme to follow is something similar to, in this case, 001_hello_cdk_sample_table.js. "001" tells the migration to run this specific file first and etc. The naming scheme is then similar to the previous step.
#### ./lambda/src/database/seeds/001_hello_cdk_sample_table.js
``javascript
const hello_cdk_sample_table = require("../var/hello_cdk_sample_table_seed"); // Requiring the seed we created in the previous step. The result of this is an array.
function seed(knex) {
return knex("hello_cdk_sample_table") // The table we want to seed
.del() // We make sure to clear out the table
.then(() => knex("hello_cdk_sample_table").insert(hello_cdk_sample_table)); // We insert the records from the array into our table
}
exports.seed = seed;
`
`txt`
This CDK Template uses an ORM (Obeject Relational Management) tool called Objection.js. Objection is an abstraction layer above Knex that allows the developer to query, setup relationships between tables and other such database tasks through JS calls. Objection is a whole different topic altogether, but a simple query of connecting to a table and querying for a row is shown here.
- We setup a model file where we setup the "connection" to our database
#### ./lambda/src/database/models/hello_cdk_sample_table.js
`javascript
const { Model } = require("objection"); // We require the Model Object from Objection
const { HELLO_CDK_TABLE } = require("../db_constants"); // A Helper constant that refers to our desired table name
class Hello_Cdk_Sample_Table extends Model {
static get tableName() {
return HELLO_CDK_TABLE; // This is how we "connect" to our desired table
}
}
module.exports = Hello_Cdk_Sample_Table; // Export out this class
`
#### ./lambda/src/index.js
`javascript
/**
* @param {Object} event - API Gateway Lambda Proxy Event
* @returns {Object} object - API Gateway Lambda Proxy Response
*/
const helloCDKDBHandler = handler("HelloCDKHandler", async _ => {
// Initialize our database
await initKnex();
const resp = await Hello_Cdk_Sample_Table.query().where({ id: 1 }); // Returns an array
// Format our response
// ...
// Destroy our database connection
await destroyKnex();
// Return back our response
// ...
});
`
---
`txt`
Any tests files should be put inside "./lambda/src/__tests__". The names of the spec files should be "*.spec.js". Ideally, write tests before implementation.
- To run a test suite, in the root folder run npm testnpm run test:watch
- To run a test suite that continuously watches changed files, run
---
- Go to the Cloudformation stack in AWS -> CloudformationOutputs
- Go to your stack and click on *ApiGatewayUrl
- The url to the API Gateway will have a key of
`
- @cardx/lambda-handler
- @aws-cdk/core
- @aws-cdk/aws-iam
- @aws-cdk/aws-ec2
- @aws-cdk/aws-certificatemanager
- @aws-cdk/aws-apigateway
- dotenvCDK Dev Dependency List
- @aws-cdk/assert
- @babel/cli
- @babel/core
- @babel/preset-env
- aws-cdk
- babel-jest
- eslint
- eslint-config-airbnb-base
- eslint-config-prettier
- eslint-plugin-import
- eslint-plugin-jest
- eslint-plugin-prettier
- husky
- jest
- jest-extended
- lint-staged
- mysql
- prettier
- rimraf
- sqlite3``---
- API REFERENCE: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html
- DEVELOPER GUIDE: https://docs.aws.amazon.com/cdk/latest/guide/home.html
---
© CardX. All rights reserved.