Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

135 refactor routes #137

Merged
merged 2 commits into from
Dec 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ module.exports = {
'prefer-const': 'warn',
'@typescript-eslint/no-unused-vars': [
'error',
{ ignoreRestSiblings: true },
{ ignoreRestSiblings: true, argsIgnorePattern: '^_' },
],
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
Expand Down
1 change: 1 addition & 0 deletions src/common/constants/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const NO_TOKEN_PROVIDED = 'No token provided' as const
1 change: 1 addition & 0 deletions src/modules/player/player.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ import { Environment } from '@config/environment'
],
controllers: [PlayerController],
providers: [PlayerService],
exports: [PlayerService],
})
export class PlayerModule {}
41 changes: 41 additions & 0 deletions src/modules/users/users-profile.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import {
spotifyResponseWithOffsetMockFactory,
artistsMock,
analysisMock,
playbackStateMock,
} from '@common/mocks'
import { SecretData } from '@modules/auth/dtos'
import { PlayerService } from '@modules/player'

describe('UsersProfileController', () => {
const accessToken = 'accessToken'
Expand All @@ -34,6 +36,7 @@ describe('UsersProfileController', () => {
let usersRepository: UsersRepository
let authService: AuthService
let statisticsService: StatisticsService
let playerService: PlayerService

beforeEach(async () => {
const module = await Test.createTestingModule({
Expand Down Expand Up @@ -63,13 +66,20 @@ describe('UsersProfileController', () => {
analysis: vi.fn(),
},
},
{
provide: PlayerService,
useValue: {
currentPlaybackState: vi.fn(),
},
},
],
}).compile()

usersProfileController = module.get(UsersProfileController)
usersRepository = module.get(UsersRepository)
authService = module.get(AuthService)
statisticsService = module.get(StatisticsService)
playerService = module.get(PlayerService)
})

test('should be defined', () => {
Expand Down Expand Up @@ -358,4 +368,35 @@ describe('UsersProfileController', () => {
expect(findOneBySpy).toHaveBeenCalledWith({ id })
})
})

describe('getState', () => {
test('should get user playback state', async () => {
const findOneBySpy = vi
.spyOn(usersRepository, 'findOneBy')
.mockResolvedValue(userMock)
const tokenSpy = vi
.spyOn(authService, 'token')
.mockResolvedValue(secretDataMock)
const currentPlaybackStateSpy = vi
.spyOn(playerService, 'currentPlaybackState')
.mockResolvedValue(playbackStateMock)

expect(await usersProfileController.getState(id)).toEqual(
playbackStateMock
)
expect(currentPlaybackStateSpy).toHaveBeenCalledWith(accessToken)
expect(findOneBySpy).toHaveBeenCalledWith({ id })
expect(tokenSpy).toHaveBeenCalledWith({
refreshToken: userMock.refreshToken,
})
})

test('should throw an error if no user is found', async () => {
const findOneBySpy = vi.spyOn(usersRepository, 'findOneBy')

await expect(usersProfileController.getState(id)).rejects.toThrowError()

expect(findOneBySpy).toHaveBeenCalledWith({ id })
})
})
})
53 changes: 47 additions & 6 deletions src/modules/users/users-profile.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
import { UsersRepository } from './users.repository'
import { USER } from './users.controller'

import { PlayerService } from '@modules/player'
import { ApiItemQuery } from '@modules/statistics/decorators'
import {
StatisticsService,
Expand All @@ -32,15 +33,19 @@ import {
NOT_BEEN_FOUND,
ONE_IS_INVALID,
} from '@common/constants'
import { ApiAuth, Token } from '@modules/auth/decorators'
import { AuthenticationType } from '@modules/auth/enums'

@Controller('users/:id/profile')
@ApiTags('users/{id}/profile')
@ApiAuth(AuthenticationType.ACCESS_TOKEN)
export class UsersProfileController {
constructor(
private readonly usersRepository: UsersRepository,
@Inject(forwardRef(() => AuthService))
private readonly authService: AuthService,
private readonly statisticsService: StatisticsService
private readonly statisticsService: StatisticsService,
private readonly playerService: PlayerService
) {}

@Get('last-tracks')
Expand All @@ -60,7 +65,8 @@ export class UsersProfileController {
})
async getLastTracks(
@Param('id', ParseUUIDPipe) id: string,
@Query() { limit, before, after }: LastItemQuery
@Query() { limit, before, after }: LastItemQuery,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

Expand Down Expand Up @@ -90,7 +96,8 @@ export class UsersProfileController {
})
async getTopArtists(
@Param('id', ParseUUIDPipe) id: string,
@Query() { limit, timeRange, offset }: TopItemQuery
@Query() { limit, timeRange, offset }: TopItemQuery,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

Expand Down Expand Up @@ -125,7 +132,8 @@ export class UsersProfileController {
})
async getTopTracks(
@Param('id', ParseUUIDPipe) id: string,
@Query() { limit, timeRange, offset }: TopItemQuery
@Query() { limit, timeRange, offset }: TopItemQuery,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

Expand Down Expand Up @@ -160,7 +168,8 @@ export class UsersProfileController {
})
async getTopGenres(
@Param('id', ParseUUIDPipe) id: string,
@Query() { limit, timeRange, offset }: TopItemQuery
@Query() { limit, timeRange, offset }: TopItemQuery,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

Expand Down Expand Up @@ -192,7 +201,10 @@ export class UsersProfileController {
@ApiBadRequestResponse({
description: ONE_IS_INVALID('uuid'),
})
async getAnalysis(@Param('id', ParseUUIDPipe) id: string) {
async getAnalysis(
@Param('id', ParseUUIDPipe) id: string,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

if (!foundUser) throw new NotFoundException(NOT_BEEN_FOUND(USER))
Expand All @@ -203,4 +215,33 @@ export class UsersProfileController {

return this.statisticsService.analysis(accessToken)
}

@Get('state')
@ApiOperation({
summary: "Getting user's playback state.",
})
@ApiParam({ name: 'id' })
@ApiOkResponse({
description: ONE_SUCCESFULLY_FOUND(USER),
})
@ApiNotFoundResponse({
description: NOT_BEEN_FOUND(USER),
})
@ApiBadRequestResponse({
description: ONE_IS_INVALID('uuid'),
})
async getState(
@Param('id', ParseUUIDPipe) id: string,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

if (!foundUser) throw new NotFoundException(NOT_BEEN_FOUND(USER))

const { accessToken } = await this.authService.token({
refreshToken: foundUser.refreshToken,
})

return this.playerService.currentPlaybackState(accessToken)
}
}
13 changes: 11 additions & 2 deletions src/modules/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,15 @@ import {
ONE_IS_INVALID,
ONE_SUCCESFULLY_FOUND,
} from '@common/constants'
import { AuthenticationType } from '@modules/auth/enums'
import { ApiAuth, Token } from '@modules/auth/decorators'

export const USER = 'user'
export const USERS = 'users'

@Controller(USERS)
@ApiTags(USERS)
@ApiAuth(AuthenticationType.ACCESS_TOKEN)
export class UsersController {
constructor(private readonly usersRepository: UsersRepository) {}

Expand All @@ -49,7 +52,10 @@ export class UsersController {
@ApiNoContentResponse({
description: NOT_BEEN_FOUND(USER),
})
async getAll(@Query('displayName') displayName?: string) {
async getAll(
@Query('displayName') displayName?: string,
@Token() _token?: string
) {
if (displayName) {
const foundUser =
await this.usersRepository.findOneByDisplayName(displayName)
Expand Down Expand Up @@ -78,7 +84,10 @@ export class UsersController {
@ApiBadRequestResponse({
description: ONE_IS_INVALID('uuid'),
})
async getOneById(@Param('id', ParseUUIDPipe) id: string) {
async getOneById(
@Param('id', ParseUUIDPipe) id: string,
@Token() _token?: string
) {
const foundUser = await this.usersRepository.findOneBy({ id })

if (!foundUser) throw new NotFoundException(NOT_BEEN_FOUND(USER))
Expand Down
2 changes: 2 additions & 0 deletions src/modules/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import { UsersProfileController } from './users-profile.controller'

import { AuthModule } from '@modules/auth'
import { StatisticsModule } from '@modules/statistics'
import { PlayerModule } from '@modules/player'

@Module({
imports: [
TypeOrmModule.forFeature([User]),
forwardRef(() => AuthModule),
StatisticsModule,
PlayerModule,
],
providers: [UsersRepository],
controllers: [UsersController, UsersProfileController],
Expand Down
Loading