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 5d80fb0
Show file tree
Hide file tree
Showing 39 changed files with 112 additions and 73 deletions.
6 changes: 3 additions & 3 deletions src/common/@types/classes/common.response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ export class AuthenticationResponse {
/**
* @example fb9eac5f-eb94-489b-8fca-24324558be18
*/
user: {
idx?: string
user!: {
idx: string
};

/**
* @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;
}
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
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 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
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
2 changes: 1 addition & 1 deletion src/entities/message.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class Message extends BaseEntity {
eager: false,
index: true,
})
sender: Rel<Ref<Post>>;
sender!: Rel<Ref<Post>>;

@ManyToOne({
eager: false,
Expand Down
2 changes: 1 addition & 1 deletion src/entities/news-letter.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BaseEntity } from "@common/database";
@Entity()
export class NewsLetter extends BaseEntity {
@Property({ index: true, unique: true })
name: string;
name!: string;

@Property({ columnType: "text" })
content!: string;
Expand Down
2 changes: 1 addition & 1 deletion src/entities/otp-log.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class OtpLog extends BaseEntity {
eager: false,
index: true,
})
user: Rel<Ref<User>>;
user!: Rel<Ref<User>>;

@Property()
isUsed? = false;
Expand Down
2 changes: 1 addition & 1 deletion src/entities/refresh-token.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class RefreshToken extends BaseEntity {
@ManyToOne({
eager: false,
})
user: Rel<Ref<User>>;
user!: Rel<Ref<User>>;

@Property()
isRevoked? = false;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/casl/casl-ability.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class CaslAbilityFactory {

/* Giving the user the ability to read and write to everything if they are an admin. */

if (user.roles.includes(Roles.ADMIN))
if (user.roles!.includes(Roles.ADMIN))
can(Action.Manage, "all"); // read-write access to everything
else
can(Action.Read, "all"); // read-only access to everything
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/firebase-admin/firebase.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ interface NestFirebase {

@Injectable()
export class NestFirebaseService implements NestFirebase {
private _firebaseConnection: admin.app.App;
private _firebaseConnection!: admin.app.App;

constructor(
@Inject(MODULE_OPTIONS_TOKEN) private _NestFirebaseOptions: FirebaseModuleOptions,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/minio.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { NestMinioModule } from "nestjs-minio";
inject: [ConfigService],
isGlobal: true,
useFactory: async (configService: ConfigService) => ({
endPoint: configService.get("minio.host"),
endPoint: configService.get("minio.host")!,
port: configService.get("minio.port"),
accessKey: configService.get("minio.accessKey"),
secretKey: configService.get("minio.secretKey"),
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ async function bootstrap() {
module.hot.dispose(() => app.close());
}

const port = process.env.PORT ?? configService.get("app.port", { infer: true });
const port = process.env.PORT ?? configService.get("app.port", { infer: true })!;

await app.listen(port);

Expand Down
2 changes: 1 addition & 1 deletion src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,6 @@ export class AuthController {
): Observable<User> {
return fromAll
? this.authService.logoutFromAll(user)
: this.authService.logout(user, refreshToken.refreshToken);
: this.authService.logout(user, refreshToken!.refreshToken);
}
}
37 changes: 34 additions & 3 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
ForbiddenException,
Injectable,
NotFoundException,
UnauthorizedException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { init } from "@paralleldrive/cuid2";
Expand Down Expand Up @@ -79,7 +80,7 @@ export class AuthService {
}

return user && isPasswordLogin
? HelperService.verifyHash(user.password, pass).pipe(
? HelperService.verifyHash(user.password, pass!).pipe(
map((isValid) => {
if (isValid)
return omit(user, ["password"]);
Expand Down Expand Up @@ -198,7 +199,7 @@ export class AuthService {
const otp = this.otpRepository.create({
user: userExists,
otpCode: otpNumber,
expiresIn: new Date(Date.now() + (protocol.otpExpiryInMinutes * 60_000)), // prettier-ignore
expiresIn: new Date(Date.now() + (protocol?.otpExpiryInMinutes ?? 5 * 60_000)), // prettier-ignore
});

return from(
Expand Down Expand Up @@ -245,6 +246,19 @@ export class AuthService {
),
).pipe(
switchMap((details) => {

if(!details) {

return throwError(
() =>
new NotFoundException(
translate("exception.itemDoesNotExist", {
args: { item: "Otp" },
}),
),
);
}

const user = details.user.getEntity();
this.userRepository.assign(user, { password });

Expand Down Expand Up @@ -332,6 +346,19 @@ export class AuthService {
}),
).pipe(
switchMap((userDetails) => {

if(!userDetails) {

return throwError(
() =>
new NotFoundException(
translate("exception.itemDoesNotExist", {
args: { item: "Account" },
}),
),
);
}

return HelperService.verifyHash(userDetails.password, oldPassword).pipe(
switchMap((isValid) => {
if (!isValid) {
Expand All @@ -354,6 +381,10 @@ export class AuthService {
}

async findUser(condition: FilterQuery<User>): Promise<User> {
return this.userRepository.findOne(condition);
const user = await this.userRepository.findOne(condition);

if (!user)
throw new UnauthorizedException();
return user
}
}
6 changes: 3 additions & 3 deletions src/modules/auth/strategies/facebook.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ export class FacebookStrategy extends PassportStrategy(Strategy, "facebook") {
): Promise<any> {
const { name, emails, username, photos } = profile;
const user: OauthResponse = {
email: emails[0].value,
email: emails![0]!.value,
firstName: name?.givenName,
lastName: name?.familyName,
accessToken,
};
// Check if the user already exists in your database
const existingUser = await this.userRepo.findOne({
email: emails[0].value,
email: emails![0]!.value,
isDeleted: false,
});

Expand All @@ -62,7 +62,7 @@ export class FacebookStrategy extends PassportStrategy(Strategy, "facebook") {
// If the user doesn't exist, create a new user
const newUser = this.userRepo.create({
...omit(user, ["accessToken"]),
avatar: photos[0].value,
avatar: photos?.[0]?.value ?? '',
username,
password: randomString({ length: 10, symbols: true, numbers: true }),
});
Expand Down
Loading

0 comments on commit 5d80fb0

Please sign in to comment.