Create a Simple TypeScript REST API using AWS CDK

When we create a new Lambda function written in TypeScript, we have to add any third party extension or config […]

広告ここから
広告ここまで

目次

    When we create a new Lambda function written in TypeScript, we have to add any third party extension or configure any build config by myself using like a Webpack, parcel, or babel.

    But now, AWS CDK provides a useful official package for TypeScript.

    Steps of creating Lambda Function

    1: Setup project

    $ mkdir ts-api
    $ cd ts-api
    $ npx aws-cdk init app --language typescript

    2: Add AWS CDK Construct library

    $ yarn add @aws-cdk/aws-lambda-nodejs
    $ yarn add -D @types/aws-lambda

    3: Create a Lambda function code

    $ vim lambda/entry.ts
    import {
        APIGatewayProxyHandler
    } from 'aws-lambda'
    
    export const handler: APIGatewayProxyHandler = async (event) => {
        console.log(event)
        return {
            statusCode: 200,
            body: JSON.stringify(event)
        }
    }

    4: Define AWS resource

    $ vim lib/ts-api-stack.ts
    import * as cdk from '@aws-cdk/core';
    import { NodejsFunction } from '@aws-cdk/aws-lambda-nodejs'
    
    export class DeployToS3Stack extends cdk.Stack {
      constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
    
        const lambdaFunction = new NodejsFunction(this, 'LambdaFunction', {
          entry: 'lambda/entry.ts',
          handler: 'handler',
        })
      }
    }

    5: deploy

    $ yarn build
    $ yarn cdk bootstrap
    $ yarn cdk deploy

    Add a new REST API endpoint (Lambda proxy)

    And we can easy to integrate to AWS API Gateway

    1: Install a construct library

    $ yarn add @aws-cdk/aws-apigateway

    2: Define AWS resource

    import * as cdk from '@aws-cdk/core';
    import { LambdaRestApi } from '@aws-cdk/aws-apigateway';
    import { NodejsFunction } from '@aws-cdk/aws-lambda-nodejs'
    
    export class DeployToS3Stack extends cdk.Stack {
      constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
    
        const lambdaFunction = new NodejsFunction(this, 'Function', {
          entry: 'lambda/entry.ts',
          handler: 'handler'
        })
    
        const api = new LambdaRestApi(this, 'API', {
          handler: lambdaFunction,
          proxy: true,
        })
      }
    }
    

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark