Skip to content

Commit

Permalink
fix: ts strict
Browse files Browse the repository at this point in the history
  • Loading branch information
rubiin committed Oct 12, 2023
1 parent 422e40f commit 243a208
Show file tree
Hide file tree
Showing 58 changed files with 227 additions and 129 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
"firebase-admin": "^11.11.0",
"handlebars": "^4.7.8",
"helmet": "^7.0.0",
"helper-fns": "^2.6.27",
"helper-fns": "^2.6.28",
"ioredis": "^5.3.2",
"isomorphic-dompurify": "^1.9.0",
"joi": "^17.11.0",
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions src/common/@types/classes/common.response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ export class AuthenticationResponse {
/**
* @example fb9eac5f-eb94-489b-8fca-24324558be18
*/
user: {
user!: {
idx?: string
id: number
};

/**
* @example eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXKYjj.eyJ
*/
accessToken: string;
accessToken!: string;

/**
* @example eyJh3d06e6e3e152ae839a6623c3cb6f961a.eyJ
Expand Down
10 changes: 5 additions & 5 deletions src/common/@types/classes/cursor.response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ export class CursorMeta {
* @example AdVxY2F0ZWdvcnlfaWQ9MjMx
*/
@ApiProperty()
nextCursor: string;
nextCursor!: string;

/**
* @example false
*/
@ApiProperty()
hasNextPage: boolean;
hasNextPage!: boolean;

/**
* @example true
*/
@ApiProperty()
hasPreviousPage: boolean;
hasPreviousPage!: boolean;

/**
* @example "lorem ipsum"
Expand All @@ -31,8 +31,8 @@ export class CursorMeta {
export class CursorPaginationResponse<T> implements PaginationAbstractResponse<T, CursorMeta> {
@IsArray()
@ApiProperty({ isArray: true })
readonly data: T[];
readonly data!: T[];

@ApiProperty({ type: () => CursorMeta })
readonly meta: CursorMeta;
readonly meta!: CursorMeta;
}
1 change: 1 addition & 0 deletions src/common/@types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ declare global {
JWT_ACCESS_EXPIRY: string
JWT_REFRESH_EXPIRY: string
JWT_SECRET: string
MAGIC_LINK_EXPIRY: string

MAIL_HOST: string
MAIL_PASSWORD: string
Expand Down
4 changes: 2 additions & 2 deletions src/common/@types/interfaces/authentication.interface.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface OauthResponse {
email: string
firstName?: string
lastName?: string
firstName: string
lastName: string
accessToken: string
}

Expand Down
2 changes: 1 addition & 1 deletion src/common/@types/interfaces/mail.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { EmailTemplate } from "../enums";

export interface MailPayload {
template: string
replacements?: Record<string, string>
replacements: Record<string, string>
to: string
subject: string
from: string
Expand Down
2 changes: 1 addition & 1 deletion src/common/constant/string.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const packageJson = readPackageSync();

export const APP_NAME = packageJson.name;
export const SWAGGER_API_CURRENT_VERSION = packageJson.version;
export const SWAGGER_DESCRIPTION = packageJson.description;
export const SWAGGER_DESCRIPTION = packageJson.description!;
export const SWAGGER_TITLE = `${capitalize(APP_NAME)} API Documentation`;

export const SWAGGER_API_ENDPOINT = "doc";
Expand Down
2 changes: 1 addition & 1 deletion src/common/database/base.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ export class BaseRepository<T extends BaseEntity> extends EntityRepository<T> {
countWhere["$and"] = this.getFilters("createdAt", decoded, oppositeOrder);
previousCount = await repo.count(countWhere);

// eslint-disable-next-line ts/dot-notation
// eslint-disable-next-line ts/dot-notation\
where["$and"] = this.getFilters("createdAt", decoded, queryOrder);
}

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 | undefined, _platform: Platform): string {
convertToDatabaseValue(value: string , _platform: Platform): string {
if (value && !(typeof value.valueOf() === "string"))
throw ValidationError.invalidType(EncryptedType, value, "JS");

Expand Down
10 changes: 6 additions & 4 deletions src/common/database/user.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ export class UserSubscriber implements EventSubscriber<User> {
}

async beforeCreate(arguments_: EventArgs<User>): Promise<void> {
if (arguments_.changeSet.payload?.password)
if (arguments_.changeSet?.payload?.password)
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);
}

}
6 changes: 3 additions & 3 deletions 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: ApiFileOptions = { fieldName: "file", required: false, ...options_ };
const options = { fieldName: "file", required: false, ...options_ } satisfies ApiFilesOptions

return applyDecorators(
UseInterceptors(FileInterceptor(options.fieldName, options.localOptions)),
Expand All @@ -54,12 +54,12 @@ export function ApiFile(options_?: ApiFileOptions) {
* @returns A function that returns a decorator.
*/
export function ApiFiles(options_?: ApiFilesOptions) {
const options: ApiFilesOptions = {
const options = {
fieldName: "files",
required: false,
maxCount: 10,
...options_,
};
} satisfies ApiFilesOptions;

return applyDecorators(
UseInterceptors(
Expand Down
4 changes: 2 additions & 2 deletions src/common/decorators/auth.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ interface AuthGuard {
*/

export function Auth(options_?: AuthGuard) {
const options: AuthGuard = {
const options = {
guards: [JwtAuthGuard, PoliciesGuard],
unauthorizedResponse: API_UNAUTHORISED_RESPONSE,
...options_,
};
} satisfies AuthGuard;

return applyDecorators(
UseGuards(...options.guards),
Expand Down
3 changes: 2 additions & 1 deletion src/common/decorators/validation/is-date-field.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export function IsDateField(options_?: DateFieldOptions) {
arrayMinSize: 0,
arrayMaxSize: Number.MAX_SAFE_INTEGER,
...options_,
};
} satisfies DateFieldOptions;

const decoratorsToApply = [
IsDateString(
{ strict: true },
Expand Down
4 changes: 2 additions & 2 deletions src/common/decorators/validation/is-date-format.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ class IsDateInFormatConstraint implements ValidatorConstraintInterface {
const [format] = arguments_.constraints as string[];

if (isArray(value))
return value.some(v => isMatch(v, format));
return value.some(v => isMatch(v, format!));

return isMatch(value, format);
return isMatch(value, format!);
}

defaultMessage(arguments_: ValidationArguments) {
Expand Down
5 changes: 3 additions & 2 deletions src/common/decorators/validation/is-number-field.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type { NumberFieldOptions } from "@common/@types";
*/

export function IsNumberField(options_?: NumberFieldOptions) {
const options: NumberFieldOptions = {
const options = {
min: 1,
required: true,
each: false,
Expand All @@ -31,7 +31,8 @@ export function IsNumberField(options_?: NumberFieldOptions) {
int: true,
positive: true,
...options_,
};
} satisfies NumberFieldOptions;

const decoratorsToApply = [
Type(() => Number),
Min(options.min, {
Expand Down
5 changes: 3 additions & 2 deletions src/common/decorators/validation/is-string-field.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Sanitize, Trim } from "./transform.decorator";
*/

export function IsStringField(options_?: StringFieldOptions) {
const options: StringFieldOptions = {
const options = {
required: true,
each: false,
sanitize: true,
Expand All @@ -31,7 +31,8 @@ export function IsStringField(options_?: StringFieldOptions) {
arrayMinSize: 0,
arrayMaxSize: Number.MAX_SAFE_INTEGER,
...options_,
};
} satisfies StringFieldOptions;

const decoratorsToApply = [
IsString({
message: validationI18nMessage("validation.isDataType", {
Expand Down
5 changes: 3 additions & 2 deletions src/common/decorators/validation/is-uuid.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import { validationI18nMessage } from "@lib/i18n";
* @returns A decorator function that takes in a target, propertyKey, and descriptor.
*/
export function IsUUIDField(options_?: UUIDFieldOptions) {
const options: UUIDFieldOptions = {
const options = {
each: false,
required: true,
...options_,
};
} satisfies UUIDFieldOptions;

const decoratorsToApply = [
IsUUID("4", {
message: validationI18nMessage("validation.isDataType", {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { validationI18nMessage } from "@lib/i18n";
* @returns A function that takes in a target, propertyKey, and descriptor
*/
export function MinMaxLength(options_?: MinMaxLengthOptions) {
const options: MinMaxLengthOptions = { minLength: 2, maxLength: 500, each: false, ...options_ };
const options = { minLength: 2, maxLength: 500, each: false, ...options_ };

return applyDecorators(
MinLength(options.minLength, {
Expand Down
2 changes: 1 addition & 1 deletion src/common/dtos/pagination.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export abstract class PaginationDto {
* The search query
*/
@IsStringField({ required: false, minLength: 1, maxLength: 100 })
search: string;
search?: string;

/**
* The `withDeleted` property is a boolean flag that
Expand Down
7 changes: 6 additions & 1 deletion src/common/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ export class AuthGuard implements CanActivate {
throw new UnauthorizedException(translate("exception.apiUnauthorizedResponse"));

try {
const decoded: { idx: string } = this.jwt.verify(token.split(" ")[1]);
const tokenValue = token.split(" ")[1]

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

request.idx = decoded.idx;

Expand Down
9 changes: 8 additions & 1 deletion src/common/guards/throttle.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ export class CustomThrottlerGuard extends ThrottlerGuard {
protected errorMessage = THROTTLE_LIMIT_RESPONSE;

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

}

}
29 changes: 20 additions & 9 deletions src/common/helpers/helpers.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { from } from "rxjs";
import sharp from "sharp";
import type { User } from "@entities";
import type { AuthenticationResponse } from "@common/@types";
import { REDIS_URI_REGEX } from "@common/constant";

const argon2Options: ArgonOptions & { raw?: false } = {
type: argon2id,
Expand Down Expand Up @@ -92,24 +93,34 @@ which is the hashed password to compare against. */
return new Date(format(currentUtcTime, "yyyy-MM-dd HH:mm:ss"));
},



redisUrlToOptions(url: string): RedisOptions {
if(!REDIS_URI_REGEX.test(url)){
throw new Error("Invalid redis url");
}

const separator = "://";

if (url.includes("://:")) {
const array = url.split("://:")[1].split("@");
const secondArray = array[1].split(":");
const [_, credentials] = url.split(separator);
const [password, rest] = credentials.split("@");
const [host, port] = rest.split(":");

return {
password: array[0],
host: secondArray[0],
port: Number.parseInt(secondArray[1], 10),
password,
host,
port: Number.parseInt(port, 10),
};
}

const connectionString = url.split("://")[1];
const array = connectionString.split(":");
const connectionString = url.split(separator)[1];
const [host, port] = connectionString.split(":");

return {
host: array[0],
port: Number.parseInt(array[1], 10),
host,
port: Number.parseInt(port, 10),
};

},
};
2 changes: 1 addition & 1 deletion src/common/middlewares/ip.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getClientIp } from "@supercharge/request-ip";
@Injectable()
export class RealIpMiddleware implements NestMiddleware {
use(request: Request, _response: Response, next: NextFunction) {
request.realIp = getClientIp(request);
request.realIp = getClientIp(request)!;
next();
}
}
2 changes: 1 addition & 1 deletion src/common/misc/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ function workerFunction(data: { functionName: string; input: string }) {
}
}

const threadWorker = new ThreadWorker(workerFunction);
const threadWorker = new ThreadWorker(workerFunction as any);

export default threadWorker;
2 changes: 1 addition & 1 deletion src/entities/conversation.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Message, User } from "./index";
@Entity()
export class Conversation extends BaseEntity {
@Property({ index: true })
chatName: string;
chatName!: string;

@ManyToMany(() => User, user => user.conversations, { index: true })
users = new Collection<User>(this);
Expand Down
Loading

0 comments on commit 243a208

Please sign in to comment.