Skip to content

Commit 666e8b0

Browse files
authored
style(docs): apply standardized formatting (#1460)
1 parent bdabb8c commit 666e8b0

11 files changed

+164
-61
lines changed

examples/cdk/.eslintrc.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
module.exports = {
2+
env: {
3+
browser: false,
4+
es2020: true,
5+
jest: true,
6+
node: true,
7+
},
8+
ignorePatterns: ['cdk.out', 'lib'],
9+
extends: [
10+
'plugin:@typescript-eslint/recommended',
11+
'plugin:prettier/recommended',
12+
],
13+
parser: '@typescript-eslint/parser',
14+
plugins: ['@typescript-eslint', 'prettier'],
15+
settings: {
16+
'import/resolver': {
17+
node: {},
18+
typescript: {
19+
project: './tsconfig.json',
20+
alwaysTryTypes: true,
21+
},
22+
},
23+
},
24+
rules: {
25+
'@typescript-eslint/explicit-function-return-type': [
26+
'error',
27+
{ allowExpressions: true },
28+
], // Enforce return type definitions for functions
29+
'@typescript-eslint/explicit-member-accessibility': 'error', // Enforce explicit accessibility modifiers on class properties and methods (public, private, protected)
30+
'@typescript-eslint/member-ordering': [
31+
// Standardize the order of class members
32+
'error',
33+
{
34+
default: {
35+
memberTypes: [
36+
'signature',
37+
'public-field',
38+
'protected-field',
39+
'private-field',
40+
'constructor',
41+
'public-method',
42+
'protected-method',
43+
'private-method',
44+
],
45+
order: 'alphabetically',
46+
},
47+
},
48+
],
49+
'@typescript-eslint/no-explicit-any': 'error', // Disallow usage of the any type
50+
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], // Disallow unused variables, except for variables starting with an underscore
51+
'@typescript-eslint/no-use-before-define': ['off'], // Check if this rule is needed
52+
'no-unused-vars': 'off', // Disable eslint core rule, since it's replaced by @typescript-eslint/no-unused-vars
53+
// Rules from eslint core https://eslint.org/docs/latest/rules/
54+
'array-bracket-spacing': ['error', 'never'], // Disallow spaces inside of array brackets
55+
'computed-property-spacing': ['error', 'never'], // Disallow spaces inside of computed properties
56+
'func-style': ['warn', 'expression'], // Enforce function expressions instead of function declarations
57+
'keyword-spacing': 'error', // Enforce spaces after keywords and before parenthesis, e.g. if (condition) instead of if(condition)
58+
'padding-line-between-statements': [
59+
// Require an empty line before return statements
60+
'error',
61+
{ blankLine: 'always', prev: '*', next: 'return' },
62+
],
63+
'no-console': 0, // Allow console.log statements
64+
'no-multi-spaces': ['error', { ignoreEOLComments: false }], // Disallow multiple spaces except for comments
65+
'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 0, maxEOF: 0 }], // Enforce no empty line at the beginning & end of files and max 1 empty line between consecutive statements
66+
'no-throw-literal': 'error', // Disallow throwing literals as exceptions, e.g. throw 'error' instead of throw new Error('error')
67+
'object-curly-spacing': ['error', 'always'], // Enforce spaces inside of curly braces in objects
68+
'prefer-arrow-callback': 'error', // Enforce arrow functions instead of anonymous functions for callbacks
69+
quotes: ['error', 'single', { allowTemplateLiterals: true }], // Enforce single quotes except for template strings
70+
semi: ['error', 'always'], // Require semicolons instead of ASI (automatic semicolon insertion) at the end of statements
71+
},
72+
};

examples/cdk/bin/cdk-app.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ import * as cdk from 'aws-cdk-lib';
44
import { CdkAppStack } from '../src/example-stack';
55

66
const app = new cdk.App();
7-
new CdkAppStack(app, 'LambdaPowertoolsTypeScript-ExamplesCdkStack', {});
7+
new CdkAppStack(app, 'LambdaPowertoolsTypeScript-ExamplesCdkStack', {});
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
// Get the DynamoDB table name from environment variables
22
const tableName = process.env.SAMPLE_TABLE;
33

4-
export {
5-
tableName
6-
};
4+
export { tableName };

examples/cdk/functions/common/dynamodb-client.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,4 @@ const translateConfig = { marshallOptions, unmarshallOptions };
2424
// Create the DynamoDB Document client.
2525
const docClient = DynamoDBDocumentClient.from(ddbClient, translateConfig);
2626

27-
export {
28-
docClient
29-
};
27+
export { docClient };

examples/cdk/functions/common/powertools.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const awsLambdaPowertoolsVersion = '1.5.0';
66

77
const defaultValues = {
88
region: process.env.AWS_REGION || 'N/A',
9-
executionEnv: process.env.AWS_EXECUTION_ENV || 'N/A'
9+
executionEnv: process.env.AWS_EXECUTION_ENV || 'N/A',
1010
};
1111

1212
const logger = new Logger({
@@ -15,18 +15,14 @@ const logger = new Logger({
1515
logger: {
1616
name: '@aws-lambda-powertools/logger',
1717
version: awsLambdaPowertoolsVersion,
18-
}
18+
},
1919
},
2020
});
2121

2222
const metrics = new Metrics({
23-
defaultDimensions: defaultValues
23+
defaultDimensions: defaultValues,
2424
});
2525

2626
const tracer = new Tracer();
2727

28-
export {
29-
logger,
30-
metrics,
31-
tracer
32-
};
28+
export { logger, metrics, tracer };

examples/cdk/functions/get-all-items.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
1+
import {
2+
APIGatewayProxyEvent,
3+
APIGatewayProxyResult,
4+
Context,
5+
} from 'aws-lambda';
26
import middy from '@middy/core';
37
import { tableName } from './common/constants';
48
import { logger, tracer, metrics } from './common/powertools';
@@ -12,7 +16,7 @@ import { default as request } from 'phin';
1216
/*
1317
*
1418
* This example uses the Middy middleware instrumentation.
15-
* It is the best choice if your existing code base relies on the Middy middleware engine.
19+
* It is the best choice if your existing code base relies on the Middy middleware engine.
1620
* Powertools offers compatible Middy middleware to make this integration seamless.
1721
* Find more Information in the docs: https://awslabs.github.io/aws-lambda-powertools-typescript/
1822
*
@@ -23,9 +27,14 @@ import { default as request } from 'phin';
2327
* @returns {Object} object - API Gateway Lambda Proxy Output Format
2428
*
2529
*/
26-
const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
30+
const getAllItemsHandler = async (
31+
event: APIGatewayProxyEvent,
32+
context: Context
33+
): Promise<APIGatewayProxyResult> => {
2734
if (event.httpMethod !== 'GET') {
28-
throw new Error(`getAllItems only accepts GET method, you tried: ${event.httpMethod}`);
35+
throw new Error(
36+
`getAllItems only accepts GET method, you tried: ${event.httpMethod}`
37+
);
2938
}
3039

3140
// Tracer: Add awsRequestId as annotation
@@ -60,9 +69,11 @@ const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context)
6069
throw new Error('SAMPLE_TABLE environment variable is not set');
6170
}
6271

63-
const data = await docClient.send(new ScanCommand({
64-
TableName: tableName
65-
}));
72+
const data = await docClient.send(
73+
new ScanCommand({
74+
TableName: tableName,
75+
})
76+
);
6677
const { Items: items } = data;
6778

6879
// Logger: All log statements are written to CloudWatch
@@ -75,15 +86,15 @@ const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context)
7586

7687
return {
7788
statusCode: 200,
78-
body: JSON.stringify(items)
89+
body: JSON.stringify(items),
7990
};
8091
} catch (err) {
8192
tracer.addErrorAsMetadata(err as Error);
8293
logger.error('Error reading from table. ' + err);
8394

8495
return {
8596
statusCode: 500,
86-
body: JSON.stringify({ 'error': 'Error reading from table.' })
97+
body: JSON.stringify({ error: 'Error reading from table.' }),
8798
};
8899
}
89100
};
@@ -95,4 +106,4 @@ export const handler = middy(getAllItemsHandler)
95106
// Use the middleware by passing the Logger instance as a parameter
96107
.use(injectLambdaContext(logger, { logEvent: true }))
97108
// Use the middleware by passing the Tracer instance as a parameter
98-
.use(captureLambdaHandler(tracer, { 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
109+
.use(captureLambdaHandler(tracer, { 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

examples/cdk/functions/get-by-id.ts

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
1+
import {
2+
APIGatewayProxyEvent,
3+
APIGatewayProxyResult,
4+
Context,
5+
} from 'aws-lambda';
26
import { tableName } from './common/constants';
37
import { logger, tracer, metrics } from './common/powertools';
48
import { LambdaInterface } from '@aws-lambda-powertools/commons';
@@ -22,7 +26,6 @@ import { default as request } from 'phin';
2226
*/
2327

2428
class Lambda implements LambdaInterface {
25-
2629
@tracer.captureMethod()
2730
public async getUuid(): Promise<string> {
2831
// Request a sample random uuid from a webservice
@@ -37,11 +40,18 @@ class Lambda implements LambdaInterface {
3740

3841
@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
3942
@logger.injectLambdaContext({ logEvent: true })
40-
@metrics.logMetrics({ throwOnEmptyMetrics: false, captureColdStartMetric: true })
41-
public async handler(event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
42-
43+
@metrics.logMetrics({
44+
throwOnEmptyMetrics: false,
45+
captureColdStartMetric: true,
46+
})
47+
public async handler(
48+
event: APIGatewayProxyEvent,
49+
context: Context
50+
): Promise<APIGatewayProxyResult> {
4351
if (event.httpMethod !== 'GET') {
44-
throw new Error(`getById only accepts GET method, you tried: ${event.httpMethod}`);
52+
throw new Error(
53+
`getById only accepts GET method, you tried: ${event.httpMethod}`
54+
);
4555
}
4656

4757
// Tracer: Add awsRequestId as annotation
@@ -76,12 +86,14 @@ class Lambda implements LambdaInterface {
7686
if (!event.pathParameters.id) {
7787
throw new Error('PathParameter id is missing');
7888
}
79-
const data = await docClient.send(new GetCommand({
80-
TableName: tableName,
81-
Key: {
82-
id: event.pathParameters.id
83-
}
84-
}));
89+
const data = await docClient.send(
90+
new GetCommand({
91+
TableName: tableName,
92+
Key: {
93+
id: event.pathParameters.id,
94+
},
95+
})
96+
);
8597
const item = data.Item;
8698

8799
logger.info(`Response ${event.path}`, {
@@ -91,19 +103,18 @@ class Lambda implements LambdaInterface {
91103

92104
return {
93105
statusCode: 200,
94-
body: JSON.stringify(item)
106+
body: JSON.stringify(item),
95107
};
96108
} catch (err) {
97109
tracer.addErrorAsMetadata(err as Error);
98110
logger.error('Error reading from table. ' + err);
99111

100112
return {
101113
statusCode: 500,
102-
body: JSON.stringify({ 'error': 'Error reading from table.' })
114+
body: JSON.stringify({ error: 'Error reading from table.' }),
103115
};
104116
}
105117
}
106-
107118
}
108119

109120
const handlerClass = new Lambda();

examples/cdk/functions/put-item.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
1+
import {
2+
APIGatewayProxyEvent,
3+
APIGatewayProxyResult,
4+
Context,
5+
} from 'aws-lambda';
26
import { tableName } from './common/constants';
37
import { logger, tracer, metrics } from './common/powertools';
48
import { docClient } from './common/dynamodb-client';
@@ -9,17 +13,22 @@ import type { Subsegment } from 'aws-xray-sdk-core';
913
/**
1014
*
1115
* This example uses the manual instrumentation.
12-
*
16+
*
1317
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
1418
* @param {APIGatewayProxyEvent} event - API Gateway Lambda Proxy Input Format
1519
*
1620
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
1721
* @returns {Promise<APIGatewayProxyResult>} object - API Gateway Lambda Proxy Output Format
1822
*
1923
*/
20-
export const handler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
24+
export const handler = async (
25+
event: APIGatewayProxyEvent,
26+
context: Context
27+
): Promise<APIGatewayProxyResult> => {
2128
if (event.httpMethod !== 'POST') {
22-
throw new Error(`putItem only accepts POST method, you tried: ${event.httpMethod}`);
29+
throw new Error(
30+
`putItem only accepts POST method, you tried: ${event.httpMethod}`
31+
);
2332
}
2433

2534
// Logger: Log the incoming event
@@ -80,13 +89,15 @@ export const handler = async (event: APIGatewayProxyEvent, context: Context): Pr
8089
const body = JSON.parse(event.body);
8190
const { id, name } = body;
8291

83-
await docClient.send(new PutCommand({
84-
TableName: tableName,
85-
Item: {
86-
id,
87-
name
88-
}
89-
}));
92+
await docClient.send(
93+
new PutCommand({
94+
TableName: tableName,
95+
Item: {
96+
id,
97+
name,
98+
},
99+
})
100+
);
90101

91102
logger.info(`Response ${event.path}`, {
92103
statusCode: 200,
@@ -95,15 +106,15 @@ export const handler = async (event: APIGatewayProxyEvent, context: Context): Pr
95106

96107
return {
97108
statusCode: 200,
98-
body: JSON.stringify(body)
109+
body: JSON.stringify(body),
99110
};
100111
} catch (err) {
101112
tracer.addErrorAsMetadata(err as Error);
102113
logger.error('Error writing data to table. ' + err);
103114

104115
return {
105116
statusCode: 500,
106-
body: JSON.stringify({ 'error': 'Error writing data to table.' })
117+
body: JSON.stringify({ error: 'Error writing data to table.' }),
107118
};
108119
} finally {
109120
if (segment && handlerSegment) {

examples/cdk/jest.config.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@ module.exports = {
33
roots: ['<rootDir>/tests'],
44
testMatch: ['**/*.test.ts'],
55
transform: {
6-
'^.+\\.tsx?$': 'ts-jest'
7-
}
6+
'^.+\\.tsx?$': 'ts-jest',
7+
},
88
};

examples/cdk/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
"build": "tsc --skipLibCheck",
1616
"watch": "tsc -w",
1717
"test": "npm run test:unit",
18-
"lint": "eslint --ext .ts --no-error-on-unmatched-pattern src tests",
19-
"lint-fix": "eslint --fix --ext .ts --fix --no-error-on-unmatched-pattern src tests",
18+
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
19+
"lint-fix": "eslint --fix --ext .ts,.js --fix --no-error-on-unmatched-pattern .",
2020
"package": "echo 'Not applicable'",
2121
"package-bundle": "echo 'Not applicable'",
2222
"test:unit": "export POWERTOOLS_DEV=true && npm run build && jest --silent",

0 commit comments

Comments
 (0)