### Deploying Simple-CDK Examples Source: https://github.com/pujaaan/simple-cdk/blob/main/examples/02-with-models/README.md Commands to install dependencies, build the project, and deploy the example stack. ```bash npm install # at the monorepo root npm run build # at the monorepo root cd examples/02-with-models npm run list npm run synth npm run deploy ``` -------------------------------- ### Run simple-cdk commands Source: https://github.com/pujaaan/simple-cdk/blob/main/examples/01-minimal/README.md Commands to install dependencies, build, list adapters, synthesize, and deploy the minimal example. ```bash npm install # at the monorepo root npm run build # at the monorepo root cd examples/01-minimal npm run list # see what each adapter discovered npm run synth # generate CloudFormation npm run deploy # push to AWS (requires AWS credentials) ``` -------------------------------- ### Clone Simple CDK Repository and Run Examples Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Clone the Simple CDK repository to work on the project itself or run the provided examples. This involves installing dependencies, building the project, and running example commands. ```bash git clone https://github.com/pujaaan/simple-cdk.git cd simple-cdk npm install npm run build cd examples/01-minimal npm run list npm run deploy ``` -------------------------------- ### Install @simple-cdk/dynamodb Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-dynamodb/README.md Install the dynamodb adapter along with core dependencies. ```bash npm install @simple-cdk/dynamodb @simple-cdk/core aws-cdk-lib constructs ``` -------------------------------- ### Install dependencies Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-appsync/README.md Install the required packages for the simple-cdk AppSync adapter. ```bash npm install @simple-cdk/appsync @simple-cdk/core @simple-cdk/dynamodb @simple-cdk/lambda aws-cdk-lib constructs ``` -------------------------------- ### Install @simple-cdk/cognito Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-cognito/README.md Install the necessary packages for the @simple-cdk/cognito adapter and its dependencies. ```bash npm install @simple-cdk/cognito @simple-cdk/core aws-cdk-lib constructs ``` -------------------------------- ### Initialize simple-cdk Project Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Run this command in any folder to initialize a new simple-cdk project. It prompts for app details and installs necessary packages. ```bash mkdir my-app && cd my-app npx simple-cdk@latest init ``` -------------------------------- ### Install RDS and Outputs Packages Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Install the necessary packages for RDS and bundled-outputs. ```bash npm install @simple-cdk/rds @simple-cdk/outputs ``` -------------------------------- ### Install simple-cdk Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/cli/README.md Installs the simple-cdk binary along with necessary AWS CDK libraries. Ensure Node.js 22+ is installed. ```bash npm install simple-cdk aws-cdk-lib constructs ``` -------------------------------- ### Install simple-cdk Core and Adapters Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Manually install simple-cdk core packages and specific adapters if you skip the `init` command. Ensure Node 22+ and AWS credentials are set up. ```bash npm install aws-cdk-lib constructs aws-cdk npm install @simple-cdk/core simple-cdk # adapters: install only the ones you need npm install @simple-cdk/lambda @simple-cdk/dynamodb @simple-cdk/appsync @simple-cdk/cognito ``` -------------------------------- ### Install @simple-cdk/core Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/core/README.md Install the core package along with AWS CDK and constructs using npm. ```bash npm install @simple-cdk/core aws-cdk-lib constructs ``` -------------------------------- ### Clone and Build Simple CDK Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Clone the Simple CDK repository and install dependencies to hack on the project or run examples. ```bash git clone https://github.com/pujaaan/simple-cdk.git cd simple-cdk npm install npm run build ``` -------------------------------- ### Initialize Simple CDK Project with `init` Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Use the `init` command to scaffold a new Simple CDK project. This command guides you through setting up the app name, AWS region, default stage, and selecting built-in adapters. ```bash mkdir my-app && cd my-app npx simple-cdk@latest init ``` -------------------------------- ### Install @simple-cdk/lambda dependencies Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-lambda/README.md Install the required packages to use the lambda adapter in your CDK project. ```bash npm install @simple-cdk/lambda @simple-cdk/core aws-cdk-lib constructs ``` -------------------------------- ### Canonical Adapter Order Example Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Ordering.md This is a common and recommended order for adapters in `config.adapters`. It ensures that dependencies between adapters are correctly managed. ```typescript adapters: [ lambdaAdapter(), dynamoDbAdapter(), cognitoAdapter(), rdsAdapter({ engine: 'postgres' }), appSyncAdapter({ schemaFile: 'schema.graphql' }), // your custom wiring adapters outputsAdapter({ collect: (ctx) => ({ ... }) }), ] ``` -------------------------------- ### GraphQL Schema Example Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Defines a simple GraphQL schema with a 'hello' query that returns a String. This file is referenced in the AppSync adapter configuration. ```graphql # schema.graphql type Query { hello: String } ``` -------------------------------- ### Install Simple CDK Manually Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Install Simple CDK and its dependencies manually if you prefer to manage versions or wire up the project yourself. This includes setting the package type to module. ```bash mkdir my-app && cd my-app npm init -y npm pkg set type=module npm install aws-cdk-lib constructs aws-cdk npm install @simple-cdk/core simple-cdk npm install @simple-cdk/lambda @simple-cdk/appsync ``` -------------------------------- ### Configure Simple CDK with `simple-cdk.config.ts` Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Define your application's configuration, including app name, default stage, and adapters. This example configures Lambda and AppSync adapters with a schema file and resolvers. ```typescript import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { appSyncAdapter } from '@simple-cdk/appsync'; export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1', removalPolicy: 'destroy', logRetentionDays: 7 }, }, adapters: [ lambdaAdapter(), appSyncAdapter({ schemaFile: 'schema.graphql', resolvers: [ { typeName: 'Query', fieldName: 'hello', source: { kind: 'lambda', lambdaName: 'hello' } }, ], }), ], }); ``` -------------------------------- ### Composing Stacks in bin/app.ts Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Adopting.md This example demonstrates how to integrate Simple CDK adapters with existing AWS CDK stacks by defining them in the same entry file. It shows how to initialize the Simple CDK engine and have it write into an existing CDK App instance. ```typescript // bin/app.ts import { App, Stack } from 'aws-cdk-lib'; import { Engine, defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { appSyncAdapter } from '@simple-cdk/appsync'; import { MyExistingNetworkStack } from '../lib/my-existing-network-stack.js'; const app = new App(); const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: 'us-east-1' }; // Your hand-written stacks, unchanged. new MyExistingNetworkStack(app, 'MyExistingNetworkStack', { env }); // A stack you want simple-cdk's adapters to register into. const apiStack = new Stack(app, 'MyApiStack', { env }); const config = defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1' } }, adapters: [ // Seam 2: hand the adapter a stack from your hand-written CDK code. lambdaAdapter({ stack: apiStack }), appSyncAdapter({ schemaFile: 'schema.graphql', stack: apiStack, generateCrud: { models: 'all' }, }), ], }); // Seam 1: engine writes into the existing App instead of creating its own. await new Engine(config).synth({ cdkApp: app }); app.synth(); ``` -------------------------------- ### List Stack Resources CLI Example Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Adopting.md Use this AWS CLI command to list resources of an existing CloudFormation stack, including their LogicalResourceId, ResourceType, and PhysicalResourceId. ```bash aws cloudformation list-stack-resources --stack-name myapp-prod-api \ --query 'StackResourceSummaries[].[LogicalResourceId,ResourceType,PhysicalResourceId]' \ --output table ``` -------------------------------- ### Using Custom SQS Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md This example shows how to integrate the custom SQS adapter into your Simple CDK application's adapter list, alongside other adapters like lambdaAdapter. ```typescript import {sqsAdapter} from './adapters/sqs.js' adapters: [lambdaAdapter(), sqsAdapter({queues: ['orders', 'emails']})] ``` -------------------------------- ### Composing Custom and Built-in Adapters in Simple CDK Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Example configuration for a production Simple CDK application, demonstrating the composition of various custom and built-in adapters for different services like data, authentication, storage, and API. ```typescript // simple-cdk.config.ts adapters: [ myDataAdapter(), // custom: domain-shaped DynamoDB models with tenant-isolation metadata cognitoAdapter({ triggersDir: 'backend/auth/triggers', mfa: 'optional', passwordPolicy: { minLength: 12, requireSymbols: true /* ... */ }, }), myAuthExtrasAdapter(), // custom: identity pool, SES, pre-token-generation grants myStorageAdapter(), // custom: S3 buckets (logos, signatures, attachments) myFunctionsAdapter(), // custom: like @simple-cdk/lambda but per-domain config metadata myWarehouseAdapter(), // custom: RDS + VPC + DynamoDB stream consumer + EventBridge schedules myApiAdapter(), // custom: uses buildApi() directly to drop resolvers into nested stacks outputsAdapter({ parameterName: `/my-app/${stage}/aws-config`, collect: (ctx) => ({ region: ctx.config.stageConfig.region, userPoolId: getUserPool(ctx).userPoolId, userPoolClientId: getUserPoolClient(ctx).userPoolClientId, // ... plus identity pool id, AppSync URL, bucket names from custom adapters }), }), ], ``` -------------------------------- ### Deploy with Additional CDK Arguments Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Pass additional arguments to the underlying CDK CLI during deployment. This example shows how to deploy with specific approval requirements and concurrency settings. ```bash npx simple-cdk deploy --stage prod -- --require-approval never --concurrency 4 ``` -------------------------------- ### ADAPTER_ORDER Error Example Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Ordering.md This error indicates that an adapter is trying to access a resource (like a Lambda function) before the adapter responsible for creating that resource has run. Adjust the order in `config.adapters` to resolve. ```text error: Lambda "create-todo" was requested before the lambda adapter ran. hint: list lambdaAdapter() before the adapter that calls getLambdaFunction(). ``` -------------------------------- ### Lambda Handler Example Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md A basic Lambda handler function that returns a string. This is typically placed in the `backend/functions/` directory. ```typescript // backend/functions/hello/handler.ts export const handler = async () => 'hello world'; ``` -------------------------------- ### List and deploy adapters Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Verify discovered resources and deploy the backend. ```bash npx simple-cdk list # show what each adapter discovered npx simple-cdk deploy --stage dev # push to AWS ``` -------------------------------- ### Initialize a new project Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Create a new directory and scaffold a project using the simple-cdk CLI. ```bash mkdir my-app && cd my-app # or: cd into an existing project root npx simple-cdk@latest init # prompts you, then installs + scaffolds ``` -------------------------------- ### Deploy the application Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Bootstrap the environment and deploy the application to a specific stage. ```bash npx cdk bootstrap # one-time per region/account npx simple-cdk deploy --stage dev # push to AWS ``` -------------------------------- ### Configure Application with Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Demonstrates how to register the SQS adapter and wire permissions between resources in the application configuration. ```typescript import { sqsAdapter, getQueue } from './adapters/sqs/index.js'; export default defineConfig({ app: 'my-app', stages: { dev: { region: 'us-east-1' } }, adapters: [ lambdaAdapter(), sqsAdapter({ dir: 'backend/queues' }), // a tiny wiring adapter that grants Lambdas SQS permissions { name: 'lambda-sqs-bindings', wire: (ctx) => { const fn = ctx.resourcesOf('lambda').find((r) => r.name === 'process-orders'); const queue = getQueue(ctx, 'orders'); queue.grantConsumeMessages((fn?.config as any).construct); }, }, ], }); ``` -------------------------------- ### Deploy simple-cdk Project Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md After initialization and bootstrapping, use this command to deploy your simple-cdk application to a specified stage. ```bash npx cdk bootstrap npx simple-cdk deploy --stage dev ``` -------------------------------- ### Deploy Application with Simple CDK Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Wiring.md Use the simple-cdk CLI to list resources and deploy your application to a specified stage. This creates DynamoDB tables, Lambda functions, and IAM grants. ```bash npx simple-cdk list --stage dev # confirms adapter discovery found your model + handlers ``` ```bash npx simple-cdk deploy --stage dev # creates the table, the lambdas, and the IAM grants ``` -------------------------------- ### Override Built-in Lambda Adapter with Custom Logic Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Extend the default lambdaAdapter by spreading its properties and adding custom logic to the register hook. This example adds a 'Owner' tag to Lambda function constructs. ```typescript import {lambdaAdapter} from '@simple-cdk/lambda' import {Tags} from 'aws-cdk-lib' const base = lambdaAdapter() const taggedLambda = { ...base, register: async (ctx) => { await base.register?.(ctx) for (const r of ctx.resources) { const fn = (r.config as any).construct if (fn) Tags.of(fn).add('Owner', 'platform') } }, } export default defineConfig({ app: 'my-app', stages: {dev: {region: 'us-east-1'}}, adapters: [taggedLambda], }) ``` -------------------------------- ### Grant Lambda Access to RDS Instance Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Example of wiring adapter to grant a Lambda function explicit access to an RDS instance and its secrets. This is necessary because rdsAdapter does not perform automatic IAM or network wiring. ```typescript { name: 'lambda-rds', wire: (ctx) => { const db = getRdsInstance(ctx); const fn = ctx.resourcesOf('lambda').find(r => r.name === 'api')!.config.construct; db.connections.allowDefaultPortFrom(fn); db.secret!.grantRead(fn); }, } ``` -------------------------------- ### Define simple-cdk configuration Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Use the defineConfig function to set up your application, stages, and adapters. Ensure app, stages, and adapters are defined as they are required for the engine to function. ```ts import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; import { appSyncAdapter } from '@simple-cdk/appsync'; export default defineConfig({ // App-level settings app: 'my-app', // required. Used as the prefix for stack names // and physical resource names: -- defaultStage: 'dev', // optional. Used when --stage is omitted. // Falls back to the first key of `stages` (alphabetical) rootDir: process.cwd(), // optional. Where adapters scan from. Defaults to // the directory containing simple-cdk.config.ts // Stages: one entry per environment. Each gets its own CF stacks. stages: { dev: { region: 'us-east-1', // required account: '111122223333', // optional. Falls back to CDK_DEFAULT_ACCOUNT / // the profile account. Pin this in prod. removalPolicy: 'destroy', // 'destroy' | 'retain' | 'snapshot'. // Applied to stateful resources (tables, buckets, // RDS instances). Omit for raw CDK defaults. logRetentionDays: 7, // optional. Applied to Lambda log groups. tags: { // optional. Propagated to every taggable resource Environment: 'dev', // in the stage's stacks. Owner: 'platform', }, env: { // optional. Injected as process.env on every LOG_LEVEL: 'debug', // discovered Lambda. Per-function config.ts FEATURE_FLAGS: 'beta', // can add to or override these. }, }, prod: { region: 'us-east-1', account: '444455556666', removalPolicy: 'retain', // never delete prod tables on stack destroy logRetentionDays: 365, tags: { Environment: 'prod', Owner: 'platform' }, env: { LOG_LEVEL: 'info' }, }, }, // Adapters: listed in the order you want them to run. The engine enforces // a stable wire-phase order, so declaration order mostly matters for // readability (data-layer first, then compute, then API, then outputs). adapters: [ dynamoDbAdapter(), // no options means: scan backend/models/*.model.ts lambdaAdapter({ defaultMemoryMb: 512, // overrides the built-in 256 MB default defaultTimeoutSeconds: 30, }), appSyncAdapter({ schemaFile: 'schema.graphql', generateCrud: { models: 'all' }, }), ], }); ``` -------------------------------- ### Simple CDK Deployment Commands Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md A set of commands for managing your Simple CDK application. Use `list` to see discovered resources, `synth` to generate CloudFormation, `diff` to compare deployed stacks, `deploy` to push changes, and `destroy` to remove resources. ```bash npx simple-cdk list ``` ```bash npx simple-cdk synth ``` ```bash npx simple-cdk diff --stage dev ``` ```bash npx simple-cdk deploy --stage dev ``` ```bash npx simple-cdk destroy --stage dev ``` -------------------------------- ### Configure AppSync Adapter with Auth Pipeline Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Use this to set up the AppSync adapter with a custom JavaScript file for the authentication pipeline. Ensure the 'schema.graphql' and 'resolvers/auth-pipeline.js' files exist. ```typescript appSyncAdapter({ schemaFile: 'schema.graphql', authPipeline: { jsFile: 'resolvers/auth-pipeline.js' }, }); ``` -------------------------------- ### Configure simple-cdk Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Define the application structure and adapters in the simple-cdk.config.ts file. ```ts // simple-cdk.config.ts import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; import { appSyncAdapter } from '@simple-cdk/appsync'; export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1', removalPolicy: 'destroy' }, prod: { region: 'us-east-1', removalPolicy: 'retain', logRetentionDays: 365 }, }, adapters: [ lambdaAdapter(), dynamoDbAdapter(), appSyncAdapter({ schemaFile: 'schema.graphql', generateCrud: { models: 'all' }, }), ], }); ``` -------------------------------- ### Configure Simple CDK Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Define the application configuration, including stages and adapters. ```typescript import {defineConfig} from '@simple-cdk/core' import {lambdaAdapter} from '@simple-cdk/lambda' import {dynamoDbAdapter} from '@simple-cdk/dynamodb' import {appSyncAdapter} from '@simple-cdk/appsync' export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: {region: 'us-east-1', removalPolicy: 'destroy'}, prod: {region: 'us-east-1', removalPolicy: 'retain', logRetentionDays: 365}, }, adapters: [ lambdaAdapter(), dynamoDbAdapter(), appSyncAdapter({ schemaFile: 'schema.graphql', generateCrud: {models: 'all'}, }), ], }) ``` -------------------------------- ### Use Standard Layout Preset Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Utilize the standardLayout preset from '@simple-cdk/core' to organize adapter directories in a nested structure, or specify a custom root directory. ```typescript import { standardLayout } from '@simple-cdk/core'; const paths = standardLayout(); // { root: 'backend' } by default adapters: [ cognitoAdapter({ triggersDir: paths.triggersDir }), // backend/auth/triggers dynamoDbAdapter({ dir: paths.tablesDir }), // backend/tables lambdaAdapter({ dir: paths.functionsDir }), // backend/functions ], ``` -------------------------------- ### Adapter Execution Phases Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Ordering.md Adapters are processed sequentially through discover, register, and wire phases. The order in `config.adapters` dictates the execution sequence within each phase. ```plaintext for each adapter in order: discover() → collect resources from disk for each adapter in order: register() → create CDK constructs for each adapter in order: wire() → cross-adapter references ``` -------------------------------- ### simple-cdk Command Usage Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/cli/README.md Demonstrates various commands available in the simple-cdk CLI for managing AWS CDK deployments. A `simple-cdk.config.ts` file is required at the project root. ```bash simple-cdk list # show what each adapter discovered ``` ```bash simple-cdk synth # synthesize CloudFormation locally ``` ```bash simple-cdk diff --stage dev # diff against deployed stack ``` ```bash simple-cdk deploy --stage prod # deploy to AWS ``` ```bash simple-cdk destroy --stage dev # tear it down ``` ```bash simple-cdk help ``` ```bash # forward extra args to the underlying cdk CLI: simple-cdk deploy --stage prod -- --require-approval never ``` -------------------------------- ### Configure CDK Adapters for DynamoDB and Lambda Integration Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Set up Simple CDK adapters for DynamoDB and Lambda, defining their configurations and wiring them together. This includes provisioning tables and functions, and granting necessary IAM permissions. ```typescript // simple-cdk.config.ts import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter, getLambdaFunction } from '@simple-cdk/lambda'; import { dynamoDbAdapter, getDynamoTable } from '@simple-cdk/dynamodb'; export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1', removalPolicy: 'destroy' } }, adapters: [ dynamoDbAdapter(), // provisions the todo table lambdaAdapter(), // provisions create-todo, list-todos, ... { name: 'lambda-dynamodb', wire: (ctx) => { const table = getDynamoTable(ctx, 'todo'); // real aws-cdk-lib Table const writer = getLambdaFunction(ctx, 'create-todo'); const reader = getLambdaFunction(ctx, 'list-todos'); table.grantWriteData(writer); // PutItem, UpdateItem, DeleteItem table.grantReadData(reader); // GetItem, Query, Scan // grantReadWriteData(fn) when one function needs both writer.addEnvironment('TABLE_NAME', table.tableName); reader.addEnvironment('TABLE_NAME', table.tableName); }, }, ], }); ``` -------------------------------- ### Bootstrap CDK Environment Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Getting-Started.md Run this command to bootstrap your AWS CDK environment in the target region. Ensure you have AWS credentials configured. ```bash npx cdk bootstrap aws:/// ``` -------------------------------- ### Forward Flags to CDK Deploy Command Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Demonstrates how to deploy a Simple CDK application to a specific stage and forward additional flags to the underlying CDK command. ```bash simple-cdk deploy --stage prod -- --require-approval never --concurrency 4 ``` -------------------------------- ### Deploy with Custom CDK Flags Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Execute the simple-cdk deploy command and forward additional flags to the underlying CDK CLI using the '--' separator. This allows for advanced deployment configurations. ```bash simple-cdk deploy --stage prod -- --require-approval never --concurrency 4 ``` -------------------------------- ### Configure DynamoDB Adapter with Model Directory Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Initialize the DynamoDB adapter, specifying the directory containing model files and file matching patterns. Defaults are provided for directory, match, and stack name. ```typescript dynamoDbAdapter({ dir: 'backend/models', // default match: ['.model.ts', '.model.js'], // default stackName: 'data', // default }) ``` -------------------------------- ### Configure simple-cdk Adapters and Wiring Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Wiring.md Configure simple-cdk adapters for DynamoDB and Lambda, and define wiring logic to grant IAM permissions and inject the DynamoDB table name into Lambda functions. ```typescript // simple-cdk.config.ts import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter, getLambdaFunction } from '@simple-cdk/lambda'; import { dynamoDbAdapter, getDynamoTable } from '@simple-cdk/dynamodb'; export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1', removalPolicy: 'destroy' }, prod: { region: 'us-east-1', removalPolicy: 'retain' }, }, adapters: [ dynamoDbAdapter(), // discovers backend/models/*.model.ts → creates real CDK tables lambdaAdapter(), // discovers backend/functions/* → creates real CDK lambdas { name: 'lambda-dynamodb', wire: (ctx) => { const table = getDynamoTable(ctx, 'todo'); // real aws-cdk-lib Table const writer = getLambdaFunction(ctx, 'create-todo'); const reader = getLambdaFunction(ctx, 'list-todos'); // IAM: use the narrowest grant that works table.grantWriteData(writer); // PutItem, UpdateItem, DeleteItem, BatchWriteItem table.grantReadData(reader); // GetItem, Query, Scan, BatchGetItem // env var: pipe the actual table name through so renames don't drift writer.addEnvironment('TABLE_NAME', table.tableName); reader.addEnvironment('TABLE_NAME', table.tableName); }, }, ], }); ``` -------------------------------- ### Configure Lambda adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Customize the Lambda adapter settings in the configuration file. ```ts lambdaAdapter({ dir: 'backend/functions', // default defaultMemoryMb: 256, defaultTimeoutSeconds: 30, stackName: 'lambda', // default }) ``` -------------------------------- ### Configure AppSync Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Configure the AppSync adapter to create a GraphQL API with auto-generated CRUD resolvers. ```typescript appSyncAdapter({ schemaFile: 'schema.graphql', // required apiName: 'api', // default authorization: {kind: 'api-key'}, // or 'iam' | 'cognito' generateCrud: { models: 'all', // or ['todo', 'user'] operations: ['get', 'list', 'create', 'update', 'delete'], softDelete: false, }, resolvers: [ // manual resolvers for anything CRUD doesn't cover { typeName: 'Query', fieldName: 'hello', source: {kind: 'lambda', lambdaName: 'hello'}, }, ], authPipeline: {jsFile: 'resolvers/auth.js'}, // optional }) ``` -------------------------------- ### Implement SQS Adapter Logic Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Implements the discovery and registration logic for SQS queues, including helper functions for retrieving queues. ```typescript // adapters/sqs/index.ts import type { Adapter, WireContext } from '@simple-cdk/core'; import { scanFiles } from '@simple-cdk/core'; import { Duration, aws_sqs as sqs } from 'aws-cdk-lib'; import { pathToFileURL } from 'node:url'; import type { SqsModelConfig, SqsResource } from './types.js'; export interface SqsAdapterOptions { dir?: string; stackName?: string; } export function sqsAdapter(opts: SqsAdapterOptions = {}): Adapter { const dir = opts.dir ?? 'backend/queues'; return { name: 'sqs', discover: async (ctx) => { const files = await scanFiles(ctx.rootDir, { dir, match: ['.queue.ts'] }); const found = []; for (const f of files) { const mod = await import(pathToFileURL(f.absolutePath).href); const modelConfig = (mod.default ?? mod.queue) as SqsModelConfig | undefined; if (!modelConfig) continue; found.push({ type: 'sqs-queue' as const, name: modelConfig.name ?? f.stem, source: f.absolutePath, config: { modelConfig }, }); } return found; }, register: (ctx) => { const stack = ctx.stack(opts.stackName ?? 'queues'); for (const r of ctx.resources as SqsResource[]) { const cfg = r.config.modelConfig; const queue = new sqs.Queue(stack, r.name, { queueName: `${ctx.config.app}-${ctx.config.stage}-${r.name}`, fifo: cfg.fifo, visibilityTimeout: Duration.seconds(cfg.visibilityTimeoutSeconds ?? 30), deadLetterQueue: cfg.deadLetterMaxReceiveCount ? { maxReceiveCount: cfg.deadLetterMaxReceiveCount, queue: new sqs.Queue(stack, r.name + 'Dlq', { fifo: cfg.fifo }), } : undefined, }); r.config.construct = queue; } }, }; } export function getQueue(ctx: Pick, name: string): sqs.Queue { const r = ctx.resourcesOf('sqs').find((r) => r.name === name) as SqsResource | undefined; if (!r?.config.construct) throw new Error(`Queue "${name}" not registered`); return r.config.construct; } ``` -------------------------------- ### Configure DynamoDB Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-dynamodb/README.md Configure the dynamodb adapter in your simple-cdk application. Specify the directory for model files and file suffixes to scan. ```typescript import { defineConfig } from '@simple-cdk/core'; import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; export default defineConfig({ app: 'my-app', stages: { dev: { region: 'us-east-1' } }, adapters: [ dynamoDbAdapter({ dir: 'backend/models', // default match: ['.model.ts', '.model.js'], // file suffixes to scan stackName: 'data', }), ], }); ``` -------------------------------- ### Configure AppSync adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-appsync/README.md Define the AppSync adapter within the simple-cdk configuration, including schema path and custom resolver definitions. ```typescript import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; import { appSyncAdapter } from '@simple-cdk/appsync'; export default defineConfig({ app: 'my-app', stages: { dev: { region: 'us-east-1' } }, adapters: [ lambdaAdapter(), dynamoDbAdapter(), appSyncAdapter({ schemaFile: 'schema.graphql', // apiName: 'my-api', // default: '--api' generateCrud: { models: 'all', softDelete: false }, resolvers: [ { typeName: 'Mutation', fieldName: 'archiveOrder', source: { kind: 'lambda', lambdaName: 'archive-order' }, }, ], }), ], }); ``` -------------------------------- ### Configure DynamoDB Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Configure the DynamoDB adapter to discover models from a specified directory. ```typescript dynamoDbAdapter({ dir: 'backend/models', // default match: ['.model.ts', '.model.js'], // default stackName: 'data', // default }) ``` -------------------------------- ### Bundle Outputs into SSM Parameter Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Home.md Use outputsAdapter to collect arbitrary values from other adapters and bundle them into a single SSM String parameter. This allows frontends or other consumers to fetch configuration in one call. This adapter runs in the wire phase. ```typescript import { outputsAdapter } from '@simple-cdk/outputs'; import { getUserPool } from '@simple-cdk/cognito'; import { getAppSyncApi } from '@simple-cdk/appsync'; outputsAdapter({ collect: (ctx) => { const pool = getUserPool(ctx); const api = getAppSyncApi(ctx); return { userPoolId: pool.userPoolId, graphqlUrl: api.graphqlUrl, region: ctx.config.stageConfig.region, }; }, // parameterName defaults to `///outputs` // cfnOutputs: true (default). Also emits each key as a CfnOutput }) ``` -------------------------------- ### Define Application Configuration Structure Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Architecture.md Defines the overall structure for application configuration, including app name, stages, and adapters. This interface is used by the simple-cdk engine. ```typescript interface AppConfig { app: string; // logical app name, used in resource ids stages: Record; // dev, staging, prod, ... adapters: Adapter[]; // ordered: discover and register run in this order defaultStage?: string; rootDir?: string; // override cwd for filesystem scans } ``` -------------------------------- ### Collect Stack Outputs with outputsAdapter Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Use the outputsAdapter to bundle stack values into an SSM String parameter for frontend access. The parameter name defaults to `///outputs` and each key is also emitted as a CfnOutput by default. ```typescript import {outputsAdapter} from '@simple-cdk/outputs' import {getUserPool} from '@simple-cdk/cognito' import {getAppSyncApi} from '@simple-cdk/appsync' outputsAdapter({ collect: (ctx) => ({ userPoolId: getUserPool(ctx).userPoolId, graphqlUrl: getAppSyncApi(ctx).graphqlUrl, region: ctx.config.stageConfig.region, }), // parameterName defaults to `///outputs` // cfnOutputs: true (default). Also emits each key as a CfnOutput }) ``` -------------------------------- ### Stashing Values in Resolvers Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Custom-Resolvers.md Explains how to use `stashBefore` and `stashCode` to compute and store values from `ctx.identity` or `ctx.args` that are needed before the main resolver logic executes. ```APIDOC ## Stashing Values in AppSync Resolvers ### Description `stashBefore` and `stashCode` allow you to pre-process context information (like identity claims or arguments) and make it available in `ctx.stash` for subsequent resolver steps or within the main resolver logic. ### `stashBefore` Use `stashBefore` for simple key-value seeding. Values can be literals or computed via code. ```ts resolvers: [ { typeName: 'Query', fieldName: 'myTodos', source: { kind: 'dynamodb', tableName: 'todo', jsFile: 'resolvers/my-todos.js' }, stashBefore: { userId: { code: 'ctx.identity.sub' }, // emitted verbatim tenantId: { code: "ctx.identity.claims?.['custom:tenantId']" }, scanLimit: 50, // literal, JSON-encoded }, }, ], ``` In the `resolvers/my-todos.js` file, these values would be accessible as `ctx.stash.userId`, `ctx.stash.tenantId`, and `ctx.stash.scanLimit`. ### `stashCode` Use `stashCode` for more complex, multi-statement logic that needs to run before the main resolver function. ```ts resolvers: [ { typeName: 'Mutation', fieldName: 'publishPost', source: { kind: 'lambda', lambdaName: 'publish-post' }, stashCode: ` const claims = ctx.identity?.claims ?? {}; ctx.stash.userId = claims.sub; ctx.stash.roles = (claims['custom:roles'] ?? '').split(',').filter(Boolean); if (!ctx.stash.roles.includes('author')) util.unauthorized(); `, }, ], ``` In this example, `ctx.stash.userId` and `ctx.stash.roles` are populated, and authorization is checked before the Lambda resolver executes. The `util.unauthorized()` call would halt execution if the user is not an 'author'. ``` -------------------------------- ### Configure auth pipeline Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/adapter-appsync/README.md Specify a JavaScript file to execute as an AppSync pipeline function before every resolver. ```typescript appSyncAdapter({ schemaFile: 'schema.graphql', authPipeline: { jsFile: 'resolvers/auth-pipeline.js' }, }); ``` -------------------------------- ### Complete simple-cdk Configuration Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Comparison.md This configuration defines a serverless backend including Lambda functions, DynamoDB tables, and an AppSync GraphQL API. It specifies application name, default stage, stage-specific configurations, and integrates various adapters for different AWS services. Lambdas are auto-discovered from 'backend/functions/', models from 'backend/models/', and AppSync resolvers are auto-generated for CRUD operations. ```typescript import { defineConfig } from '@simple-cdk/core'; import { lambdaAdapter } from '@simple-cdk/lambda'; import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; import { appSyncAdapter } from '@simple-cdk/appsync'; export default defineConfig({ app: 'my-app', defaultStage: 'dev', stages: { dev: { region: 'us-east-1', removalPolicy: 'destroy' }, prod: { region: 'us-east-1', removalPolicy: 'retain', logRetentionDays: 365 }, }, adapters: [ lambdaAdapter(), dynamoDbAdapter(), appSyncAdapter({ schemaFile: 'schema.graphql', generateCrud: { models: 'all' }, }), ], }); ``` -------------------------------- ### Configure DynamoDB Adapter Options Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Customize the dynamoDbAdapter by specifying a different directory for table definitions and defining a custom file match pattern for table files. ```typescript import { dynamoDbAdapter } from '@simple-cdk/dynamodb'; dynamoDbAdapter({ dir: 'database/tables', match: ['.table.ts'], // pick your own filename convention }); ``` -------------------------------- ### Import Core Functionality Source: https://github.com/pujaaan/simple-cdk/blob/main/packages/core/README.md Import necessary functions and types from the @simple-cdk/core package for use in your configuration or adapter code. ```typescript import { defineConfig, Engine, scanFiles } from '@simple-cdk/core'; import type { Adapter, AppConfig, Resource, RegisterContext, WireContext } from '@simple-cdk/core'; ``` -------------------------------- ### Configure AppSync Adapter Options Source: https://github.com/pujaaan/simple-cdk/blob/main/docs/Extending.md Configure the AppSync adapter to specify the schema file, control CRUD generation for models, and define custom resolvers. ```typescript import { appSyncAdapter } from '@simple-cdk/appsync'; appSyncAdapter({ schemaFile: 'graphql/schema.graphql', generateCrud: { models: ['user', 'organization'], // only these get CRUD operations: ['get', 'list'], // skip create/update/delete softDelete: true, }, resolvers: [ { typeName: 'Mutation', fieldName: 'archiveUser', source: { kind: 'lambda', lambdaName: 'archive-user' }, }, ], }); ``` -------------------------------- ### Configure Lambda Adapter Source: https://github.com/pujaaan/simple-cdk/blob/main/README.md Configure the Lambda adapter to auto-discover Lambda handlers from a specified directory. ```typescript lambdaAdapter({ dir: 'backend/functions', // default defaultMemoryMb: 256, defaultTimeoutSeconds: 30, stackName: 'lambda', // default }) ```