Skip to content

docs(parameters): add parameters examples cdk and sam #1622

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jul 25, 2023
22 changes: 22 additions & 0 deletions examples/cdk/functions/common/getUuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { logger } from './powertools';
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
import { randomUUID } from 'node:crypto';
import { default as request } from 'phin';

export const getUuid = async (): Promise<string> => {
const uuidApiUrl = await getParameter('/app/uuid-api-url');
if (!uuidApiUrl) {
// create uuid locally
logger.warn('No uuid-api-url parameter found, creating uuid locally');

return randomUUID();
} else {
// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: uuidApiUrl,
parse: 'json',
});

return res.body.uuid;
}
};
5 changes: 2 additions & 3 deletions examples/cdk/functions/common/powertools.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { Metrics } from '@aws-lambda-powertools/metrics';
import { Tracer } from '@aws-lambda-powertools/tracer';

const awsLambdaPowertoolsVersion = '1.5.0';
import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version';

const defaultValues = {
region: process.env.AWS_REGION || 'N/A',
Expand All @@ -14,7 +13,7 @@ const logger = new Logger({
...defaultValues,
logger: {
name: '@aws-lambda-powertools/logger',
version: awsLambdaPowertoolsVersion,
version: PT_VERSION,
},
},
});
Expand Down
21 changes: 8 additions & 13 deletions examples/cdk/functions/get-all-items.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { injectLambdaContext } from '@aws-lambda-powertools/logger';
import { logMetrics } from '@aws-lambda-powertools/metrics';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
import middy from '@middy/core';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import middy from '@middy/core';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
import { logMetrics } from '@aws-lambda-powertools/metrics';
import { injectLambdaContext } from '@aws-lambda-powertools/logger';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
import { docClient } from './common/dynamodb-client';
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
import { getUuid } from './common/getUuid';
import { logger, metrics, tracer } from './common/powertools';

/*
*
Expand Down Expand Up @@ -45,12 +45,7 @@ const getAllItemsHandler = async (
awsRequestId: context.awsRequestId,
});

// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;
const uuid = await getUuid();

// Logger: Append uuid to each log statement
logger.appendKeys({ uuid });
Expand Down
17 changes: 5 additions & 12 deletions examples/cdk/functions/get-by-id.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { LambdaInterface } from '@aws-lambda-powertools/commons';
import { GetCommand } from '@aws-sdk/lib-dynamodb';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
import { LambdaInterface } from '@aws-lambda-powertools/commons';
import { docClient } from './common/dynamodb-client';
import { GetCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
import { getUuid } from './common/getUuid';
import { logger, metrics, tracer } from './common/powertools';

/*
*
Expand All @@ -28,14 +28,7 @@ import { default as request } from 'phin';
class Lambda implements LambdaInterface {
@tracer.captureMethod()
public async getUuid(): Promise<string> {
// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;

return uuid;
return getUuid();
}

@tracer.captureLambdaHandler({ captureResponse: false }) // by default the tracer would add the response as metadata on the segment, but there is a chance to hit the 64kb segment size limit. Therefore set captureResponse: false
Expand Down
15 changes: 5 additions & 10 deletions examples/cdk/functions/put-item.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { PutCommand } from '@aws-sdk/lib-dynamodb';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import type { Subsegment } from 'aws-xray-sdk-core';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
import { docClient } from './common/dynamodb-client';
import { PutCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
import type { Subsegment } from 'aws-xray-sdk-core';
import { getUuid } from './common/getUuid';
import { logger, metrics, tracer } from './common/powertools';

/**
*
Expand Down Expand Up @@ -59,12 +59,7 @@ export const handler = async (
awsRequestId: context.awsRequestId,
});

// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;
const uuid = await getUuid();

// Logger: Append uuid to each log statement
logger.appendKeys({ uuid });
Expand Down
8 changes: 8 additions & 0 deletions examples/cdk/functions/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { randomUUID } from 'node:crypto';

exports.handler = async (_event) => {
return {
statusCode: 200,
body: JSON.stringify(randomUUID()),
};
};
3 changes: 3 additions & 0 deletions examples/cdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@
"*.js": "npm run lint-fix"
},
"devDependencies": {
"@aws-lambda-powertools/commons": "^1.11.1",
"@aws-lambda-powertools/logger": "^1.11.1",
"@aws-lambda-powertools/metrics": "^1.11.1",
"@aws-lambda-powertools/parameters": "^1.11.1",
"@aws-lambda-powertools/tracer": "^1.11.1",
"@aws-sdk/client-ssm": "^3.360.0",
"@aws-sdk/lib-dynamodb": "^3.360.0",
"@types/aws-lambda": "^8.10.109",
"@types/jest": "^29.2.4",
Expand Down
52 changes: 46 additions & 6 deletions examples/cdk/src/example-stack.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Table, BillingMode, AttributeType } from 'aws-cdk-lib/aws-dynamodb';
import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import { LambdaIntegration, RestApi } from 'aws-cdk-lib/aws-apigateway';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import { LayerVersion, Runtime, Tracing } from 'aws-cdk-lib/aws-lambda';
import {
NodejsFunction,
NodejsFunctionProps,
} from 'aws-cdk-lib/aws-lambda-nodejs';
import { Runtime, Tracing, LayerVersion } from 'aws-cdk-lib/aws-lambda';
import { RetentionDays } from 'aws-cdk-lib/aws-logs';
import { RestApi, LambdaIntegration } from 'aws-cdk-lib/aws-apigateway';
import { StringParameter } from 'aws-cdk-lib/aws-ssm';
import { Construct } from 'constructs';

const commonProps: Partial<NodejsFunctionProps> = {
runtime: Runtime.NODEJS_18_X,
Expand Down Expand Up @@ -37,6 +38,8 @@ export class CdkAppStack extends Stack {
public constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);

const uuidApi = new UuidApi(this, 'uuid-api');

const table = new Table(this, 'Table', {
billingMode: BillingMode.PAY_PER_REQUEST,
partitionKey: {
Expand All @@ -51,7 +54,7 @@ export class CdkAppStack extends Stack {
'powertools-layer',
`arn:aws:lambda:${
Stack.of(this).region
}:094274105915:layer:AWSLambdaPowertoolsTypeScript:6`
}:094274105915:layer:AWSLambdaPowertoolsTypeScript:16`
)
);

Expand All @@ -76,12 +79,20 @@ export class CdkAppStack extends Stack {
entry: './functions/get-by-id.ts',
handler: 'handler',
});

uuidApi.apiUrlParam.grantRead(getByIdFn);
uuidApi.apiUrlParam.grantRead(putItemFn);
uuidApi.apiUrlParam.grantRead(getAllItemsFn);

getByIdFn.addEnvironment('SAMPLE_TABLE', table.tableName);
table.grantReadData(getByIdFn);

const api = new RestApi(this, 'items-api', {
restApiName: 'Items Service',
description: 'This service serves items.',
deployOptions: {
tracingEnabled: true,
},
});

const itemPutIntegration = new LambdaIntegration(putItemFn);
Expand All @@ -95,3 +106,32 @@ export class CdkAppStack extends Stack {
item.addMethod('GET', itemIntegration);
}
}

class UuidApi extends Construct {
public readonly apiUrlParam: StringParameter;
public constructor(scope: Construct, id: string) {
super(scope, id);

const uuidFn = new NodejsFunction(this, 'UuidFn', {
runtime: Runtime.NODEJS_18_X,
entry: './functions/uuid.ts',
});

const api = new RestApi(this, 'uuid-api', {
restApiName: 'UUID Service',
description: 'This service serves UUIDs.',
deployOptions: {
tracingEnabled: true,
},
});

const uuidIntegration = new LambdaIntegration(uuidFn);
const uuid = api.root.addResource('uuid');
uuid.addMethod('GET', uuidIntegration);

this.apiUrlParam = new StringParameter(this, 'uuid-api-url', {
parameterName: '/app/uuid-api-url',
stringValue: `${api.url}/uuid`,
});
}
}
2 changes: 1 addition & 1 deletion examples/cdk/tests/cdk-app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import * as CdkApp from '../src/example-stack';
test('CDK code synthesize', () => {
const app = new cdk.App();
const stack = new CdkApp.CdkAppStack(app, 'MyTestStack');
Template.fromStack(stack).resourceCountIs('AWS::Lambda::Function', 4); // The stack has 4 functions: 3 for the example, and 1 for the log retention that is deployed by CDK
Template.fromStack(stack).resourceCountIs('AWS::Lambda::Function', 5); // The stack has 4 functions: 3 for the example, and 1 for the log retention that is deployed by CDK
});
4 changes: 3 additions & 1 deletion examples/sam/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"@types/node": "18.11.17",
"@typescript-eslint/eslint-plugin": "^5.46.1",
"@typescript-eslint/parser": "^5.46.1",
"esbuild": "^0.16.9",
"eslint": "^8.30.0",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
Expand All @@ -40,9 +39,12 @@
"@aws-lambda-powertools/logger": "^1.11.1",
"@aws-lambda-powertools/metrics": "^1.11.1",
"@aws-lambda-powertools/tracer": "^1.11.1",
"@aws-lambda-powertools/parameters": "^1.11.1",
"@aws-sdk/client-dynamodb": "^3.360.0",
"@aws-sdk/client-ssm": "^3.360.0",
"@aws-sdk/lib-dynamodb": "^3.360.0",
"@middy/core": "^3.6.2",
"esbuild": "^0.18.14",
"phin": "^3.7.0"
}
}
22 changes: 22 additions & 0 deletions examples/sam/src/common/getUuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { logger } from './powertools';
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
import { randomUUID } from 'node:crypto';
import { default as request } from 'phin';

export const getUuid = async (): Promise<string> => {
const uuidApiUrl = await getParameter('/app/uuid-api-url');
if (!uuidApiUrl) {
// create uuid locally
logger.warn('No uuid-api-url parameter found, creating uuid locally');

return randomUUID();
} else {
// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: uuidApiUrl,
parse: 'json',
});

return res.body.uuid;
}
};
5 changes: 2 additions & 3 deletions examples/sam/src/common/powertools.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { Metrics } from '@aws-lambda-powertools/metrics';
import { Tracer } from '@aws-lambda-powertools/tracer';

const awsLambdaPowertoolsVersion = '1.5.0';
import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version';

const defaultValues = {
region: process.env.AWS_REGION || 'N/A',
Expand All @@ -14,7 +13,7 @@ const logger = new Logger({
...defaultValues,
logger: {
name: '@aws-lambda-powertools/logger',
version: awsLambdaPowertoolsVersion,
version: PT_VERSION,
},
},
});
Expand Down
9 changes: 2 additions & 7 deletions examples/sam/src/get-all-items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { injectLambdaContext } from '@aws-lambda-powertools/logger';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
import { docClient } from './common/dynamodb-client';
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
import { getUuid } from './common/getUuid';

/*
*
Expand Down Expand Up @@ -45,12 +45,7 @@ const getAllItemsHandler = async (
awsRequestId: context.awsRequestId,
});

// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;
const uuid = await getUuid();

// Logger: Append uuid to each log statement
logger.appendKeys({ uuid });
Expand Down
17 changes: 5 additions & 12 deletions examples/sam/src/get-by-id.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { LambdaInterface } from '@aws-lambda-powertools/commons';
import { GetCommand } from '@aws-sdk/lib-dynamodb';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
import { LambdaInterface } from '@aws-lambda-powertools/commons';
import { docClient } from './common/dynamodb-client';
import { GetCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
import { getUuid } from './common/getUuid';
import { logger, metrics, tracer } from './common/powertools';

/*
*
Expand All @@ -28,14 +28,7 @@ import { default as request } from 'phin';
class Lambda implements LambdaInterface {
@tracer.captureMethod()
public async getUuid(): Promise<string> {
// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;

return uuid;
return getUuid();
}

@tracer.captureLambdaHandler({ captureResponse: false }) // by default the tracer would add the response as metadata on the segment, but there is a chance to hit the 64kb segment size limit. Therefore set captureResponse: false
Expand Down
8 changes: 8 additions & 0 deletions examples/sam/src/get-uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { randomUUID } from 'node:crypto';

exports.handler = async (_event) => {
return {
statusCode: 200,
body: JSON.stringify(randomUUID()),
};
};
Loading