Skip to content

Commit 455261a

Browse files
authored
style(docs): apply standardized formatting (#1461)
1 parent 666e8b0 commit 455261a

File tree

10 files changed

+141
-107
lines changed

10 files changed

+141
-107
lines changed

examples/sam/.eslintrc.js

Lines changed: 41 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,63 +5,68 @@ module.exports = {
55
jest: true,
66
node: true,
77
},
8-
extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended' ],
8+
ignorePatterns: ['cdk.out', 'lib'],
9+
extends: [
10+
'plugin:@typescript-eslint/recommended',
11+
'plugin:prettier/recommended',
12+
],
913
parser: '@typescript-eslint/parser',
10-
plugins: ['@typescript-eslint'],
14+
plugins: ['@typescript-eslint', 'prettier'],
1115
settings: {
1216
'import/resolver': {
1317
node: {},
1418
typescript: {
15-
project: './tsconfig.es.json',
19+
project: './tsconfig.json',
1620
alwaysTryTypes: true,
1721
},
1822
},
1923
},
2024
rules: {
21-
'@typescript-eslint/ban-ts-ignore': ['off'],
22-
'@typescript-eslint/camelcase': ['off'],
23-
'@typescript-eslint/explicit-function-return-type': [ 'error', { allowExpressions: true } ],
24-
'@typescript-eslint/explicit-member-accessibility': 'error',
25-
'@typescript-eslint/indent': [ 'error', 2, { SwitchCase: 1 } ],
26-
'@typescript-eslint/interface-name-prefix': ['off'],
27-
'@typescript-eslint/member-delimiter-style': [ 'error', { multiline: { delimiter: 'none' } } ],
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)
2830
'@typescript-eslint/member-ordering': [
31+
// Standardize the order of class members
2932
'error',
3033
{
3134
default: {
3235
memberTypes: [
3336
'signature',
34-
'public-field', // = ["public-static-field", "public-instance-field"]
35-
'protected-field', // = ["protected-static-field", "protected-instance-field"]
36-
'private-field', // = ["private-static-field", "private-instance-field"]
37+
'public-field',
38+
'protected-field',
39+
'private-field',
3740
'constructor',
38-
'public-method', // = ["public-static-method", "public-instance-method"]
39-
'protected-method', // = ["protected-static-method", "protected-instance-method"]
40-
'private-method', // = ["private-static-method", "private-instance-method"]
41+
'public-method',
42+
'protected-method',
43+
'private-method',
4144
],
4245
order: 'alphabetically',
4346
},
4447
},
4548
],
46-
'@typescript-eslint/no-explicit-any': 'error',
47-
'@typescript-eslint/no-inferrable-types': ['off'],
48-
'@typescript-eslint/no-unused-vars': [ 'error', { argsIgnorePattern: '^_' } ],
49-
'@typescript-eslint/no-use-before-define': ['off'],
50-
'@typescript-eslint/semi': [ 'error', 'always' ],
51-
'array-bracket-spacing': [ 'error', 'always', { singleValue: false } ],
52-
'arrow-body-style': [ 'error', 'as-needed' ],
53-
'computed-property-spacing': [ 'error', 'never' ],
54-
'func-style': [ 'warn', 'expression' ],
55-
indent: [ 'error', 2, { SwitchCase: 1 } ],
56-
'keyword-spacing': 'error',
57-
'newline-before-return': 2,
58-
'no-console': 0,
59-
'no-multi-spaces': [ 'error', { ignoreEOLComments: false } ],
60-
'no-multiple-empty-lines': [ 'error', { max: 1, maxBOF: 0 } ],
61-
'no-throw-literal': 'error',
62-
'object-curly-spacing': [ 'error', 'always' ],
63-
'prefer-arrow-callback': 'error',
64-
quotes: [ 'error', 'single', { allowTemplateLiterals: true } ],
65-
semi: [ 'error', 'always' ]
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
6671
},
6772
};

examples/sam/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/sam/package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
"scripts": {
1212
"build": "sam build --beta-features",
1313
"test": "npm run test:unit",
14-
"lint": "eslint --ext .ts --no-error-on-unmatched-pattern src tests",
15-
"lint-fix": "eslint --fix --ext .ts --fix --no-error-on-unmatched-pattern src tests",
14+
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
15+
"lint-fix": "eslint --fix --ext .ts,.js --fix --no-error-on-unmatched-pattern .",
1616
"package": "echo 'Not applicable'",
1717
"package-bundle": "echo 'Not applicable'",
1818
"test:unit": "export POWERTOOLS_DEV=true && npm run build && jest --silent",
@@ -46,4 +46,4 @@
4646
"@middy/core": "^3.6.2",
4747
"phin": "^3.7.0"
4848
}
49-
}
49+
}

examples/sam/src/common/constants.ts

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/sam/src/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/sam/src/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/sam/src/get-all-items.ts

Lines changed: 23 additions & 12 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,30 +69,32 @@ 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
6980
logger.debug(`retrieved items: ${items?.length || 0}`);
70-
81+
7182
logger.info(`Response ${event.path}`, {
7283
statusCode: 200,
7384
body: items,
7485
});
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);
83-
94+
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/sam/src/get-by-id.ts

Lines changed: 29 additions & 18 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,34 +86,35 @@ 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;
86-
98+
8799
logger.info(`Response ${event.path}`, {
88100
statusCode: 200,
89101
body: item,
90102
});
91-
103+
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);
99-
111+
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();

0 commit comments

Comments
 (0)