finish all apis

main
Ayush Mukherjee 2 years ago
parent 3408f01ad5
commit 41d1a5071b

@ -5,12 +5,12 @@
- [x] user api - [x] user api
- [x] signup - [x] signup
- [x] login - [x] login
- [] leaderboard api - [x] leaderboard api
- [] add 20 pts - [x] add 20 pts
- [] add 60 pts - [x] add 60 pts
- [] add 100 pts - [x] add 100 pts
- [] get standings - [x] get standings
- [] get user score history - [x] get user score history
## additional notes ## additional notes

@ -3,6 +3,7 @@ import { SequelizeModule } from '@nestjs/sequelize';
import { UserModule } from './user/user.module'; import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module'; import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { RankModule } from './rank/rank.module';
@Module({ @Module({
imports: [ imports: [
@ -20,6 +21,7 @@ import { ConfigModule } from '@nestjs/config';
}), }),
UserModule, UserModule,
AuthModule, AuthModule,
RankModule,
], ],
}) })

@ -16,8 +16,8 @@ export class AuthController {
@UseGuards(LocalAuthGuard) @UseGuards(LocalAuthGuard)
@Post('login') @Post('login')
async login(@Req() req: Request) { async login(@Req() req) {
return this.authService.authenticate(req.user); return this.authService.authenticate(req.user.dataValues);
} }
@Post('register') @Post('register')

@ -5,11 +5,12 @@ import { ExtractJwt, Strategy } from "passport-jwt";
@Injectable() @Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) { export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) { constructor(configService: ConfigService) {
const secret = configService.get<string>('JWT_SECRET');
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false, ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET'), secretOrKey: secret,
}); });
} }

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { RankController } from './rank.controller';
describe('RankController', () => {
let controller: RankController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [RankController],
}).compile();
controller = module.get<RankController>(RankController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

@ -0,0 +1,45 @@
import { Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
import { Request } from 'express';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { Rank } from './rank.model';
import { RankService } from './rank.service';
@Controller('rank')
export class RankController {
constructor(private rankService: RankService) {}
@Get()
async getRankList(): Promise<Rank[]> {
return this.rankService.findRankList();
}
@UseGuards(JwtAuthGuard)
@Get('/:id')
async getUserRank(@Param('id') userId: string): Promise<Rank> {
return this.rankService.findByUserLatest(userId);
}
@UseGuards(JwtAuthGuard)
@Get('/:id/all')
async getUserHistory(@Param('id') userId: string): Promise<Rank[]> {
return this.rankService.findByUser(userId);
}
@UseGuards(JwtAuthGuard)
@Post('/add/20')
async add20Points(@Req() req): Promise<any> {
this.rankService.create(20, req.user.id);
}
@UseGuards(JwtAuthGuard)
@Post('/add/60')
async add60Points(@Req() req): Promise<void> {
this.rankService.create(60, req.user.id);
}
@UseGuards(JwtAuthGuard)
@Post('/add/100')
async add100Points(@Req() req): Promise<void> {
this.rankService.create(100, req.user.id);
}
}

@ -0,0 +1,30 @@
import { BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Model, NotEmpty, PrimaryKey, Table, UpdatedAt } from "sequelize-typescript";
import { User } from "src/user/user.model";
@Table({
timestamps: true,
})
export class Rank extends Model {
@PrimaryKey
@Default(DataType.UUIDV4)
@Column(DataType.STRING)
id: string;
@NotEmpty
@Column
points: number;
@CreatedAt
createdAt: Date;
@UpdatedAt
updatedAt: Date;
@NotEmpty
@ForeignKey(() => User)
@Column
userId: string;
@BelongsTo(() => User)
user: User;
}

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { RankService } from './rank.service';
import { RankController } from './rank.controller';
import { SequelizeModule } from '@nestjs/sequelize';
import { Rank } from './rank.model';
@Module({
imports: [
SequelizeModule.forFeature([Rank]),
],
providers: [RankService],
controllers: [RankController]
})
export class RankModule {}

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { RankService } from './rank.service';
describe('RankService', () => {
let service: RankService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [RankService],
}).compile();
service = module.get<RankService>(RankService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

@ -0,0 +1,69 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from 'sequelize';
import { col, fn } from 'sequelize';
import { User } from 'src/user/user.model';
import { Rank } from './rank.model';
@Injectable()
export class RankService {
constructor(
@InjectModel(Rank) private rankModel: typeof Rank
) {}
async create(points, userId): Promise<Rank> {
return this.rankModel.create({
points,
userId
});
}
async findAll(): Promise<Rank[]>{
return this.rankModel.findAll();
}
async findByUser(userId: string): Promise<Rank[]> {
return this.rankModel.findAll({
where: {
userId,
},
});
}
async findByUserLatest(userId: string): Promise<Rank> {
return this.rankModel.findOne({
where: {
userId,
},
order: ['createdAt', 'DESC'],
});
}
async findRankList(): Promise<Rank[]> {
return this.rankModel.findAll({
attributes: [
'id',
[fn('MAX', col('createdAt')), 'mDate'],
'userId',
],
group: ['userId'],
}).then((res) => {
const maxIds = [];
res.forEach(r => {
maxIds.push(r.id);
});
return this.rankModel.findAll({
attributes: ['id', 'points'],
where: {
id: {
[Op.in]: maxIds
},
},
include: [{
model: User,
attributes: ['name'],
}],
});
});
}
}

@ -1,6 +1,4 @@
import { Body, Controller, Get, Post } from '@nestjs/common'; import { Controller, Get } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from './dtos/CreateUserDto';
import { User } from './user.model'; import { User } from './user.model';
import { UserService } from './user.service'; import { UserService } from './user.service';
@ -13,10 +11,4 @@ export class UserController {
findAll(): Promise<User[]> { findAll(): Promise<User[]> {
return this.userService.findAll(); return this.userService.findAll();
} }
@Post()
async create(user: CreateUserDto) {
user.password = await bcrypt.hash(user.password, 10);
return user;
}
} }

@ -1,10 +1,10 @@
import { Column, Model, Table, CreatedAt, UpdatedAt, PrimaryKey, DataType, NotEmpty, Default } from 'sequelize-typescript'; import { Column, Model, Table, CreatedAt, UpdatedAt, PrimaryKey, DataType, NotEmpty, Default, HasMany } from 'sequelize-typescript';
import { Rank } from 'src/rank/rank.model';
@Table({ @Table({
timestamps: true, timestamps: true,
}) })
export class User extends Model { export class User extends Model {
@NotEmpty
@PrimaryKey @PrimaryKey
@Default(DataType.UUIDV4) @Default(DataType.UUIDV4)
@Column(DataType.STRING) @Column(DataType.STRING)
@ -29,4 +29,7 @@ export class User extends Model {
@UpdatedAt @UpdatedAt
@Column @Column
updatedAt: Date; updatedAt: Date;
@HasMany(() => Rank)
ranks: Rank[];
} }

Loading…
Cancel
Save