cardx-billing-plans
v1.1.10
Published
A repo for charging billing plan resources.
Downloads
243
Readme
Cloud Development Kit
Usage
Install dependencies in the root folder
npm install
Example of creating a lambda without an authorizer
./lambda/src/index.js/
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
/** * 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
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/*
| Tagsandbox-*
| | NPD-EDG | Branchmain
| Tagdevelop-*
| | NPD-BTA | N/A | Tagbeta-*
| | PRD-DMO | N/A | Tagdemo-*
| | PRD-TST | N/A | Tagv0.*
| | PRD-PRD | N/A | Tagv0.*
|- 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 ofsandbox-*
- When deploying to production, run
npm minor
to automatically apply a tag ofv0.*
for the current version, then push up this tag
Connecting to Bitbucket
- cd to your local git repo - In the console, input `git add --all` - Then input `git commit` and give a proper message - In Bitbucket, inside the new Bitbucket repo, you created, naviagate to `source`. - You will see in the section `Get your local Git repository on Bitbucket`, in step 2 a command that starts with `git remote add origin` - Copy this line to your command line and run it - Afterwards, input in the command, `git push -u origin main` - Your local repo will be connected to the git repo afterwards
Tagging Process
- In the console, input `git add --all` - Then input `git commit` and give a proper message - Input `git tag` followed by the tag you want for the commit. Tags would usually have a commit hash attached. An example is `git tag sandbox-h7438jre` - Afterwards, to push up the tags to bitbucket, input `git push --tags`
Database
Creating Migrations
- 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
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);
};
Creating Seeds & Seeding Database
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 namedhello_cdk_sample_table
, the file you will have here ishello_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
// 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`
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;
Querying our database
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
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
/**
* @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
// ...
});
Testing
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 test
- To run a test suite that continuously watches changed files, run
npm run test:watch
Running API Gateway
- Go to the Cloudformation stack in
AWS
->Cloudformation
- Go to your stack and click on
Outputs
- The url to the API Gateway will have a key of
*ApiGatewayUrl
Dependency List
## CDK Dependency List
- `@cardx/common`
- `@cardx/lambda-handler`
- `@aws-cdk/core`
- `@aws-cdk/aws-iam`
- `@aws-cdk/aws-ec2`
- `@aws-cdk/aws-certificatemanager`
- `@aws-cdk/aws-apigateway`
- `dotenv`
## CDK 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`
CDK Documentation
- 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
License
© CardX. All rights reserved.