Skip to content

Commit

Permalink
fix: sonar lint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
rubiin committed Oct 16, 2023
1 parent a687957 commit 6d2b423
Show file tree
Hide file tree
Showing 49 changed files with 198 additions and 214 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"rabbitmq",
"Requote",
"rubiin",
"sonarjs",
"SSSZ",
"UNAUTHORISED"
]
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,15 @@ More docs found at `docs` folder

Also if you are into NestJS ecosystem you may be interested in one of my other libs:

[nestjs-easyconfig](https://github.com/rubiin/nestjs-pino)

[helper-fns](https://github.com/rubiin/helper-fns)

[![GitHub stars](https://img.shields.io/github/stars/rubiin/helper-fns?style=flat-square)](https://github.com/rubiin/helper-fns)
[![npm](https://img.shields.io/npm/dm/helper-fns?style=flat-square)](https://www.npmjs.com/package/helper-fns)

A collection of helper functions for typescrip development. It includes functions for array,object,string,etc

[nestjs-easyconfig](https://github.com/rubiin/nestjs-easyconfig)

[![GitHub stars](https://img.shields.io/github/stars/rubiin/nestjs-easyconfig?style=flat-square)](https://github.com/rubiin/nestjs-easyconfig)
[![npm](https://img.shields.io/npm/dm/nestjs-easyconfig?style=flat-square)](https://www.npmjs.com/package/nestjs-easyconfig)
Expand All @@ -251,7 +259,7 @@ This is a cloudinary module for Nest.

---

[nestjs-pgpromise](https://github.com/segmentstream/nestjs-injectable)
[nestjs-pgpromise](https://github.com/rubiin/nestjs-pgpromise)

[![GitHub stars](https://img.shields.io/github/stars/rubiin/nestjs-pgpromise?style=flat-square)](https://github.com/rubiin/nestjs-pgpromise)
[![npm](https://img.shields.io/npm/dm/nestjs-pgpromise?style=flat-square)](https://www.npmjs.com/package/nestjs-pgpromise)
Expand Down
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module.exports = rubiin({
"ts/no-unsafe-assignment": "off", // optimize this
"ts/no-unsafe-member-access": "off", // optimize this
"unicorn/prefer-top-level-await": "off",
"sonarjs/no-duplicate-string": ["error", { "threshold": 10 }],
"ts/no-misused-promises": [
"error",
{
Expand Down
17 changes: 9 additions & 8 deletions src/_mocks_/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable ts/no-unsafe-return */
import path from "node:path";
import type { Request, Response } from "express";
import type { AmqpConnection } from "@golevelup/nestjs-rabbitmq";
Expand Down Expand Up @@ -99,21 +98,23 @@ export const refreshToken = new RefreshToken({
export const protocol = new Protocol(mockedProtocol);

export const mockEm = createMock<EntityManager>();

const payload = {
xss: "<option><iframe></select><b><script>alert(1)</script>",
test: "test",
};
export const mockRequest = createMock<Request>({
query: {
test: "test",
clearCache: "true",
xss: "<option><iframe></select><b><script>alert(1)</script>",
...payload,
},
params: {
test: "test",
xss: "<option><iframe></select><b><script>alert(1)</script>",
...payload,
},

body: {
test: "test",
xss: "<option><iframe></select><b><script>alert(1)</script>",
password: "<option><iframe></select><b><script>alert(1)</script>",
...payload,
password: payload.xss,
},
});
export const mockResponse = createMock<Response>();
Expand Down
4 changes: 1 addition & 3 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ import { SharedModule } from "@modules/shared/shared.module";
import { AppController } from "app.controller";
import { SWAGGER_API_ENDPOINT } from "@common/constant";


const stripeWebhookPath = "stripe/webhook";
const excludedPaths = [stripeWebhookPath, SWAGGER_API_ENDPOINT];


@Module({
controllers: [AppController],
imports: [SharedModule, NestCacheModule],
Expand Down Expand Up @@ -47,7 +45,7 @@ export class AppModule implements NestModule {
consumer
.apply(RealIpMiddleware, ClearCacheMiddleware)
.exclude(
...excludedPaths.map((path) => ({
...excludedPaths.map(path => ({
path,
method: RequestMethod.ALL,
})),
Expand Down
15 changes: 8 additions & 7 deletions src/common/database/base.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
getOppositeOrder,
getQueryOrder,
} from "@common/@types";
import { translate } from "@lib/i18n";
import { itemDoesNotExistKey, translate } from "@lib/i18n";
import type { BaseEntity } from "./base.entity";

export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
Expand Down Expand Up @@ -117,7 +117,7 @@ export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
return throwError(
() =>
new NotFoundException(
translate("exception.itemDoesNotExist", {
translate(itemDoesNotExistKey, {
args: { item: this.getEntityName() },
}),
),
Expand All @@ -142,7 +142,7 @@ export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
return throwError(
() =>
new NotFoundException(
translate("exception.itemDoesNotExist", {
translate(itemDoesNotExistKey, {
args: { item: this.getEntityName() },
}),
),
Expand All @@ -167,7 +167,7 @@ export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
return throwError(
() =>
new NotFoundException(
translate("exception.itemDoesNotExist", {
translate(itemDoesNotExistKey, {
args: { item: this.getEntityName() },
}),
),
Expand Down Expand Up @@ -485,12 +485,13 @@ export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
const oppositeOrder = getOppositeOrder(order);
const countWhere = where;

//@ts-expect-error
// @ts-expect-error - because of runtime issues
// eslint-disable-next-line ts/dot-notation
countWhere["$and"] = this.getFilters("createdAt", decoded, oppositeOrder);
previousCount = await repo.count(countWhere);

//@ts-expect-error
where["$and"] = this.getFilters("createdAt", decoded, queryOrder);
// @ts-expect-error - because of runtime issues
where["$and "] = this.getFilters("createdAt", decoded, queryOrder);
}

const [entities, count] = await repo.findAndCount(where, {
Expand Down
2 changes: 1 addition & 1 deletion src/common/database/mikro-orm.encrypted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export class EncryptedType extends Type {
private readonly encKey = process.env.ENC_KEY;
private readonly encIV = process.env.ENC_IV;

convertToDatabaseValue(value: string , _platform: Platform): string {
convertToDatabaseValue(value: string, _platform: Platform): string {
if (value && !(typeof value.valueOf() === "string"))
throw ValidationError.invalidType(EncryptedType, value, "JS");

Expand Down
8 changes: 3 additions & 5 deletions src/common/database/user.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ export class UserSubscriber implements EventSubscriber<User> {
arguments_.entity.password = await HelperService.hashString(arguments_.entity.password);
}


async beforeUpdate(arguments_: EventArgs<User>): Promise<void> {
if (arguments_.changeSet?.payload?.password)
arguments_.entity.password = await HelperService.hashString(arguments_.entity.password);
}

if (arguments_.changeSet?.payload?.password)
arguments_.entity.password = await HelperService.hashString(arguments_.entity.password);
}
}
2 changes: 1 addition & 1 deletion src/common/decorators/api-file.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interface ApiFilesOptions extends ApiFileOptions {
* @returns A function that returns a decorator.
*/
export function ApiFile(options_?: ApiFileOptions) {
const options = { fieldName: "file", required: false, ...options_ } satisfies ApiFilesOptions
const options = { fieldName: "file", required: false, ...options_ } satisfies ApiFilesOptions;

return applyDecorators(
UseInterceptors(FileInterceptor(options.fieldName, options.localOptions)),
Expand Down
4 changes: 2 additions & 2 deletions src/common/decorators/swagger-api.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export function SwaggerResponse({
notFound,
badRequest,
params,
//@ts-ignore
// @ts-expect-error - This is intentional
body,
//@ts-ignore
// @ts-expect-error - This is intentional
response,
}: SwaggerResponseOptions<typeof body, typeof response>) {
const decsToApply = [ApiOperation({ summary: operation })];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe("isAfter", () => {
it("if endDate is after than startDate then it should succeed", async () => {
const model = new MyClass();

model.startDate = new Date("2022-02-21");
model.startDate = new Date("2022-02-22");
model.endDate = new Date("2022-05-01");

const errors = await validator.validate(model);
Expand Down
2 changes: 1 addition & 1 deletion src/common/decorators/validation/is-after.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { isAfter } from "date-fns";
class IsAfterConstraint implements ValidatorConstraintInterface {
async validate(value: string, arguments_: ValidationArguments) {
const [relatedPropertyName] = arguments_.constraints;
const relatedValue = (arguments_.object as Record<string,string | Date>)[relatedPropertyName] as string | Date;
const relatedValue = (arguments_.object as Record<string, string | Date>)[relatedPropertyName] as string | Date;

return isAfter(new Date(value), new Date(relatedValue));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function IsDateField(options_?: DateFieldOptions) {
arrayMaxSize: Number.MAX_SAFE_INTEGER,
...options_,
} satisfies DateFieldOptions;

const decoratorsToApply = [
IsDateString(
{ strict: true },
Expand Down
2 changes: 1 addition & 1 deletion src/common/decorators/validation/is-equal-to.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
class IsEqualToConstraint implements ValidatorConstraintInterface {
async validate(value: string, arguments_: ValidationArguments) {
const [relatedPropertyName] = arguments_.constraints;
const relatedValue = (arguments_.object as Record<string,any>)[relatedPropertyName]
const relatedValue = (arguments_.object as Record<string, any>)[relatedPropertyName];

return value === relatedValue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
class IsGreaterThanConstraint implements ValidatorConstraintInterface {
async validate(value: string, arguments_: ValidationArguments) {
const [relatedPropertyName] = arguments_.constraints;
const relatedValue = (arguments_.object as Record<string,string>)[relatedPropertyName] as string;
const relatedValue = (arguments_.object as Record<string, string>)[relatedPropertyName] as string;

return Number.parseFloat(value) > Number.parseFloat(relatedValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function IsNumberField(options_?: NumberFieldOptions) {
positive: true,
...options_,
} satisfies NumberFieldOptions;

const decoratorsToApply = [
Type(() => Number),
Min(options.min, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function IsStringField(options_?: StringFieldOptions) {
arrayMaxSize: Number.MAX_SAFE_INTEGER,
...options_,
} satisfies StringFieldOptions;

const decoratorsToApply = [
IsString({
message: validationI18nMessage("validation.isDataType", {
Expand Down
2 changes: 1 addition & 1 deletion src/common/decorators/validation/is-uuid.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function IsUUIDField(options_?: UUIDFieldOptions) {
required: true,
...options_,
} satisfies UUIDFieldOptions;

const decoratorsToApply = [
IsUUID("4", {
message: validationI18nMessage("validation.isDataType", {
Expand Down
12 changes: 6 additions & 6 deletions src/common/dtos/pagination.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@ export abstract class PaginationDto {

@IsOptional()
@IsDateField()
from?: Date;
from?: Date;

/**
* From date filter
*/

@IsOptional()
@IsDateField()
to?: Date;
to?: Date;

/**
* The search query
*/
@IsStringField({ required: false, minLength: 1, maxLength: 100 })
search?: string;
search?: string;

/**
* The `withDeleted` property is a boolean flag that
Expand All @@ -37,21 +37,21 @@ export abstract class PaginationDto {
type: "boolean",
}),
})
withDeleted = false;
withDeleted = false;

/**
* The `relations` property is used to specify which related
* entities should be included in the query
* results.
*/
@IsStringField({ required: false, each: true })
relations = [];
relations: string[] = [];

/**
* The `fields` property is used to specify which
* entities field should be included in the query
* results.
*/
@IsStringField({ required: false, each: true })
fields = [];
fields: string[] = [];
}
6 changes: 3 additions & 3 deletions src/common/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ export class AuthGuard implements CanActivate {
throw new UnauthorizedException(translate("exception.apiUnauthorizedResponse"));

try {
const tokenValue = token.split(" ")[1]
const tokenValue = token.split(" ")[1];

if(!tokenValue){
if (!tokenValue)
return false;
}

const decoded: { idx: string } = this.jwt.verify(tokenValue);

request.idx = decoded.idx;
Expand Down
10 changes: 4 additions & 6 deletions src/common/guards/throttle.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ export class CustomThrottlerGuard extends ThrottlerGuard {
protected errorMessage = THROTTLE_LIMIT_RESPONSE;

protected async getTracker(request: Request): Promise<string> {
if (request.ips.length > 0 && request.ips[0]) {
if (request.ips.length > 0 && request.ips[0])
return request.ips[0];
} else if (request.ip) {
else if (request.ip)
return request.ip;
}
throw new Error("Unable to get IP address");

}

throw new Error("Unable to get IP address");
}
}
3 changes: 1 addition & 2 deletions src/common/helpers/helpers.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ which is the hashed password to compare against. */
return new Date(format(currentUtcTime, "yyyy-MM-dd HH:mm:ss"));
},


//TODO: fix this
// TODO: fix this
// redisUrlToOptions(url: string): RedisOptions {
// if(!REDIS_URI_REGEX.test(url)){
// throw new Error("Invalid redis url");
Expand Down
1 change: 1 addition & 0 deletions src/common/misc/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const ImageMulterOption: MulterOptions = {
if (!FileType.IMAGE.test(file.mimetype))
return callback(new Error(MULTER_IMAGE_FILTER), false);

// eslint-disable-next-line unicorn/no-null
return callback(null, true);
},
};
Expand Down
13 changes: 5 additions & 8 deletions src/common/misc/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@ import { ThreadFunctions } from "@common/@types";

// all expensive process goes here to avoid blocking the main thread
function workerFunction(data: { functionName: string; input: string }) {
switch (data.functionName) {
case ThreadFunctions.HASH_STRING: {
return HelperService.hashString(data.input);
}
if (data.functionName === ThreadFunctions.HASH_STRING)
return HelperService.hashString(data.input);

default: {
throw new Error(`Invalid thread function name, available are ${Object.keys(ThreadFunctions).join(" ,")}`);
}
}
throw new Error(`Invalid thread function name, available are ${Object.keys(ThreadFunctions).join(" ,")}`);
}

const threadWorker = new ThreadWorker(workerFunction as any);

export default threadWorker;

// TODO: fix this
Loading

0 comments on commit 6d2b423

Please sign in to comment.