Skip to content

style(commons): apply standardized formatting #1454

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 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
72 changes: 72 additions & 0 deletions packages/commons/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
module.exports = {
env: {
browser: false,
es2020: true,
jest: true,
node: true,
},
ignorePatterns: ['coverage', 'lib'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'prettier'],
settings: {
'import/resolver': {
node: {},
typescript: {
project: './tsconfig.json',
alwaysTryTypes: true,
},
},
},
rules: {
'@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',
'protected-field',
'private-field',
'constructor',
'public-method',
'protected-method',
'private-method',
],
order: 'alphabetically',
},
},
],
'@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
},
};
47 changes: 17 additions & 30 deletions packages/commons/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,24 @@ module.exports = {
name: 'AWS Lambda Powertools utility: COMMONS',
color: 'red',
},
'preset': 'ts-jest',
'transform': {
preset: 'ts-jest',
transform: {
'^.+\\.ts?$': 'ts-jest',
},
moduleFileExtensions: [ 'js', 'ts' ],
'collectCoverageFrom': [
'**/src/**/*.ts',
'!**/node_modules/**',
],
'testMatch': ['**/?(*.)+(spec|test).ts'],
'roots': [
'<rootDir>/src',
'<rootDir>/tests',
],
'testPathIgnorePatterns': [
'/node_modules/',
],
'testEnvironment': 'node',
'coveragePathIgnorePatterns': [
'/node_modules/',
],
'coverageThreshold': {
'global': {
'statements': 100,
'branches': 100,
'functions': 100,
'lines': 100,
moduleFileExtensions: ['js', 'ts'],
collectCoverageFrom: ['**/src/**/*.ts', '!**/node_modules/**'],
testMatch: ['**/?(*.)+(spec|test).ts'],
roots: ['<rootDir>/src', '<rootDir>/tests'],
testPathIgnorePatterns: ['/node_modules/'],
testEnvironment: 'node',
coveragePathIgnorePatterns: ['/node_modules/'],
coverageThreshold: {
global: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
},
'coverageReporters': [
'json-summary',
'text',
'lcov' ],
};
coverageReporters: ['json-summary', 'text', 'lcov'],
};
9 changes: 5 additions & 4 deletions packages/commons/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
"test:e2e": "echo 'Not Applicable'",
"watch": "jest --watch",
"build": "tsc",
"lint": "eslint --ext .ts --no-error-on-unmatched-pattern src tests",
"lint-fix": "eslint --fix --ext .ts --no-error-on-unmatched-pattern src tests",
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .",
"package": "mkdir -p dist/ && npm pack && mv *.tgz dist/",
"package-bundle": "../../package-bundler.sh commons-bundle ./dist",
"prepare": "npm run build"
},
"lint-staged": {
"*.ts": "npm run lint-fix"
"*.ts": "npm run lint-fix",
"*.js": "npm run lint-fix"
},
"homepage": "https://github.com/awslabs/aws-lambda-powertools-typescript/tree/main/packages/metrics#readme",
"license": "MIT-0",
Expand Down Expand Up @@ -51,4 +52,4 @@
"@aws-sdk/client-lambda": "^3.310.0",
"@aws-sdk/util-utf8-node": "^3.259.0"
}
}
}
52 changes: 26 additions & 26 deletions packages/commons/src/Utility.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,51 @@
/**
* ## Intro
* Utility is a base class that other Powertools utilites can extend to inherit shared logic.
*
*
*
*
* ## Key features
* * Cold Start heuristic to determine if the current
*
* * Cold Start heuristic to determine if the current
*
* ## Usage
*
*
* ### Cold Start
*
*
* Cold start is a term commonly used to describe the `Init` phase of a Lambda function. In this phase, Lambda creates or unfreezes an execution environment with the configured resources, downloads the code for the function and all layers, initializes any extensions, initializes the runtime, and then runs the function’s initialization code (the code outside the main handler). The Init phase happens either during the first invocation, or in advance of function invocations if you have enabled provisioned concurrency.
*
*
* To learn more about the Lambda execution environment lifecycle, see the [Execution environment section](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html) of the AWS Lambda documentation.
*
*
* As a Powertools user you probably won't be using this class directly, in fact if you use other Powertools utilities the cold start heuristic found here is already used to:
* * Add a `coldStart` key to the structured logs when injecting context information in `Logger`
* * Emit a metric during a cold start function invocation in `Metrics`
* * Annotate the invocation segment with a `coldStart` key in `Tracer`
*
*
* If you want to use this logic in your own utilities, `Utility` provides two methods:
*
*
* #### `getColdStart()`
*
*
* Since the `Utility` class is instantiated outside of the Lambda handler it will persist across invocations of the same execution environment. This means that if you call `getColdStart()` multiple times, it will return `true` during the first invocation, and `false` afterwards.
*
*
* @example
* ```typescript
* import { Utility } from '@aws-lambda-powertools/commons';
*
*
* const utility = new Utility();
*
*
* export const handler = async (_event: any, _context: any) => {
* utility.getColdStart();
* };
* ```
*
*
* #### `isColdStart()`
*
*
* This method is an alias of `getColdStart()` and is exposed for convenience and better readability in certain usages.
*
*
* @example
* ```typescript
* import { Utility } from '@aws-lambda-powertools/commons';
*
*
* const utility = new Utility();
*
*
* export const handler = async (_event: any, _context: any) => {
* if (utility.isColdStart()) {
* // do something, this block is only executed on the first invocation of the function
Expand All @@ -56,7 +56,7 @@
* ```
*/
export class Utility {
private coldStart: boolean = true;
private coldStart = true;
private readonly defaultServiceName: string = 'service_undefined';

public getColdStart(): boolean {
Expand All @@ -78,12 +78,12 @@ export class Utility {
}

/**
* Validate that the service name provided is valid.
* Used internally during initialization.
*
* @param serviceName - Service name to validate
*/
* Validate that the service name provided is valid.
* Used internally during initialization.
*
* @param serviceName - Service name to validate
*/
protected isValidServiceName(serviceName?: string): boolean {
return typeof serviceName === 'string' && serviceName.trim().length > 0;
}
}
}
7 changes: 2 additions & 5 deletions packages/commons/src/config/ConfigService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
* @abstract
*/
abstract class ConfigService {

/**
* It returns the value of an environment variable that has given name.
*
Expand All @@ -26,7 +25,7 @@ abstract class ConfigService {

/**
* It returns the value of the _X_AMZN_TRACE_ID environment variable.
*
*
* The AWS X-Ray Trace data available in the environment variable has this format:
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
*
Expand All @@ -45,6 +44,4 @@ abstract class ConfigService {
public abstract isValueTrue(value: string): boolean;
}

export {
ConfigService,
};
export { ConfigService };
14 changes: 5 additions & 9 deletions packages/commons/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { ConfigService } from '.';
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables
*/
class EnvironmentVariablesService extends ConfigService {

/**
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables
* @protected
Expand Down Expand Up @@ -44,7 +43,7 @@ class EnvironmentVariablesService extends ConfigService {

/**
* It returns the value of the _X_AMZN_TRACE_ID environment variable.
*
*
* The AWS X-Ray Trace data available in the environment variable has this format:
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
*
Expand All @@ -60,7 +59,7 @@ class EnvironmentVariablesService extends ConfigService {

/**
* It returns true if the Sampled flag is set in the _X_AMZN_TRACE_ID environment variable.
*
*
* The AWS X-Ray Trace data available in the environment variable has this format:
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
*
Expand All @@ -79,7 +78,7 @@ class EnvironmentVariablesService extends ConfigService {
* @returns boolean
*/
public isValueTrue(value: string): boolean {
const truthyValues: string[] = [ '1', 'y', 'yes', 't', 'true', 'on' ];
const truthyValues: string[] = ['1', 'y', 'yes', 't', 'true', 'on'];

return truthyValues.includes(value.toLowerCase());
}
Expand All @@ -98,8 +97,7 @@ class EnvironmentVariablesService extends ConfigService {
const xRayTraceData: Record<string, string> = {};

xRayTraceEnv.split(';').forEach((field) => {

const [ key, value ] = field.split('=');
const [key, value] = field.split('=');

xRayTraceData[key] = value;
});
Expand All @@ -108,6 +106,4 @@ class EnvironmentVariablesService extends ConfigService {
}
}

export {
EnvironmentVariablesService,
};
export { EnvironmentVariablesService };
2 changes: 1 addition & 1 deletion packages/commons/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './ConfigService';
export * from './EnvironmentVariablesService';
export * from './EnvironmentVariablesService';
2 changes: 1 addition & 1 deletion packages/commons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ export * from './Utility';
export * from './config';
export * as ContextExamples from './samples/resources/contexts';
export * as Events from './samples/resources/events';
export * from './types/middy';
export * from './types/middy';
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ const helloworldContext: Context = {
memoryLimitInMB: '128',
logGroupName: '/aws/lambda/foo-bar-function-123456abcdef',
logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456',
invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function',
invokedFunctionArn:
'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function',
awsRequestId: 'c6af9ac6-7b61-11e6-9a41-93e812345678',
getRemainingTimeInMillis: () => 1234,
done: () => console.log('Done!'),
fail: () => console.log('Failed!'),
succeed: () => console.log('Succeeded!'),
};

export {
helloworldContext,
};
export { helloworldContext };
2 changes: 1 addition & 1 deletion packages/commons/src/samples/resources/contexts/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './hello-world';
export * from './hello-world';
2 changes: 1 addition & 1 deletion packages/commons/src/samples/resources/events/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * as Custom from './custom';
export * as Custom from './custom';
Loading