Skip to content

Commit

Permalink
refactor: refactor and update TypeScript related issue (#26)
Browse files Browse the repository at this point in the history
* refactor: update all any type

* style: update eslint

* build: update lint task
  • Loading branch information
ckng0221 authored Jan 4, 2024
1 parent 15c3a63 commit 8b995d5
Show file tree
Hide file tree
Showing 17 changed files with 69 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ module.exports = {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
},
};
3 changes: 2 additions & 1 deletion apps/book/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import { BookController } from '../src/book.controller';
import { BookService } from '../src/book.service';
import { BookDtoStub } from '../src/dto/book.dto.stub';
import { Book, BookSchema } from '../src/schemas/book.schema';
import { ReadBookDto } from '../src/dto/book.dto';

describe('Book (e2e)', () => {
let app: INestApplication;

let mongod: MongoMemoryServer;
let mongoConnection: Connection;
let bookModel: Model<Book>;
let testBook: any;
let testBook: ReadBookDto;

beforeAll(async () => {
mongod = await MongoMemoryServer.create();
Expand Down
14 changes: 6 additions & 8 deletions apps/borrowing/src/borrowing.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {

import { EventPattern, Payload } from '@nestjs/microservices';
import { ObjectIdValidationPipe } from '../../../packages/nestlib';
import { IPaymentDone } from '../../ui/src/interfaces/payment';

@Controller('borrowings')
export class BorrowingController {
Expand Down Expand Up @@ -63,15 +64,12 @@ export class BorrowingController {
}

@EventPattern('payment_done')
async handlePaymentDone(@Payload() data: any) {
const payment = JSON.parse(data);
async handlePaymentDone(@Payload() data: string) {
const payment: IPaymentDone = JSON.parse(data);

const borrowing = await this.borrowingService.updateOne(
payment.borrowing_id,
{
is_payment_done: true,
},
);
return await this.borrowingService.updateOne(payment.borrowing_id, {
is_payment_done: true,
});
// console.log(borrowing);
}

Expand Down
3 changes: 2 additions & 1 deletion apps/borrowing/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import { BorrowingController } from '../src/borrowing.controller';
import { BorrowingService } from '../src/borrowing.service';
import { BorrowingDtoStub } from '../src/dto/borrowing.dto.stub';
import { Borrowing, BorrowingSchema } from '../src/schemas/borrowing.schema';
import { ReadBorrowingDto } from '../src/dto/borrowing.dto';

describe('Borrowing (e2e)', () => {
let app: INestApplication;

let mongod: MongoMemoryServer;
let mongoConnection: Connection;
let borrowingModel: Model<Borrowing>;
let testBorrowing: any;
let testBorrowing: ReadBorrowingDto;

beforeAll(async () => {
mongod = await MongoMemoryServer.create();
Expand Down
3 changes: 2 additions & 1 deletion apps/customer/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import { CustomerService } from '../src/customer.service';
import { Customer, CustomerSchema } from '../src/schemas/customer.schema';
import { INestApplication } from '@nestjs/common';
import { CustomerDtoStub } from '../src/dto/customer.dto.stub';
import { ReadCustomerDto } from '../src/dto/customer.dto';

describe('Customer (e2e)', () => {
let app: INestApplication;

let mongod: MongoMemoryServer;
let mongoConnection: Connection;
let customerModel: Model<Customer>;
let testCustomer: any;
let testCustomer: ReadCustomerDto;

beforeAll(async () => {
mongod = await MongoMemoryServer.create();
Expand Down
3 changes: 2 additions & 1 deletion apps/notification/src/notification.controller.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { ReadBookDto } from '../../book/src/dto/book.dto';
import { NotificationService } from './notification.service';

@Controller('notification')
export class NotificationController {
constructor(private readonly notificationService: NotificationService) {}

@EventPattern('book_added')
async handleBorrowingCreated(@Payload() data: any) {
async handleBorrowingCreated(@Payload() data: { book: ReadBookDto }) {
console.log(`Received new book. Name: ${data.book?.title}`);
return this.notificationService.sendNotification(data.book.title);
}
Expand Down
4 changes: 2 additions & 2 deletions apps/payment/src/events.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class EventGateway {
@WebSocketServer()
server: Server;

handleConnection(client: any) {
handleConnection(client) {

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 13 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used
// console.log(client);
this.server.emit('connected', {});

Expand All @@ -19,7 +19,7 @@ export class EventGateway {
// Handle connection event
}

handleDisconnect(client: any) {
handleDisconnect(client) {

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used

Check warning on line 22 in apps/payment/src/events.gateway.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'client' is defined but never used
// Handle disconnection event
this.server.emit('disconnected', {});

Expand Down
13 changes: 9 additions & 4 deletions apps/payment/src/payment.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ import {
Query,
} from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { ApiQuery } from '@nestjs/swagger';
import { ObjectIdValidationPipe } from '../../../packages/nestlib';
import { CreatePaymentDto, ReadPaymentDto } from './dto/payment.dto';
import { PaymentService } from './payment.service';
import { ApiQuery } from '@nestjs/swagger';
import { EventGateway } from './events.gateway';
import { PaymentService } from './payment.service';
import { ReadBorrowingDto } from '../../borrowing/src/dto/borrowing.dto';

@Controller('payments')
export class PaymentController {
Expand Down Expand Up @@ -87,9 +88,13 @@ export class PaymentController {
}

@EventPattern('borrowing_created')
async handleBorrowingCreated(@Payload() data: any) {
async handleBorrowingCreated(
@Payload() data: { borrowing: ReadBorrowingDto },
) {
// console.log(data);

console.log(
`Received borrowing_created. borrowing_id: ${data.borrowing?._id}`,
`Received borrowing_created. borrowing_id: ${data.borrowing._id}`,
);

const payment = await this.paymentService.create({
Expand Down
3 changes: 2 additions & 1 deletion apps/payment/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import { PaymentController } from '../src/payment.controller';
import { PaymentService } from '../src/payment.service';
import { Payment, PaymentSchema } from '../src/schemas/payment.schema';
import { EventGateway } from '../src/events.gateway';
import { ReadPaymentDto } from '../src/dto/payment.dto';

describe('Payment (e2e)', () => {
let app: INestApplication;

let mongod: MongoMemoryServer;
let mongoConnection: Connection;
let paymentModel: Model<Payment>;
let testPayment: any;
let testPayment: ReadPaymentDto;

beforeAll(async () => {
mongod = await MongoMemoryServer.create();
Expand Down
2 changes: 1 addition & 1 deletion apps/ui/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module.exports = {
'warn',
{ allowConstantExport: true },
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'off',
},
};
2 changes: 1 addition & 1 deletion apps/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "vite --port 3000",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --fix",
"preview": "vite preview"
},
"dependencies": {
Expand Down
9 changes: 9 additions & 0 deletions apps/ui/src/interfaces/borrowing.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ChipOwnProps } from '@mui/material';

export interface IBorrowingBook {
id: string;
name: string;
Expand All @@ -12,3 +14,10 @@ export interface IBorrowing {
is_payment_done?: boolean;
borrowed_date?: Date;
}

export interface IPaymentStatus<
T extends ChipOwnProps['color'] = ChipOwnProps['color'],
> {
text: string;
color: T;
}
6 changes: 6 additions & 0 deletions apps/ui/src/interfaces/payment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ export interface IPayment {
created_date?: string;
payment_date?: string;
}

export interface IPaymentDone {
payment_id: string;
borrowing_id: string;
status: 'success' | 'failed';
}
10 changes: 6 additions & 4 deletions apps/ui/src/pages/BorrowingDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
CardContent,
CardMedia,
Chip,
ChipOwnProps,
CircularProgress,
Grid,
Link,
Expand All @@ -21,8 +22,8 @@ import AlertComp from '../components/Alert';
import CopyToClipboardIcon from '../components/CopyToClipboard';
import DialogComp from '../components/Dialog';
import TableComp from '../components/Table';
import { IBorrowing } from '../interfaces/borrowing';
import { IPayment } from '../interfaces/payment';
import { IBorrowing, IPaymentStatus } from '../interfaces/borrowing';
import { IPayment, IPaymentDone } from '../interfaces/payment';
import { paymentSocket } from '../utils/socket';
import sampleBook from '/sample-book.webp';

Expand Down Expand Up @@ -59,6 +60,7 @@ function BorrowingDetails() {
const payments = await getPayments({
borrowing_id: String(borrowingId),
});

setPayment(payments.data[0]);
setIsFetchingData(false);
}
Expand All @@ -67,7 +69,7 @@ function BorrowingDetails() {
}, [borrowingId]);

useEffect(() => {
function onPaymentDone(message: any) {
function onPaymentDone(message: IPaymentDone) {
console.log('payment_done', message);
if (message.status === 'success') {
// console.log('before', borrowingRef.current);
Expand Down Expand Up @@ -97,7 +99,7 @@ function BorrowingDetails() {
const borrowingBooks = borrowing.books.map((book, index) => {
return { index: index + 1, ...book };
});
const paymentStatus: any = {
const paymentStatus: IPaymentStatus<'success' | 'warning'> = {
text: borrowing.is_payment_done || paymentDone ? 'Successful' : 'Pending',
color: borrowing.is_payment_done || paymentDone ? 'success' : 'warning',
};
Expand Down
8 changes: 4 additions & 4 deletions apps/ui/src/pages/Borrowings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ import { Link as RouterLink } from 'react-router-dom';
import { getBorrowings } from '../api/borrowing-api';
import CopyToClipboardIcon from '../components/CopyToClipboard';
import TableComp from '../components/Table';
import { IBorrowing } from '../interfaces/borrowing';
import { IBorrowing, IPaymentStatus } from '../interfaces/borrowing';
import { ICustomer } from '../interfaces/customer';
import { IPaymentDone } from '../interfaces/payment';
import { paymentSocket } from '../utils/socket';
import Footer from '../components/Footer';

const ListItems = ({ borrowings }: { borrowings: IBorrowing[] }) => {
const columns = [
Expand All @@ -37,7 +37,7 @@ const ListItems = ({ borrowings }: { borrowings: IBorrowing[] }) => {
const borrowingBooks = borrowing.books.map((book, index) => {
return { index: index + 1, ...book };
});
const paymentStatus: any = {
const paymentStatus: IPaymentStatus<'success' | 'warning'> = {
text: borrowing.is_payment_done ? 'Successful' : 'Pending',
color: borrowing.is_payment_done ? 'success' : 'warning',
};
Expand Down Expand Up @@ -127,7 +127,7 @@ function Borrowings(props: IProps) {
setIsConnected(false);
}

function onPaymentDone(message: any) {
function onPaymentDone(message: IPaymentDone) {
console.log('payment_done', message);
if (message.status === 'success') {
const objIndex = borrowingsRef.current.findIndex(
Expand Down
5 changes: 3 additions & 2 deletions packages/nestlib/src/database/abstract.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
UpdateQuery,
SaveOptions,
Connection,
ClientSession,
} from 'mongoose';
import { AbstractDocument } from './abstract.schema';

Expand All @@ -30,7 +31,7 @@ export abstract class AbstractRepository<TDocument extends AbstractDocument> {
).toJSON() as unknown as TDocument;
}

async findOne(filterQuery: FilterQuery<TDocument>): Promise<any> {
async findOne(filterQuery: FilterQuery<TDocument>) {
const document = await this.model.findOne(filterQuery, {}, { lean: true });

if (!document) {
Expand Down Expand Up @@ -73,7 +74,7 @@ export abstract class AbstractRepository<TDocument extends AbstractDocument> {
return this.model.find(filterQuery, {}, { lean: true });
}

async startTransaction() {
async startTransaction(): Promise<ClientSession> {
const session = await this.connection.startSession();
session.startTransaction();
return session;
Expand Down
14 changes: 11 additions & 3 deletions packages/nestlib/src/pipe/validation.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,21 @@ import { Types } from 'mongoose';
export interface ObjectIdPipeOptions {
errorHttpStatusCode?: ErrorHttpStatusCode;
errorMessage?: string;
exceptionFactory?: (error: string) => any;
exceptionFactory?: (error: string) => unknown;
optional?: boolean;
}

interface ObjectIdLike {
id: string | Uint8Array;
__id?: string;
toHexString(): string;
}
/**
* Ensure objectId of MongoDB
*/
@Injectable()
export class ObjectIdValidationPipe implements PipeTransform {
protected exceptionFactory: (error: string) => any;
protected exceptionFactory: (error: string) => unknown;

constructor(@Optional() protected readonly options?: ObjectIdPipeOptions) {
options = options || {};
Expand All @@ -35,7 +41,9 @@ export class ObjectIdValidationPipe implements PipeTransform {
((error) => new HttpErrorByCode[errorHttpStatusCode](error));
}

transform(value: any) {
transform(
value: string | number | Types.ObjectId | ObjectIdLike | Uint8Array,
) {
if (Types.ObjectId.isValid(value)) return value;
throw this.exceptionFactory(this.options.errorMessage || 'Invalid ID');
}
Expand Down

0 comments on commit 8b995d5

Please sign in to comment.