Skip to content
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

style(docs): apply standardized formatting #1461

Merged
merged 1 commit into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 41 additions & 36 deletions examples/sam/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,63 +5,68 @@ module.exports = {
jest: true,
node: true,
},
extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended' ],
ignorePatterns: ['cdk.out', 'lib'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
plugins: ['@typescript-eslint', 'prettier'],
settings: {
'import/resolver': {
node: {},
typescript: {
project: './tsconfig.es.json',
project: './tsconfig.json',
alwaysTryTypes: true,
},
},
},
rules: {
'@typescript-eslint/ban-ts-ignore': ['off'],
'@typescript-eslint/camelcase': ['off'],
'@typescript-eslint/explicit-function-return-type': [ 'error', { allowExpressions: true } ],
'@typescript-eslint/explicit-member-accessibility': 'error',
'@typescript-eslint/indent': [ 'error', 2, { SwitchCase: 1 } ],
'@typescript-eslint/interface-name-prefix': ['off'],
'@typescript-eslint/member-delimiter-style': [ 'error', { multiline: { delimiter: 'none' } } ],
'@typescript-eslint/explicit-function-return-type': [
'error',
{ allowExpressions: true },
], // Enforce return type definitions for functions
'@typescript-eslint/explicit-member-accessibility': 'error', // Enforce explicit accessibility modifiers on class properties and methods (public, private, protected)
'@typescript-eslint/member-ordering': [
// Standardize the order of class members
'error',
{
default: {
memberTypes: [
'signature',
'public-field', // = ["public-static-field", "public-instance-field"]
'protected-field', // = ["protected-static-field", "protected-instance-field"]
'private-field', // = ["private-static-field", "private-instance-field"]
'public-field',
'protected-field',
'private-field',
'constructor',
'public-method', // = ["public-static-method", "public-instance-method"]
'protected-method', // = ["protected-static-method", "protected-instance-method"]
'private-method', // = ["private-static-method", "private-instance-method"]
'public-method',
'protected-method',
'private-method',
],
order: 'alphabetically',
},
},
],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-inferrable-types': ['off'],
'@typescript-eslint/no-unused-vars': [ 'error', { argsIgnorePattern: '^_' } ],
'@typescript-eslint/no-use-before-define': ['off'],
'@typescript-eslint/semi': [ 'error', 'always' ],
'array-bracket-spacing': [ 'error', 'always', { singleValue: false } ],
'arrow-body-style': [ 'error', 'as-needed' ],
'computed-property-spacing': [ 'error', 'never' ],
'func-style': [ 'warn', 'expression' ],
indent: [ 'error', 2, { SwitchCase: 1 } ],
'keyword-spacing': 'error',
'newline-before-return': 2,
'no-console': 0,
'no-multi-spaces': [ 'error', { ignoreEOLComments: false } ],
'no-multiple-empty-lines': [ 'error', { max: 1, maxBOF: 0 } ],
'no-throw-literal': 'error',
'object-curly-spacing': [ 'error', 'always' ],
'prefer-arrow-callback': 'error',
quotes: [ 'error', 'single', { allowTemplateLiterals: true } ],
semi: [ 'error', 'always' ]
'@typescript-eslint/no-explicit-any': 'error', // Disallow usage of the any type
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], // Disallow unused variables, except for variables starting with an underscore
'@typescript-eslint/no-use-before-define': ['off'], // Check if this rule is needed
'no-unused-vars': 'off', // Disable eslint core rule, since it's replaced by @typescript-eslint/no-unused-vars
// Rules from eslint core https://eslint.org/docs/latest/rules/
'array-bracket-spacing': ['error', 'never'], // Disallow spaces inside of array brackets
'computed-property-spacing': ['error', 'never'], // Disallow spaces inside of computed properties
'func-style': ['warn', 'expression'], // Enforce function expressions instead of function declarations
'keyword-spacing': 'error', // Enforce spaces after keywords and before parenthesis, e.g. if (condition) instead of if(condition)
'padding-line-between-statements': [
// Require an empty line before return statements
'error',
{ blankLine: 'always', prev: '*', next: 'return' },
],
'no-console': 0, // Allow console.log statements
'no-multi-spaces': ['error', { ignoreEOLComments: false }], // Disallow multiple spaces except for comments
'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
'no-throw-literal': 'error', // Disallow throwing literals as exceptions, e.g. throw 'error' instead of throw new Error('error')
'object-curly-spacing': ['error', 'always'], // Enforce spaces inside of curly braces in objects
'prefer-arrow-callback': 'error', // Enforce arrow functions instead of anonymous functions for callbacks
quotes: ['error', 'single', { allowTemplateLiterals: true }], // Enforce single quotes except for template strings
semi: ['error', 'always'], // Require semicolons instead of ASI (automatic semicolon insertion) at the end of statements
},
};
4 changes: 2 additions & 2 deletions examples/sam/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ module.exports = {
roots: ['<rootDir>/tests'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
'^.+\\.tsx?$': 'ts-jest',
},
};
6 changes: 3 additions & 3 deletions examples/sam/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
"scripts": {
"build": "sam build --beta-features",
"test": "npm run test:unit",
"lint": "eslint --ext .ts --no-error-on-unmatched-pattern src tests",
"lint-fix": "eslint --fix --ext .ts --fix --no-error-on-unmatched-pattern src tests",
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint-fix": "eslint --fix --ext .ts,.js --fix --no-error-on-unmatched-pattern .",
"package": "echo 'Not applicable'",
"package-bundle": "echo 'Not applicable'",
"test:unit": "export POWERTOOLS_DEV=true && npm run build && jest --silent",
Expand Down Expand Up @@ -46,4 +46,4 @@
"@middy/core": "^3.6.2",
"phin": "^3.7.0"
}
}
}
4 changes: 1 addition & 3 deletions examples/sam/src/common/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
// Get the DynamoDB table name from environment variables
const tableName = process.env.SAMPLE_TABLE;

export {
tableName
};
export { tableName };
4 changes: 1 addition & 3 deletions examples/sam/src/common/dynamodb-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,4 @@ const translateConfig = { marshallOptions, unmarshallOptions };
// Create the DynamoDB Document client.
const docClient = DynamoDBDocumentClient.from(ddbClient, translateConfig);

export {
docClient
};
export { docClient };
12 changes: 4 additions & 8 deletions examples/sam/src/common/powertools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const awsLambdaPowertoolsVersion = '1.5.0';

const defaultValues = {
region: process.env.AWS_REGION || 'N/A',
executionEnv: process.env.AWS_EXECUTION_ENV || 'N/A'
executionEnv: process.env.AWS_EXECUTION_ENV || 'N/A',
};

const logger = new Logger({
Expand All @@ -15,18 +15,14 @@ const logger = new Logger({
logger: {
name: '@aws-lambda-powertools/logger',
version: awsLambdaPowertoolsVersion,
}
},
},
});

const metrics = new Metrics({
defaultDimensions: defaultValues
defaultDimensions: defaultValues,
});

const tracer = new Tracer();

export {
logger,
metrics,
tracer
};
export { logger, metrics, tracer };
35 changes: 23 additions & 12 deletions examples/sam/src/get-all-items.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import middy from '@middy/core';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
Expand All @@ -12,7 +16,7 @@ import { default as request } from 'phin';
/*
*
* This example uses the Middy middleware instrumentation.
* It is the best choice if your existing code base relies on the Middy middleware engine.
* It is the best choice if your existing code base relies on the Middy middleware engine.
* Powertools offers compatible Middy middleware to make this integration seamless.
* Find more Information in the docs: https://awslabs.github.io/aws-lambda-powertools-typescript/
*
Expand All @@ -23,9 +27,14 @@ import { default as request } from 'phin';
* @returns {Object} object - API Gateway Lambda Proxy Output Format
*
*/
const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
const getAllItemsHandler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
if (event.httpMethod !== 'GET') {
throw new Error(`getAllItems only accepts GET method, you tried: ${event.httpMethod}`);
throw new Error(
`getAllItems only accepts GET method, you tried: ${event.httpMethod}`
);
}

// Tracer: Add awsRequestId as annotation
Expand Down Expand Up @@ -60,30 +69,32 @@ const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context)
throw new Error('SAMPLE_TABLE environment variable is not set');
}

const data = await docClient.send(new ScanCommand({
TableName: tableName
}));
const data = await docClient.send(
new ScanCommand({
TableName: tableName,
})
);
const { Items: items } = data;

// Logger: All log statements are written to CloudWatch
logger.debug(`retrieved items: ${items?.length || 0}`);

logger.info(`Response ${event.path}`, {
statusCode: 200,
body: items,
});

return {
statusCode: 200,
body: JSON.stringify(items)
body: JSON.stringify(items),
};
} catch (err) {
tracer.addErrorAsMetadata(err as Error);
logger.error('Error reading from table. ' + err);

return {
statusCode: 500,
body: JSON.stringify({ 'error': 'Error reading from table.' })
body: JSON.stringify({ error: 'Error reading from table.' }),
};
}
};
Expand All @@ -95,4 +106,4 @@ export const handler = middy(getAllItemsHandler)
// Use the middleware by passing the Logger instance as a parameter
.use(injectLambdaContext(logger, { logEvent: true }))
// Use the middleware by passing the Tracer instance as a parameter
.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
.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
47 changes: 29 additions & 18 deletions examples/sam/src/get-by-id.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
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';
Expand All @@ -22,7 +26,6 @@ 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
Expand All @@ -37,11 +40,18 @@ class Lambda implements LambdaInterface {

@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
@logger.injectLambdaContext({ logEvent: true })
@metrics.logMetrics({ throwOnEmptyMetrics: false, captureColdStartMetric: true })
public async handler(event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {

@metrics.logMetrics({
throwOnEmptyMetrics: false,
captureColdStartMetric: true,
})
public async handler(
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> {
if (event.httpMethod !== 'GET') {
throw new Error(`getById only accepts GET method, you tried: ${event.httpMethod}`);
throw new Error(
`getById only accepts GET method, you tried: ${event.httpMethod}`
);
}

// Tracer: Add awsRequestId as annotation
Expand Down Expand Up @@ -76,34 +86,35 @@ class Lambda implements LambdaInterface {
if (!event.pathParameters.id) {
throw new Error('PathParameter id is missing');
}
const data = await docClient.send(new GetCommand({
TableName: tableName,
Key: {
id: event.pathParameters.id
}
}));
const data = await docClient.send(
new GetCommand({
TableName: tableName,
Key: {
id: event.pathParameters.id,
},
})
);
const item = data.Item;

logger.info(`Response ${event.path}`, {
statusCode: 200,
body: item,
});

return {
statusCode: 200,
body: JSON.stringify(item)
body: JSON.stringify(item),
};
} catch (err) {
tracer.addErrorAsMetadata(err as Error);
logger.error('Error reading from table. ' + err);

return {
statusCode: 500,
body: JSON.stringify({ 'error': 'Error reading from table.' })
body: JSON.stringify({ error: 'Error reading from table.' }),
};
}
}

}

const handlerClass = new Lambda();
Expand Down
Loading