Skip to content

Commit

Permalink
Update here and there
Browse files Browse the repository at this point in the history
  • Loading branch information
sayeed205 committed Jun 3, 2023
1 parent 7bd59a5 commit 7781058
Show file tree
Hide file tree
Showing 23 changed files with 199 additions and 61 deletions.
8 changes: 0 additions & 8 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
{
"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"]
}
2 changes: 1 addition & 1 deletion src/app/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { UserDocument } from 'src/auth/schemas';
import { GetUser } from 'src/common/decorators';
import { GetUser } from 'src/utilities/decorators';
import { AppService } from './app.service';

@Controller()
Expand Down
18 changes: 8 additions & 10 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ export class AuthService {
private jwtService: JwtService,
) {}

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

// Check if user with phone number already exists as registered user
Expand All @@ -37,7 +35,7 @@ export class AuthService {
user.signedUpOn = new Date();
await user.save();
const token = this.jwtService.sign({ user_id: user._id });
return { ok: true, data: { token } };
return { token };
}

// if user not found, create new user
Expand All @@ -50,10 +48,7 @@ export class AuthService {
});

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

async logIn(loginInfo: LoginInfo) {
Expand All @@ -72,8 +67,11 @@ export class AuthService {
// Send jwt token back to user
const token = this.jwtService.sign({ user_id: user._id });
return {
ok: true,
data: { token },
token,
name: user.name,
phone: user.phone,
image: user.avatar,
id: user._id,
};
}
}
2 changes: 1 addition & 1 deletion src/auth/dto/signup.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
IsString,
IsStrongPassword,
} from 'class-validator';
import { Match } from 'src/common/decorators';
import { Match } from 'src/utilities/decorators';

export class SignupDto {
@IsString()
Expand Down
24 changes: 0 additions & 24 deletions src/common/decorators/apiPaginatedResponse.decorator.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/common/dto/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './pagination.dto';
export * from './paginationRes.dto';
27 changes: 27 additions & 0 deletions src/common/dto/paginationQuery.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsInt, Max, Min } from 'class-validator';

export class PaginationQueryDto {
@ApiProperty({
description: 'Number of items per page',
default: 10,
minimum: 1,
maximum: 50,
})
@IsInt()
@Transform(({ value }) => parseInt(value))
@Min(1)
@Max(50)
limit = 10;

@ApiProperty({
description: 'Current page',
default: 1,
minimum: 1,
})
@IsInt()
@Transform(({ value }) => parseInt(value))
@Min(1)
page = 1;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

export class PaginationDto<TData> {
export class PaginationResDto<TData> {
@ApiProperty({
description: 'Total number of items found in the collection',
})
Expand Down
7 changes: 7 additions & 0 deletions src/transaction-room/dto/transaction-rooms-res.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Types } from 'mongoose';

export class TransactionRoomRes {
name: string;
_id: Types.ObjectId;
avatar?: string;
}
3 changes: 2 additions & 1 deletion src/transaction-room/schemas/transaction-room.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class roomDetails {
@Prop()
avatar?: string;

// TODO: Add more fields
@Prop({ type: Types.ObjectId, ref: 'Transaction' })
lastTransaction?: Types.ObjectId;
}

@Schema({ timestamps: true })
Expand Down
25 changes: 21 additions & 4 deletions src/transaction-room/transaction-room.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Get,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import {
ApiBadRequestResponse,
Expand All @@ -8,11 +16,13 @@ import {
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { Types } from 'mongoose';
import { PaginationQueryDto } from 'src/common/dto/paginationQuery.dto';

import { User } from '../auth/schemas/user.schema';
import { GetUser } from '../common/decorators';
import { ValidateMongoId } from '../pipes';
import { ApiPaginatedResponse, GetUser } from '../utilities/decorators';
import { ValidateMongoId } from '../utilities/pipes';
import { createTransactionRoomDto } from './dto';
import { TransactionRoomRes } from './dto/transaction-rooms-res.dto';
import { TransactionRoomService } from './transaction-room.service';

@Controller('transaction-room')
Expand Down Expand Up @@ -42,12 +52,19 @@ export class TransactionRoomController {
}

@Get('all')
@ApiPaginatedResponse(TransactionRoomRes)
@ApiUnauthorizedResponse({ description: 'Unauthorized' })
async getAllTransactionRooms(
@GetUser()
user: User,
@Query()
paginationQuery: PaginationQueryDto,
) {
console.log('paginationQuery', paginationQuery);
const _id = user._id;
return await this.transactionRoomService.getAllTransactionRooms(_id);
return await this.transactionRoomService.getAllTransactionRooms(_id, {
...paginationQuery,
});
}

@Get(':id')
Expand Down
94 changes: 88 additions & 6 deletions src/transaction-room/transaction-room.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { PaginationResDto } from 'src/common/dto';
import { User } from '../auth/schemas/user.schema';
import { TransactionRoom } from './schemas';

Expand Down Expand Up @@ -79,13 +80,94 @@ export class TransactionRoomService {
return newTransactionRoom;
}

async getAllTransactionRooms(id: Types.ObjectId) {
// Find all transaction rooms where the given user is a member in the members array
const transactionRooms = await this.transactionRoomModel.find({
members: { $in: [id] },
});
async getAllTransactionRooms(
id: Types.ObjectId,
{ page, limit }: { page: number; limit: number },
): Promise<PaginationResDto<TransactionRoom>> {
// {
// "_id": "6460b71dd930d70d3b6d3e3f",
// "members": [
// "6460b70dd930d70d3b6d3e39",
// "6460b71dd930d70d3b6d3e3d"
// ],
// "roomDetails": [
// {
// "userId": "6460b70dd930d70d3b6d3e39",
// "name": "Raj Da"
// },
// {
// "userId": "6460b71dd930d70d3b6d3e3d",
// "name": "Sayeed"
// }
// ],
// "createdAt": "2023-05-14T10:25:33.059Z",
// "updatedAt": "2023-05-15T01:07:15.049Z",
// "__v": 9
// },

const aggregateOptions = [
{
$match: {
members: { $in: [id] },
},
},
{
$addFields: {
name: {
$filter: {
input: '$roomDetails',
as: 'roomDetail',
cond: { $eq: ['$$roomDetail.userId', id] },
},
},
},
},
{
$addFields: {
image: {
$filter: {
input: '$roomDetails',
as: 'roomDetail',
cond: { $eq: ['$$roomDetail.userId', id] },
},
},
},
},
{
$project: {
_id: 1,
name: { $arrayElemAt: ['$name.name', 0] },
image: { $arrayElemAt: ['$image.image', 0] },
},
},
];

const transactionRooms = await this.transactionRoomModel.aggregate([
...aggregateOptions,
{
$limit: limit,
},
{
$skip: (page - 1) * limit,
},
// {
// $sort: {
// "lastTransaction.createdAt": -1
// }
// }
]); // TODO)): add last transaction details

const total = await this.transactionRoomModel.countDocuments(
aggregateOptions,
);

// Return the transaction rooms
return transactionRooms; // TODO)): add pagination and aggregate with proper room details
return {
total,
page,
limit,
pages: Math.ceil(total / limit),
results: transactionRooms,
};
}
}
2 changes: 1 addition & 1 deletion src/transaction/dto/transaction-query.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Transform } from 'class-transformer';
import { IsInt, IsNotEmpty, IsString } from 'class-validator';

import { Types } from 'mongoose';
import { IsValidMongoId } from 'src/common/decorators';
import { IsValidMongoId } from 'src/utilities/decorators';

export class TransactionQueryDto {
@IsNotEmpty()
Expand Down
4 changes: 2 additions & 2 deletions src/transaction/transaction.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import {
import { Types } from 'mongoose';

import { User } from '../auth/schemas/user.schema';
import { GetUser } from '../common/decorators';
import { ValidateMongoId } from '../pipes';
import { GetUser } from '../utilities/decorators';
import { ValidateMongoId } from '../utilities/pipes';
import {
TransactionQueryDto,
createTransactionDto,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ValidationOptions, registerDecorator } from 'class-validator';
import { Types } from 'mongoose';
import { MongoIdException } from 'src/exceptions';
import { MongoIdException } from 'src/utilities/exceptions';

/**
* Validates that a given value is a valid MongoDB ObjectId.
Expand Down
38 changes: 38 additions & 0 deletions src/utilities/decorators/apiPaginatedResponse.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { applyDecorators, Type } from '@nestjs/common';
import { ApiOkResponse, getSchemaPath } from '@nestjs/swagger';

import { PaginationResDto } from '../../common/dto';

export const ApiPaginatedResponse = <TModel extends Type<any>>(model: TModel) =>
applyDecorators(
ApiOkResponse({
schema: {
title: `${model.name}PaginatedResponse`,
allOf: [
{ $ref: getSchemaPath(PaginationResDto) },
{
properties: {
page: {
type: 'number',
default: 1,
},
limit: {
type: 'number',
default: 10,
},
total: {
type: 'number',
},
pages: {
type: 'number',
},
results: {
type: 'array',
items: { $ref: getSchemaPath(model) },
},
},
},
],
},
}),
);
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 7781058

Please sign in to comment.