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 5d80fb0 commit c7484e5
Show file tree
Hide file tree
Showing 26 changed files with 100 additions and 56 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.

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

/**
Expand Down
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
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
Original file line number Diff line number Diff line change
Expand Up @@ -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
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;
4 changes: 2 additions & 2 deletions src/entities/post.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class Post extends BaseEntity {
eager: false,
index: true,
})
author: Rel<Ref<User>>;
author!: Rel<Ref<User>>;

@OneToMany(() => Comment, comment => comment.post, {
eager: false,
Expand Down Expand Up @@ -84,7 +84,7 @@ export class Post extends BaseEntity {

getReadingTime(content: string) {
const avgWordsPerMin = 250;
const count = content.match(/\w+/g).length;
const count = content.match(/\w+/g)?.length ?? 0;

return Math.ceil(count / avgWordsPerMin);
}
Expand Down
4 changes: 2 additions & 2 deletions src/entities/referral.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export class Referral extends BaseEntity {
@ManyToOne({
index: true,
})
referrer: Rel<Ref<User>>;
referrer!: Rel<Ref<User>>;

@Property({
index: true,
})
mobileNumber: string;
mobileNumber!: string;

@Index()
@Enum(() => ReferralStatus)
Expand Down
11 changes: 7 additions & 4 deletions src/lib/aws/aws.s3.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ export class AwsS3Service {
Prefix: prefix,
}),
)).pipe(map((listItems) => {
if(!listItems.Contents) return [];


const mapList = listItems.Contents.map((value) => {
const lastIndex = value.Key.lastIndexOf("/");
const path = value.Key.slice(0, lastIndex);
Expand Down Expand Up @@ -159,8 +162,8 @@ export class AwsS3Service {
content: Uint8Array | Buffer,
options?: AwsS3PutItemOptions,
): Observable<AwsS3> {
const filename = options.keepOriginalName ? originalFilename : this.generateFileName(originalFilename);
const { key, mime, path } = this.getOptions(options, filename);
const filename = options?.keepOriginalName ? originalFilename : this.generateFileName(originalFilename);
const { key, mime, path } = this.getOptions(filename,options);
return from(this.s3Client.send(
new PutObjectCommand({
Bucket: this.bucket,
Expand Down Expand Up @@ -274,7 +277,7 @@ export class AwsS3Service {
filename: string,
options?: AwsS3PutItemOptions,
): Observable<AwsS3MultiPart> {
const { key, mime, path, acl } = this.getOptions(options, filename);
const { key, mime, path, acl } = this.getOptions(filename,options );

return from(this.s3Client.send(
new CreateMultipartUploadCommand({
Expand Down Expand Up @@ -303,7 +306,7 @@ export class AwsS3Service {
* file.
* @returns An object with the properties `key`, `mime`, `path`, and `acl`.
*/
private getOptions(options: AwsS3PutItemOptions, filename: string) {
private getOptions( filename: string,options?: AwsS3PutItemOptions) {
let path = options?.path ?? undefined;
const acl = options?.acl ?? "public-read";

Expand Down
2 changes: 1 addition & 1 deletion src/lib/config/configs/minio.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const minioConfigValidationSchema = {

export const minio = registerAs("minio", () => ({
host: process.env.MINIO_HOST,
port: Number.parseInt(process.env.?MINIO_PORT, 10),
port: Number.parseInt(process.env.MINIO_PORT, 10),
accessKey: process.env.MINIO_ACCESS_KEY,
secretKey: process.env.MINIO_SECRET_KEY,
useSSl: process.env.MINIO_USE_SSL === "true",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/crud/crud.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function ControllerFactory<
C extends RequiredEntityData<T>,
U extends EntityData<T>,
> implements Crud<T, Q, C, U> {
protected service: BaseService<T, Q, C, U>;
protected service!: BaseService<T, Q, C, U>;

@Get(":idx")
@SwaggerResponse({
Expand Down
4 changes: 2 additions & 2 deletions src/lib/crud/crud.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export abstract class BaseService<
CreateDto extends RequiredEntityData<Entity> = RequiredEntityData<Entity>,
UpdateDto extends EntityData<Entity> = EntityData<Entity>,
> implements Crud<Entity, PRequest> {
protected searchField: keyof Entity;
protected searchField!: keyof Entity;
protected queryName = "entity";

protected constructor(private readonly repository: BaseRepository<Entity>) {}
Expand Down Expand Up @@ -65,11 +65,11 @@ export abstract class BaseService<

return this.repository.qbOffsetPagination({
pageOptionsDto: {
...dto,
alias: this.queryName,
order: QueryOrder.ASC,
offset: dto.offset,
searchField: this.searchField,
...dto,
},
qb,
});
Expand Down
9 changes: 8 additions & 1 deletion src/lib/i18n/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import type { Path, TranslateOptions } from "nestjs-i18n";
import { I18nContext, i18nValidationMessage } from "nestjs-i18n";

export function translate(key: Path<I18nTranslations>, options: TranslateOptions = {}) {
return I18nContext.current<I18nTranslations>().t(key, options);
const i18nContext = I18nContext.current<I18nTranslations>();

if (i18nContext) {
return i18nContext.t(key, options);
}

// Handle the case when i18nContext is undefined
return ''; // or throw an error, return a default value, etc.
}

export function validationI18nMessage(key: Path<I18nTranslations>, arguments_?: any) {
Expand Down
12 changes: 6 additions & 6 deletions src/lib/minio.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import { NestMinioModule } from "nestjs-minio";
imports: [ConfigModule],
inject: [ConfigService],
isGlobal: true,
useFactory: async (configService: ConfigService) => ({
endPoint: configService.get("minio.host")!,
port: configService.get("minio.port"),
accessKey: configService.get("minio.accessKey"),
secretKey: configService.get("minio.secretKey"),
useSSL: configService.get("minio.ssl"),
useFactory: async (configService: ConfigService<Configs, true>) => ({
endPoint: configService.get("minio.host",{ infer: true }),
port: configService.get("minio.port",{ infer: true }),
accessKey: configService.get("minio.accessKey",{ infer: true }),
secretKey: configService.get("minio.secretKey",{ infer: true }),
useSSL: configService.get("minio.ssl",{ infer: true }),
}),
}),
],
Expand Down
Loading

0 comments on commit c7484e5

Please sign in to comment.