AWS & Typescript Masterclass - 3. Serverless project

September 9th, 2022

API gateway

Lambda

DynamoDb

Cognito

 

https://github.com/barosanuemailtest/space-finder-backend.git

https://github.com/barosanuemailtest/space-finder-frontend.git

 

 

git init

npm init -y

npm i -D aws-cdk aws-cdk-lib constructs ts-node typescript

 

mkdir infra

touch infra/Launcher.ts

touch infra/SpaceStack.ts

 

# echo '{"app":"npx infra/Launcher.ts"}' > cdk.json

echo '{"app": "npx ts-node --prefer-ts-exts infra/Launcher.ts"}' > cdk.json

 

cdk synth    # error related to tsconfig target

 

npx tsc --init

# change tsconfig.json "target": "es2016", -> "target": "ES2018",

# copy tsconfig.json from generated project

 

infra/Launcher.ts

import {App} from "aws-cdk-lib";

import {SpaceStack} from "./SpaceStack";

 

 

const app = new App()

new SpaceStack(app, 'Space-finder', {

stackName: 'SpaceFinder'

})

 

infra/SpaceStack.ts

import {Stack, StackProps} from 'aws-cdk-lib'

import {Construct} from 'constructs'

 

export class SpaceStack extends Stack {

constructor(scope: Construct, id: string, props: StackProps) {

super(scope, id, props);

}

}

 


 

Lambda (js)

infra/SpaceStack.ts

const helloLambda = new Lambda(this, 'helloLambda', {

runtime: Runtime.NODEJS_14_X,

code: Code.fromAsset(join(__dirname, '..', 'services', 'hello')),

handler: 'hello.main'

})

services/hello/hello.js

exports.main = async function(event, context) {

return {

statusCode: 200,

body: 'hello from lambda',

}

}

 


 

Api Gateway

infra/SpaceStack.ts

const api = new RestApi(this, 'SpaceApi')

const helloLambdaIntegration = new LambdaIntegration(helloLambda);

const helloLambdaResource = this.api.root.addResource('hello');

helloLambdaResource.addMethod('GET', helloLambdaIntegration);

 


 

DynamoDB

infra/SpaceStack.ts

const spacesTableName = 'SpacesTable'

new Table(this, spacesTableName, {

partitionKey: {

name: 'SpaceId',

type: AttributeType.STRING,

},

tableName: spacesTableName

})