Logo

dev-resources.site

for different kinds of informations.

AWS CDK context validation

Published at
10/14/2024
Categories
cdk
zod
context
aws
Author
shtuper
Categories
4 categories in total
cdk
open
zod
open
context
open
aws
open
Author
7 person written this
shtuper
open
AWS CDK context validation

AWS CDK gives us rather primitive tools to access its context. It is only possible to get context values one by one (with tryGetContext), they are not typed and not validated. I want to be able to get multiple values at once and have them validated so that I don't have to test each value if it's empty etc.

All of this we can achieve by using Zod and a small wrapper.

We'll create a function that takes Zod schema as an input, and returns us validated context values.

import {getValidatedContext, z} from 'zod-cdk-context'

const app = new cdk.App();

// {foo: string; bar?: string; baz: number}
const {foo, bar, baz} = getValidatedContext(app.node, {
  foo: z.string().min(1),
  bar: z.string().min(1).optional(),
  baz: z.coerce.number(),
})
Enter fullscreen mode Exit fullscreen mode

Note: Complete source code is below

Main idea is to use schema.shape to get schema keys and use them as context names

Object.keys(schema.shape).map((key) => node.tryGetContext(key))
Enter fullscreen mode Exit fullscreen mode

Also we need to narrow down possible validators of input schema to strings and numbers - context values can only be strings but we can also pass number as a string, then "coerce" them to numbers so we have number type in the end.

{
  [key: string]: z.ZodString | z.ZodNumber | z.ZodOptional<z.ZodString | z.ZodNumber>
}
Enter fullscreen mode Exit fullscreen mode

And that's all the interesting details. Here is complete source code of the function

import type { Node } from 'constructs'

import { z } from 'zod'

export const getValidatedContext = <
  T extends {
    [key: string]: z.ZodString | z.ZodNumber | z.ZodOptional<z.ZodString | z.ZodNumber>
  }
>(
  node: Node,
  schemaObject: T
): z.infer<z.ZodObject<T>> => {
  const schema = z.object(schemaObject)
  const obj = Object.fromEntries(
    Object.keys(schema.shape).map((key) => [key, node.tryGetContext(key)])
  )

  return schema.parse(obj)
}

Enter fullscreen mode Exit fullscreen mode

Or you can use my npm package:

> npm i zod-cdk-context
Enter fullscreen mode Exit fullscreen mode
cdk Article's
30 articles in total
Favicon
Invoking Private API Gateway Endpoints From Step Functions
Favicon
Automating Cross-Account CDK Bootstrapping Using AWS Lambda
Favicon
Deploy de NextJS utilizando CDK
Favicon
Config AWS Cloudwatch Application Signals Transaction Search with CDK
Favicon
[Solved] AWS Resource limit exceeded
Favicon
Create a cross-account glue Job using AWS CDK
Favicon
Enabling Decorators for Lambda Functions with CDK in an Nx Monorepo
Favicon
Run vs code on a private AWS ec2 instance without ssh (with AWS CDK examples)
Favicon
Config AWS Cloudwatch Application Signals for NodeJs Lambda with CDK
Favicon
Deploying a Simple Static Website on AWS with CDK and TypeScript
Favicon
AWS Architectural Diagrams on a Commit Base: Using AWS PDK Diagram Plugin with Python
Favicon
AWS CDK Aspects specifications have changed
Favicon
Relative Python imports in a Dockerized lambda function
Favicon
Building Scalable Infrastructure with AWS CDK: A Developer’s Guide to Best Practices
Favicon
API Gateway integration with AWS Services.
Favicon
DevSecOps with AWS- IaC at scale - Building your own platform – Part 3 - Pipeline as a Service
Favicon
AWS Cloud Development Kit (CDK) vs. Terraform
Favicon
Query your EventBridge Scheduled Events in DynamoDB
Favicon
AWS CDK context validation
Favicon
How to combine SQS and SNS to implement multiple Consumers (Part 2)
Favicon
Serverless Code-Signing (EV) with KMS and Fargate
Favicon
How to build an API with Lambdas, API Gateway and deploy with AWS CDK
Favicon
The Journey of CDK.dev: From Static Site to Bluesky
Favicon
Create an Asset Store with a Custom Domain using AWS CDK, Route53, S3 and CloudFront
Favicon
Crafting a Scalable Node.js API: Insights from My RealWorld Project with Express, Knex, and AWS CDK
Favicon
Techniques to Save Costs Using AWS Lambda Functions with CDK
Favicon
Deploy a Docker Image to ECS with Auto Scaling Using AWS CDK in Minutes
Favicon
AWS CDK + Localstack (API Gateway, Lambda, SQS, DynamoDB,TypeScript)
Favicon
Simplifying Cloud Infrastructure with AWS CDK
Favicon
Effortless Debugging: AWS CDK TypeScript Projects in VSCode

Featured ones: