Skip to content

Commit

Permalink
Merge pull request #86 from SigwoTechnologies/feat/change-account-inf…
Browse files Browse the repository at this point in the history
…ormation

feat: change account information
  • Loading branch information
AlefrankM authored Jan 13, 2023
2 parents b0120a3 + adb27f5 commit a0a15b4
Show file tree
Hide file tree
Showing 18 changed files with 213 additions and 31 deletions.
9 changes: 8 additions & 1 deletion src/account/__tests__/account.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Collection, Image } from '../../config/entities.config';
import { ItemService } from '../../items/services/item.service';
import { Voucher } from '../../items/entities/voucher.entity';
import { CollectionService } from '../../collections/services/collection.service';
import { AccountService } from '../services/account.service';

const itemServiceMock = () => ({
findByAddress: jest.fn(),
Expand All @@ -18,6 +19,11 @@ const collectionServiceMock = () => ({
findByOwner: jest.fn(),
});

const accountServiceMock = () => ({
findByAddress: jest.fn(),
changeInformation: jest.fn(),
});

describe('AccountController', () => {
let controller: AccountsController;
let itemService;
Expand All @@ -28,6 +34,7 @@ describe('AccountController', () => {
providers: [
{ provide: ItemService, useFactory: itemServiceMock },
{ provide: CollectionService, useFactory: collectionServiceMock },
{ provide: AccountService, useFactory: accountServiceMock },
],
}).compile();

Expand Down Expand Up @@ -70,7 +77,7 @@ describe('AccountController', () => {
const mockData = expected.map((prop) => ({ ...prop }));
itemService.findByAddress.mockResolvedValue(mockData);

const actual = await controller.findItems('123');
const actual = await controller.findItems('123', { limit: 15, page: 1 });

expect(actual[0].itemId).toEqual(expected[0].itemId);
});
Expand Down
3 changes: 2 additions & 1 deletion src/account/account.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { ItemModule } from '../items/item.module';
import { Module } from '@nestjs/common';
import { CollectionRepository } from '../collections/repositories/collection.repository';
import { CollectionService } from '../collections/services/collection.service';
import { AccountService } from './services/account.service';

@Module({
imports: [ItemModule],
controllers: [AccountsController],
providers: [AccountRepository, CollectionRepository, CollectionService],
providers: [AccountRepository, CollectionRepository, CollectionService, AccountService],
exports: [AccountRepository],
})
export class AccountModule {}
31 changes: 25 additions & 6 deletions src/account/controllers/account.controller.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import { Controller, Get, Param } from '@nestjs/common';
import { Controller, Get, Param, Query, Patch, Body } from '@nestjs/common';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { IsAddressValid } from '../../auth/decorators/address.decorator';
import { Collection } from '../../collections/entities/collection.entity';
import { CollectionService } from '../../collections/services/collection.service';
import { Item } from '../../items/entities/item.entity';
import { ItemService } from '../../items/services/item.service';
import { EditAccountDto } from '../dto/edit-account.dto';
import { AccountService } from '../services/account.service';
@Controller('accounts')
export class AccountsController {
constructor(private itemService: ItemService, private collectionService: CollectionService) {}
constructor(
private itemService: ItemService,
private collectionService: CollectionService,
private accountService: AccountService
) {}

@IsAddressValid()
@Get('/:address/items')
findItems(@Param('address') address: string): Promise<Item[]> {
return this.itemService.findByAddress(address);
findItems(
@Param('address') address: string,
@Query() paginationDto: PaginationDto
): Promise<Item[]> {
return this.itemService.findByAddress(address, paginationDto);
}

@IsAddressValid()
Expand All @@ -28,7 +38,16 @@ export class AccountsController {

@IsAddressValid()
@Get('/:address/liked-items')
findLikedItems(@Param('address') address: string): Promise<Item[]> {
return this.itemService.findLikedByAddress(address);
findLikedItems(
@Param('address') address: string,
@Query() paginationDto: PaginationDto
): Promise<Item[]> {
return this.itemService.findLikedByAddress(address, paginationDto);
}

@IsAddressValid()
@Patch('/:address')
changeInformation(@Param('address') address: string, @Body() editAccountDto: EditAccountDto) {
return this.accountService.changeInformation(address, editAccountDto);
}
}
23 changes: 23 additions & 0 deletions src/account/dto/edit-account.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { IsOptional, IsString } from 'class-validator';

export class EditAccountDto {
@IsOptional()
background: {
url: string;
cid: string;
};

@IsOptional()
picture: {
url: string;
cid: string;
};

@IsOptional()
@IsString()
address: string;

@IsOptional()
@IsString()
username: string;
}
22 changes: 21 additions & 1 deletion src/account/entities/account.entity.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Item } from '../../items/entities/item.entity';
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Column, Entity, JoinColumn, OneToMany, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
import { History } from '../../items/entities/history.entity';
import { ItemLike } from '../../items/entities/item-like.entity';
import { Voucher } from '../../items/entities/voucher.entity';
import { Collection } from '../../collections/entities/collection.entity';
import { Image } from '../../items/entities/image.entity';

@Entity()
export class Account {
Expand All @@ -13,6 +14,9 @@ export class Account {
@Column({ unique: true, nullable: false })
address: string;

@Column({ unique: true, nullable: true })
username: string;

@OneToMany(() => Item, (item) => item.owner, { cascade: true })
items: Item[];

Expand All @@ -28,6 +32,22 @@ export class Account {
@OneToMany(() => Collection, (table) => table.owner, { cascade: true })
collections: Collection[];

@OneToOne(() => Image, {
onDelete: 'CASCADE',
orphanedRowAction: 'delete',
cascade: true,
})
@JoinColumn({ name: 'backgroundId' })
background: Image;

@OneToOne(() => Image, {
onDelete: 'CASCADE',
orphanedRowAction: 'delete',
cascade: true,
})
@JoinColumn({ name: 'pictureId' })
picture: Image;

@Column()
createdAt: Date;

Expand Down
24 changes: 23 additions & 1 deletion src/account/repositories/account.repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Account } from '../entities/account.entity';
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { EditAccountDto } from '../dto/edit-account.dto';
import { formatImageUrl } from '../../common/utils/image-utils';
import { Image } from '../../items/entities/image.entity';

@Injectable()
export class AccountRepository extends Repository<Account> {
Expand All @@ -10,12 +13,31 @@ export class AccountRepository extends Repository<Account> {

async findByAddress(address: string): Promise<Account | undefined> {
const account = await this.createQueryBuilder('account')
.select(['account.accountId', 'account.address'])
.where('account.address = :address', { address: address.toLocaleLowerCase() })
.getOne();

if (!account) return;

return account;
}

async changeInformation(account: Account, editAccountDto: EditAccountDto): Promise<Account> {
account.background =
account.background &&
({
url: formatImageUrl(editAccountDto.background.url),
cid: editAccountDto.background.cid,
} as Image);

account.picture =
account.background &&
({
url: formatImageUrl(editAccountDto.picture.url),
cid: editAccountDto.picture.cid,
} as Image);

account.username = editAccountDto.username;

return this.save(account);
}
}
25 changes: 25 additions & 0 deletions src/account/services/account.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Injectable } from '@nestjs/common';
import { CollectionRepository } from '../../collections/repositories/collection.repository';
import { ItemRepository } from '../../items/repositories/item.repository';
import { EditAccountDto } from '../dto/edit-account.dto';
import { Account } from '../entities/account.entity';
import { AccountRepository } from '../repositories/account.repository';

@Injectable()
export class AccountService {
constructor(
private collectionRepository: CollectionRepository,
private accountRepository: AccountRepository,
private itemsRepository: ItemRepository
) {}

async findByAddress(address: string) {
return this.accountRepository.findByAddress(address);
}

async changeInformation(address: string, editAccountDto: EditAccountDto): Promise<Account> {
const account = await this.accountRepository.findByAddress(address);

return this.accountRepository.changeInformation(account, editAccountDto);
}
}
6 changes: 6 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './strategies/jwt.strategy';
import { CacheModule, Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AccountService } from 'src/account/services/account.service';
import { CollectionRepository } from 'src/collections/repositories/collection.repository';
import { ItemRepository } from 'src/items/repositories/item.repository';

@Module({
imports: [
Expand Down Expand Up @@ -38,6 +41,9 @@ import { PassportModule } from '@nestjs/passport';
provide: APP_GUARD,
useClass: AddressGuard,
},
AccountService,
CollectionRepository,
ItemRepository,
],
exports: [AuthService],
controllers: [AuthController],
Expand Down
8 changes: 5 additions & 3 deletions src/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { CredentialsResponseDto } from '../dto/credentials-response.dto';
import { Public } from '../../auth/decorators/public.decorator';
import { SigninRequestDto } from '../dto/signin-request.dto';
import { IsAddressValid } from '../decorators/address.decorator';
import { AccountService } from 'src/account/services/account.service';
import { Account } from 'src/config/entities.config';

@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
constructor(private authService: AuthService, private accountService: AccountService) {}

@Public()
@Post('/signin')
Expand All @@ -24,7 +26,7 @@ export class AuthController {

@IsAddressValid()
@Post('/authenticate')
authenticate(@Body() authCredentialsDto: CredentialsRequestDto): string {
return authCredentialsDto.address;
authenticate(@Body() authCredentialsDto: CredentialsRequestDto): Promise<Account> {
return this.accountService.findByAddress(authCredentialsDto.address);
}
}
3 changes: 3 additions & 0 deletions src/auth/dto/credentials-response.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { Account } from 'src/config/entities.config';

export class CredentialsResponseDto {
access_token: string;
account: Account;
}
2 changes: 1 addition & 1 deletion src/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class AuthService {

this.cacheManager.del(address);

return { access_token };
return { access_token, account };
}

throw new UnauthorizedException();
Expand Down
3 changes: 1 addition & 2 deletions src/collections/controllers/collection.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Body, Controller, Get, Param, Patch, Query } from '@nestjs/common';
import { Collection } from 'src/config/entities.config';
import { Collection } from '../../collections/entities/collection.entity';
import { NewestItemsRequestDto } from 'src/items/dto/newest-items-request.dto';
import { ItemPaginationDto } from 'src/items/dto/pagination-request.dto';
import { PriceRangeDto } from 'src/items/dto/price-range.dto';
Expand Down Expand Up @@ -51,7 +51,6 @@ export class CollectionsController {
@Param('collectionId') collectionId: string,
@Body() editCollectionDto: EditCollectionDto
): Promise<Collection> {
console.log(editCollectionDto);
return this.collectionService.changeInformation(collectionId, editCollectionDto);
}
}
2 changes: 1 addition & 1 deletion src/common/utils/average-item-likes-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Item } from 'src/config/entities.config';
import { Item } from '../../items/entities/item.entity';

export const getAverage = (items: Item[]) => {
const itemsTotalLikes = items.reduce((prev, actual) => prev + actual.likes, 0);
Expand Down
2 changes: 1 addition & 1 deletion src/config/datasource.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function getConfig() {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
migrations: ['src/migrations/**/*{.js,.ts}'],
migrations: ['src/migrations/*{.js,.ts}'],
entities: [__dirname + '/entities.config.ts'],
extra: {
ssl: {
Expand Down
6 changes: 3 additions & 3 deletions src/items/__tests__/item.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ describe('ItemService', () => {
const mockedData = expected.map((prop) => ({ ...prop }));
itemRepository.findByAccount.mockResolvedValue(mockedData);

const actual = await service.findByAddress('123');
const actual = await service.findByAddress('123', { limit: 15, page: 1 });

expect(actual).toEqual(expected);
});
Expand All @@ -206,7 +206,7 @@ describe('ItemService', () => {

accountRepository.findByAddress.mockResolvedValue(null);

const exception = () => service.findByAddress(unexistingAddress);
const exception = () => service.findByAddress(unexistingAddress, { limit: 15, page: 1 });

await expect(exception).rejects.toThrow(BusinessException);
await expect(exception).rejects.toEqual(
Expand Down Expand Up @@ -288,7 +288,7 @@ describe('ItemService', () => {

accountRepository.findByAddress.mockResolvedValue(null);

const exception = () => service.findByAddress(unexistingAddress);
const exception = () => service.findByAddress(unexistingAddress, { limit: 15, page: 1 });

await expect(exception).rejects.toThrow(BusinessException);
await expect(exception).rejects.toEqual(
Expand Down
Loading

0 comments on commit a0a15b4

Please sign in to comment.