Skip to content

Commit ec59136

Browse files
committed
Refactor eslint, prettier
1 parent 3f45246 commit ec59136

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+340
-303
lines changed

.eslintrc

Lines changed: 32 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,64 +2,66 @@
22
"root": true,
33
"parser": "@typescript-eslint/parser",
44
"parserOptions": {
5+
"project": true,
56
"tsconfigRootDir": ".",
6-
"project": "tsconfig.json",
77
"sourceType": "module"
88
},
9-
"plugins": ["@typescript-eslint", "sonarjs", "jest"],
9+
"plugins": ["@typescript-eslint", "sonarjs", "jest", "prettier"],
1010
"extends": [
1111
"eslint:recommended",
1212
"airbnb-base",
1313
"airbnb-typescript/base",
1414
"plugin:jest/recommended",
1515
"plugin:sonarjs/recommended",
16-
"plugin:@typescript-eslint/recommended",
17-
"plugin:@typescript-eslint/recommended-requiring-type-checking"
16+
"plugin:@typescript-eslint/strict-type-checked",
17+
"plugin:@typescript-eslint/stylistic-type-checked",
18+
"plugin:prettier/recommended"
1819
],
1920
"ignorePatterns": ["**/node_modules/**", "dist/**", "src/entity/**"],
20-
"rules": { // These rules are for reference only.
21+
"rules": {
22+
// These rules are for reference only.
23+
//#region eslint
2124
"class-methods-use-this": "off",
2225
// https://github.com/typescript-eslint/typescript-eslint/issues/1277
2326
"consistent-return": "off",
2427
"func-names": "off",
25-
"max-len": ["error", { "code": 140, "ignoreTemplateLiterals": true }],
28+
"max-len": ["error", { "code": 140, "ignoreTemplateLiterals": true, "ignoreUrls": true }],
2629
"newline-per-chained-call": "off",
2730
"no-await-in-loop": "off",
2831
"no-continue": "off",
2932
// https://github.com/airbnb/javascript/issues/1342
3033
"no-param-reassign": ["error", { "props": false }],
3134
// https://github.com/airbnb/javascript/issues/1271
32-
// https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb-base/rules/style.js#L334-L352
35+
// https://github.com/airbnb/javascript/blob/fd77bbebb77362ddecfef7aba3bf6abf7bdd81f2/packages/eslint-config-airbnb-base/rules/style.js#L340-L358
3336
"no-restricted-syntax": ["error", "ForInStatement", "LabeledStatement", "WithStatement"],
3437
"no-underscore-dangle": ["error", { "allow": ["_id"] }],
3538
"no-void": ["error", { "allowAsStatement": true }],
3639
"object-curly-newline": "off",
3740
"spaced-comment": ["error", "always", { "line": { "markers": ["/", "#region", "#endregion"] } }],
41+
//#endregion
3842

39-
// Change eslint rule to @typescript-eslint rule
40-
"lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
41-
"no-dupe-class-members": "off",
42-
"no-duplicate-imports": "off",
43-
"no-loop-func": "off",
44-
"no-return-await": "off",
45-
"no-unused-expressions": "off",
46-
"object-curly-spacing": "off",
47-
48-
"import/extensions": ["error", "never"],
43+
//#region import
44+
// https://github.com/tportio/tportio.github.io/issues/13
45+
"import/extensions": "off",
4946
// https://github.com/benmosher/eslint-plugin-import/issues/1753
5047
"import/named": "off",
5148
"import/no-default-export": "error",
52-
"import/order": ["error", { "groups": [["builtin", "external", "internal"]], "newlines-between": "always", "alphabetize": { "order": "asc", "caseInsensitive": true } }],
49+
"import/order": [
50+
"error",
51+
{
52+
"groups": [["builtin", "external", "internal"]],
53+
"newlines-between": "always",
54+
"alphabetize": { "order": "asc", "caseInsensitive": true }
55+
}
56+
],
5357
"import/prefer-default-export": "off",
58+
//#endregion
5459

55-
"@typescript-eslint/consistent-indexed-object-style": "error",
60+
//#region @typescript-eslint
5661
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "angle-bracket" }],
57-
"@typescript-eslint/explicit-function-return-type": "error",
58-
"@typescript-eslint/explicit-member-accessibility": ["error", { "overrides": { "constructors": "no-public" } }],
5962
"@typescript-eslint/lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
60-
"@typescript-eslint/member-delimiter-style": "error",
61-
"@typescript-eslint/member-ordering": "error",
62-
"@typescript-eslint/naming-convention": ["error",
63+
"@typescript-eslint/naming-convention": [
64+
"error",
6365
{ "selector": "default", "format": ["strictCamelCase"] },
6466
{ "selector": "variable", "format": ["strictCamelCase", "UPPER_CASE", "StrictPascalCase"] },
6567
// https://github.com/microsoft/TypeScript/issues/9458
@@ -69,30 +71,13 @@
6971
{ "selector": "typeLike", "format": ["StrictPascalCase"] },
7072
{ "selector": "enumMember", "format": ["UPPER_CASE"] }
7173
],
72-
"@typescript-eslint/no-dupe-class-members": "error",
73-
"@typescript-eslint/no-duplicate-imports": "error",
74-
"@typescript-eslint/no-floating-promises": ["error", { "ignoreIIFE": true, "ignoreVoid": true }],
75-
"@typescript-eslint/no-inferrable-types": ["error", { "ignoreParameters": true, "ignoreProperties": true }],
76-
"@typescript-eslint/no-loop-func": "error",
77-
"@typescript-eslint/no-misused-promises": ["error", { "checksVoidReturn": false }],
78-
"@typescript-eslint/no-unnecessary-boolean-literal-compare": "error",
79-
"@typescript-eslint/no-unnecessary-condition": "error",
80-
"@typescript-eslint/no-unnecessary-qualifier": "error",
81-
"@typescript-eslint/no-unnecessary-type-arguments": "error",
82-
"@typescript-eslint/no-unnecessary-type-assertion": "error",
83-
"@typescript-eslint/no-unnecessary-type-constraint": "error",
84-
"@typescript-eslint/no-unsafe-assignment": "off",
74+
"@typescript-eslint/no-extraneous-class": "off",
8575
"@typescript-eslint/no-unsafe-member-access": "off",
86-
"@typescript-eslint/no-unused-expressions": "error",
87-
"@typescript-eslint/object-curly-spacing": ["error", "always"],
88-
"@typescript-eslint/prefer-includes": "off",
89-
"@typescript-eslint/prefer-optional-chain": "error",
90-
"@typescript-eslint/promise-function-async": "error",
91-
"@typescript-eslint/restrict-template-expressions": "off",
92-
"@typescript-eslint/return-await": "error",
93-
"@typescript-eslint/typedef": ["error", { "memberVariableDeclaration": true, "parameter": true, "propertyDeclaration": true }],
94-
"@typescript-eslint/unbound-method": ["error", { "ignoreStatic": true }],
76+
//#endregion
9577

96-
"sonarjs/no-duplicate-string": "off"
78+
//#region sonarjs
79+
"sonarjs/no-duplicate-string": "off",
80+
"sonarjs/cognitive-complexity": ["error", 25]
81+
//#endregion
9782
}
9883
}

bin/entity.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,22 @@ if (!process.env.DB_HOST) {
1313
}
1414

1515
(async (): Promise<void> => {
16-
const response = await prompts([{
17-
type: 'text',
18-
name: 'db',
19-
message: 'Please enter a database name.',
20-
validate: (value: string): boolean => !!value,
21-
}, /* {
16+
const response = await prompts([
17+
{
18+
type: 'text',
19+
name: 'db',
20+
message: 'Please enter a database name.',
21+
validate: (value: string): boolean => !!value,
22+
} /* {
2223
type: 'select',
2324
name: 'db',
2425
message: 'Please select a database name.',
2526
choices: [
2627
{ title: 'db1' },
2728
{ title: 'db2' },
2829
],
29-
} */]);
30+
} */,
31+
]);
3032

3133
const { db } = <{ db: string }>response;
3234
const MODEL_DIR = pathJoin(__dirname, '../src/entity', db);
@@ -53,7 +55,7 @@ if (!process.env.DB_HOST) {
5355
try {
5456
execSync(`typeorm-model-generator ${generatorConfig.join(' ')}`, { stdio: 'pipe' });
5557
} catch (error) {
56-
console.error(`> Failed to load '${db}' database.\n${error}`);
58+
console.error(`> Failed to load '${db}' database.`, error);
5759
return;
5860
}
5961

@@ -68,4 +70,4 @@ if (!process.env.DB_HOST) {
6870
writeFileSync(pathJoin(MODEL_DIR, 'index.ts'), files.join('\n'));
6971

7072
console.log(`> '${db}' database entities has been created: ${MODEL_DIR}`);
71-
})();
73+
})().catch(console.error);

bin/ormconfig.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { configuration } from '../src/config';
77

88
dotenv.config();
99
const ormconfig = async (): Promise<DataSource> => {
10-
const config = <{ db: DataSourceOptions }> await configuration();
10+
const config = <{ db: DataSourceOptions }>await configuration();
1111

1212
return new DataSource({
1313
...config.db,

jest.config.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,7 @@ const jestConfig: Config = {
164164
],
165165

166166
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
167-
testPathIgnorePatterns: [
168-
'/node_modules/',
169-
'/dist/',
170-
'/e2e/',
171-
],
167+
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/e2e/'],
172168

173169
// The regexp pattern or array of patterns that Jest uses to detect test files
174170
// testRegex: [],
@@ -183,10 +179,13 @@ const jestConfig: Config = {
183179

184180
// A map from regular expressions to paths to transformers
185181
transform: {
186-
'^.+\\.tsx?$': ['ts-jest', {
187-
tsconfig: 'tsconfig.json',
188-
isolatedModules: true,
189-
}],
182+
'^.+\\.tsx?$': [
183+
'ts-jest',
184+
{
185+
tsconfig: 'tsconfig.json',
186+
isolatedModules: true,
187+
},
188+
],
190189
},
191190

192191
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation

src/app.middleware.ts

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,28 @@ import helmet from 'helmet';
55
import passport from 'passport';
66

77
export function middleware(app: INestApplication): INestApplication {
8-
const isProduction = (process.env.NODE_ENV === 'production');
8+
const isProduction = process.env.NODE_ENV === 'production';
99

1010
app.use(compression());
11-
app.use(session({
12-
// Requires 'store' setup for production
13-
secret: 'tEsTeD',
14-
resave: false,
15-
saveUninitialized: true,
16-
cookie: { secure: isProduction },
17-
}));
11+
app.use(
12+
session({
13+
// Requires 'store' setup for production
14+
secret: 'tEsTeD',
15+
resave: false,
16+
saveUninitialized: true,
17+
cookie: { secure: isProduction },
18+
}),
19+
);
1820
app.use(passport.initialize());
1921
app.use(passport.session());
2022
// https://github.com/graphql/graphql-playground/issues/1283#issuecomment-703631091
2123
// https://github.com/graphql/graphql-playground/issues/1283#issuecomment-1012913186
22-
app.use(helmet({
23-
contentSecurityPolicy: isProduction ? undefined : false,
24-
crossOriginEmbedderPolicy: isProduction ? undefined : false,
25-
}));
24+
app.use(
25+
helmet({
26+
contentSecurityPolicy: isProduction ? undefined : false,
27+
crossOriginEmbedderPolicy: isProduction ? undefined : false,
28+
}),
29+
);
2630
// app.enableCors();
2731

2832
return app;

src/app.module.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,16 @@ import { SampleModule } from './sample';
4848
DebugSampleModule,
4949
// Module Router
5050
// https://docs.nestjs.com/recipes/router-module
51-
RouterModule.register([{
52-
path: 'test',
53-
module: SampleModule,
54-
}, {
55-
path: 'test',
56-
module: DebugSampleModule,
57-
}]),
51+
RouterModule.register([
52+
{
53+
path: 'test',
54+
module: SampleModule,
55+
},
56+
{
57+
path: 'test',
58+
module: DebugSampleModule,
59+
},
60+
]),
5861
],
5962
providers: [
6063
// Global Guard, Authentication check on all routers

src/app.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { AppModule } from './app.module';
1212
* https://github.com/nestjs/nest/issues/2249#issuecomment-494734673
1313
*/
1414
async function bootstrap(): Promise<string> {
15-
const isProduction = (process.env.NODE_ENV === 'production');
15+
const isProduction = process.env.NODE_ENV === 'production';
1616
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
1717
bufferLogs: true,
1818
});
@@ -33,7 +33,7 @@ async function bootstrap(): Promise<string> {
3333
return app.getUrl();
3434
}
3535

36-
(async (): Promise<void> => {
36+
void (async (): Promise<void> => {
3737
try {
3838
const url = await bootstrap();
3939
NestLogger.log(url, 'Bootstrap');

src/auth/auth.service.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ export class AuthService {
2929
return false;
3030
}
3131

32-
const payload = <{ sub: string }> this.jwt.decode(refreshToken);
33-
return (payload.sub === data.userId);
32+
const payload = <{ sub: string }>this.jwt.decode(refreshToken);
33+
return payload.sub === data.userId;
3434
}
3535

3636
public jwtSign(data: Payload): JwtSign {
@@ -42,23 +42,27 @@ export class AuthService {
4242
};
4343
}
4444

45-
public getPayload(token: string): Payload | void {
45+
public getPayload(token: string): Payload | null {
4646
try {
47-
const payload = <JwtPayload | null> this.jwt.decode(token);
47+
const payload = <JwtPayload | null>this.jwt.decode(token);
4848
if (!payload) {
49-
return;
49+
return null;
5050
}
5151

5252
return { userId: payload.sub, username: payload.username, roles: payload.roles };
5353
} catch {
5454
// Unexpected token i in JSON at position XX
55+
return null;
5556
}
5657
}
5758

5859
private getRefreshToken(sub: string): string {
59-
return this.jwt.sign({ sub }, {
60-
secret: this.config.get('jwtRefreshSecret'),
61-
expiresIn: '7d', // Set greater than the expiresIn of the access_token
62-
});
60+
return this.jwt.sign(
61+
{ sub },
62+
{
63+
secret: this.config.get('jwtRefreshSecret'),
64+
expiresIn: '7d', // Set greater than the expiresIn of the access_token
65+
},
66+
);
6367
}
6468
}

src/auth/guards/authenticated.guard.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ export class AuthenticatedGuard implements CanActivate {
2020

2121
public getRequest(context: ExecutionContext): Request {
2222
if (context.getType<GqlContextType>() === 'graphql') {
23-
const ctx = GqlExecutionContext.create(context).getContext();
24-
return <Request>ctx.req;
23+
const ctx = GqlExecutionContext.create(context).getContext<{ req: Request }>();
24+
return ctx.req;
2525
}
2626

2727
return context.switchToHttp().getRequest<Request>();

src/auth/guards/jwt-auth.guard.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
88
// @ts-expect-error: is not assignable to type '<T = any>(context: ExecutionContext) => T'
99
public override getRequest(context: ExecutionContext): Request {
1010
if (context.getType<GqlContextType>() === 'graphql') {
11-
const ctx = GqlExecutionContext.create(context).getContext();
12-
return <Request>ctx.req;
11+
const ctx = GqlExecutionContext.create(context).getContext<{ req: Request }>();
12+
return ctx.req;
1313
}
1414

1515
return context.switchToHttp().getRequest<Request>();

src/auth/guards/jwt-verify.guard.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ export class JwtVerifyGuard extends AuthGuard('jwt-verify') {
88
// @ts-expect-error: is not assignable to type '<T = any>(context: ExecutionContext) => T'
99
public override getRequest(context: ExecutionContext): Request {
1010
if (context.getType<GqlContextType>() === 'graphql') {
11-
const ctx = GqlExecutionContext.create(context).getContext();
12-
return <Request>ctx.req;
11+
const ctx = GqlExecutionContext.create(context).getContext<{ req: Request }>();
12+
return ctx.req;
1313
}
1414

1515
return context.switchToHttp().getRequest<Request>();

src/auth/guards/local-login.guard.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { Request } from 'express';
55
@Injectable()
66
export class LocalLoginGuard extends AuthGuard('local') implements CanActivate {
77
public override async canActivate(context: ExecutionContext): Promise<boolean> {
8-
const result = <boolean> await super.canActivate(context);
8+
const result = <boolean>await super.canActivate(context);
99
const request = context.switchToHttp().getRequest<Request>();
1010
await super.logIn(request);
1111

src/auth/strategies/jwt-verify.strategy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export class JwtVerifyStrategy extends PassportStrategy(Strategy, 'jwt-verify')
1111
super({
1212
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
1313
ignoreExpiration: true, // Expiration of the access_token is not checked when processing the refresh_token.
14-
secretOrKey: config.get('jwtSecret'),
14+
secretOrKey: config.get<string>('jwtSecret'),
1515
});
1616
}
1717

0 commit comments

Comments
 (0)