Skip to content

Commit

Permalink
refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
sayeed205 committed May 29, 2023
1 parent 7f57ab7 commit f81b752
Show file tree
Hide file tree
Showing 25 changed files with 277 additions and 187 deletions.
14 changes: 7 additions & 7 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 4,
"semi": false,
"arrowParens": "avoid",
"endOfLine": "auto"
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 4,
"semi": true,
"arrowParens": "avoid",
"endOfLine": "auto"
}
17 changes: 9 additions & 8 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
{
"search.exclude": {
"**/.yarn": true,
"**/.pnp.*": true
},
"eslint.nodePath": ".yarn/sdks",
"prettier.prettierPath": ".yarn/sdks/prettier/index.js",
"typescript.tsdk": ".yarn/sdks/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
"search.exclude": {
"**/.yarn": true,
"**/.pnp.*": true
},
"eslint.nodePath": ".yarn/sdks",
"prettier.prettierPath": ".yarn/sdks/prettier/index.js",
"typescript.tsdk": ".yarn/sdks/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"cSpell.words": ["ectx"]
}
22 changes: 11 additions & 11 deletions src/app/app.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing'
import { Test, TestingModule } from '@nestjs/testing';

import { AppController } from './app.controller'
import { AppService } from './app.service'
import { AppController } from './app.controller';
import { AppService } from './app.service';

describe('AppController', () => {
let app: TestingModule
let app: TestingModule;

beforeAll(async () => {
app = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile()
})
}).compile();
});

describe('getData', () => {
it('should return "Hello World!"', () => {
const appController = app.get<AppController>(AppController)
const appController = app.get<AppController>(AppController);
expect(appController.getHello()).toEqual({
message: 'Hello World!',
})
})
})
})
});
});
});
});
6 changes: 3 additions & 3 deletions src/app/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Controller, Get } from '@nestjs/common'
import { Controller, Get } from '@nestjs/common';

import { AppService } from './app.service'
import { AppService } from './app.service';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}

@Get()
getHello() {
return this.appService.getHello()
return this.appService.getHello();
}
}
26 changes: 13 additions & 13 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { MorganMiddleware } from '@nest-middlewares/morgan'
import { MorganMiddleware } from '@nest-middlewares/morgan';
import {
MiddlewareConsumer,
Module,
NestModule,
ValidationPipe,
} from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
import { APP_PIPE } from '@nestjs/core'
import { MongooseModule } from '@nestjs/mongoose'
} from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_PIPE } from '@nestjs/core';
import { MongooseModule } from '@nestjs/mongoose';

import { AuthModule } from '../auth/auth.module'
import { TransactionRoomModule } from '../transaction-room/transaction-room.module'
import { TransactionModule } from '../transaction/transaction.module'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { AuthModule } from '../auth/auth.module';
import { TransactionRoomModule } from '../transaction-room/transaction-room.module';
import { TransactionModule } from '../transaction/transaction.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
imports: [
Expand All @@ -36,14 +36,14 @@ import { AppService } from './app.service'
transform: true,
forbidNonWhitelisted: true,
transformOptions: { enableImplicitConversion: true },
})
});
},
},
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
MorganMiddleware.configure('dev')
consumer.apply(MorganMiddleware).forRoutes('*')
MorganMiddleware.configure('dev');
consumer.apply(MorganMiddleware).forRoutes('*');
}
}
20 changes: 10 additions & 10 deletions src/app/app.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { Test } from '@nestjs/testing'
import { Test } from '@nestjs/testing';

import { AppService } from './app.service'
import { AppService } from './app.service';

describe('AppService', () => {
let service: AppService
let service: AppService;

beforeAll(async () => {
const app = await Test.createTestingModule({
providers: [AppService],
}).compile()
}).compile();

service = app.get<AppService>(AppService)
})
service = app.get<AppService>(AppService);
});

describe('getHello', () => {
it('should return "Hello API"', () => {
expect(service.getHello()).toEqual({ message: 'Hello API' })
})
})
})
expect(service.getHello()).toEqual({ message: 'Hello API' });
});
});
});
4 changes: 2 additions & 2 deletions src/app/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Injectable } from '@nestjs/common'
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
getHello() {
return {
message: 'Hello World!',
}
};
}
}
25 changes: 7 additions & 18 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
// auth.module.ts
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { PassportModule } from '@nestjs/passport';

import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtConfigModule } from './jwt.config.module';
import { JwtStrategy } from './jwt.strategy';
import { User, UserSchema } from './schemas/user.schema';
import { authProviders } from './providers';
import { UserModule } from './user.module';

@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<string | number>(
'JWT_EXPIRES_IN',
),
},
}),
}),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
JwtConfigModule,
UserModule,
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
providers: [...authProviders],
exports: [JwtStrategy, PassportModule],
})
export class AuthModule {}
20 changes: 10 additions & 10 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';

describe('AuthService', () => {
let service: AuthService;
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();

service = module.get<AuthService>(AuthService);
});
service = module.get<AuthService>(AuthService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
57 changes: 29 additions & 28 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import {
ConflictException,
Injectable,
UnauthorizedException,
} from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

import { LoginDto, SignupDto } from './dto'
import { User } from './schemas/user.schema'
import { AuthError, LoginInfo, SignupInfo } from './interfaces/auth.interface';
import { User } from './schemas/user.schema';

@Injectable()
export class AuthService {
Expand All @@ -19,25 +19,25 @@ export class AuthService {
) {}

async signUp(
signupInfo: SignupDto,
signupInfo: SignupInfo,
): Promise<{ ok: boolean; data: { token: string } }> {
const { phone, password, name } = signupInfo
const { phone, password, name } = signupInfo;

// Check if user with phone number already exists as registered user
const user = await this.userModel.findOne({ phone })
let user = await this.userModel.findOne({ phone });
if (user && user.isReal) {
throw new ConflictException('phone number already in use')
throw new ConflictException(AuthError.PhoneAlreadyInUse);
}
if (user && !user.isReal) {
// TODO: Send OTP to user and verify it to complete registration
// sendOTP();
user.name = name
user.password = password
user.isReal = true
user.signedUpOn = new Date()
await user.save()
const token = this.jwtService.sign({ user_id: user._id })
return { ok: true, data: { token } }
user.name = name;
user.password = password;
user.isReal = true;
user.signedUpOn = new Date();
await user.save();
const token = this.jwtService.sign({ user_id: user._id });
return { ok: true, data: { token } };
}

// if user not found, create new user
Expand All @@ -47,32 +47,33 @@ export class AuthService {
phone,
isReal: true,
signedUpOn: new Date(),
})
});

const token = this.jwtService.sign({ user_id: newUser._id })
const token = this.jwtService.sign({ user_id: newUser._id });
return {
ok: true,
data: { token },
}
};
}

async logIn(loginInfo: LoginDto) {
const { phone, password } = loginInfo
async logIn(loginInfo: LoginInfo) {
const { phone, password } = loginInfo;

// Check if user with phone number already exists as registered user
const user = await this.userModel.findOne({ phone, isReal: true })
if (!user) throw new UnauthorizedException('Invalid credentials')
const user = await this.userModel.findOne({ phone, isReal: true });
if (!user)
throw new UnauthorizedException(AuthError.InvalidCredentials);

// Check if password is correct
const isPasswordCorrect = await user.comparePassword(password)
const isPasswordCorrect = await user.comparePassword(password);
if (!isPasswordCorrect)
throw new UnauthorizedException('Invalid credentials')
throw new UnauthorizedException(AuthError.InvalidCredentials);

// Send jwt token back to user
const token = this.jwtService.sign({ user_id: user._id })
const token = this.jwtService.sign({ user_id: user._id });
return {
ok: true,
data: { token },
}
};
}
}
2 changes: 0 additions & 2 deletions src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,4 @@ export class LoginDto {
example: 'Abcd@1234',
})
password: string;

// email?:
}
19 changes: 19 additions & 0 deletions src/auth/interfaces/auth.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export interface SignupInfo {
phone: string;
password: string;
name: string;
}

export interface LoginInfo {
phone: string;
password: string;
}

export interface JwtPayload {
user_id: string;
}

export enum AuthError {
PhoneAlreadyInUse = 'phone number already in use',
InvalidCredentials = 'Invalid credentials',
}
Loading

0 comments on commit f81b752

Please sign in to comment.