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

Added userChallenge pagination #33

Merged
merged 10 commits into from
Dec 8, 2024
35 changes: 34 additions & 1 deletion src/api/userChallenge/challenge.crud.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import { CreateChallengeDBPayload, FindByParams } from './validation.schema';
import { UserChallengeProgress } from '../../database/models/UserChallengeProgress';

import { PaginationRequest } from '~/core/interfaces';
import { getPaginationMeta } from '~/core/utils';
import { UserChallenge } from '~/database/models/UserChallenge';
import { UserChallengeProgress } from '~/database/models/UserChallengeProgress';
import { ChallengeStatus } from '~/shared/userChallenge';

interface WhereClause {
userId: string;
status?: ChallengeStatus;
}

interface FindManyParams {
whereClause: WhereClause;
paginationParams: PaginationRequest;
}

export class UserChallengeCrud {
static findManyByUserId(userId: string) {
Expand All @@ -12,6 +25,26 @@ export class UserChallengeCrud {
});
}

static async findMany({ whereClause, paginationParams }: FindManyParams) {
const { page, limit } = paginationParams;

const offset = (page - 1) * limit;

const { rows: challenges, count: totalRecords } =
await UserChallenge.findAndCountAll({
where: whereClause,
limit,
offset,
});

const paginationMeta = getPaginationMeta(page, limit, totalRecords);

return {
data: challenges,
pagination: paginationMeta,
};
}

static findOneByParams(params: FindByParams) {
return UserChallenge.findOne({
where: {
Expand Down
19 changes: 17 additions & 2 deletions src/api/userChallenge/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
UnprocessableEntityError,
} from '~/core/errors';
import { isAuthenticated } from '~/shared/user';
import { ChallengeStatus } from '~/shared/userChallenge';

const route = express.Router();

Expand Down Expand Up @@ -110,16 +111,30 @@ route.get('/', async (req: Request, res: Response, next: NextFunction) => {
return next(new UnauthorizedError(ErrorMessages.unauthorized));
}

const status = req.query.status as ChallengeStatus;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added the validation lorgic here.

We always should work with safe/parsed values because we don`t know what we can get

const page = Number(req.query.page);
const limit = Number(req.query.limit);

try {
const dbresult = await UserChallengeCrud.findManyByUserId(user.id);
const { data, pagination } = await UserChallengeCrud.findMany({
whereClause: {
userId: user.id,
status,
},
paginationParams: {
page,
limit,
},
});

return res.status(200).json({
type: 'CHALLENGE_LIST_FETCHED',
statusCode: 200,
message: 'Challenge list fetched successfully',
isSuccess: true,
details: {
challenges: dbresult,
data,
meta: pagination,
},
});
} catch (error: unknown) {
Expand Down
1 change: 1 addition & 0 deletions src/core/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './response';
export * from './pagination';
12 changes: 12 additions & 0 deletions src/core/interfaces/pagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export interface PaginationResponse {
totalRecords: number;
totalPages: number;
currentPage: number;
nextPage: number | null;
prevPage: number | null;
}

export interface PaginationRequest {
page: number;
limit: number;
}
1 change: 1 addition & 0 deletions src/core/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from './generateOTP';
export * from './jwt';
export * from './buffer';
export * from './modelToPlain';
export * from './pagination';
export * from './env';
19 changes: 19 additions & 0 deletions src/core/utils/pagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { PaginationResponse } from '~/core/interfaces';

export const getPaginationMeta = (
page: number,
limit: number,
totalRecords: number,
): PaginationResponse => {
const totalPages = Math.ceil(totalRecords / limit);

const paginationMeta: PaginationResponse = {
totalRecords,
totalPages,
currentPage: page,
nextPage: page < totalPages ? page + 1 : null,
prevPage: page > 1 ? page - 1 : null,
};

return paginationMeta;
};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should to mark each challenge according our new statuses and the startAtDate property.

If startAtDate === currentMonth -> ACTIVE
if startAtDate < currentMonth -> COMPLETED

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('userChallenge', 'status', {
type: Sequelize.TEXT,
allowNull: true,
unique: false,
defaultValue: 'ACTIVE',
});
},

async down(queryInterface, Sequelize) {
await queryInterface.removeColumn('userChallenge', 'status');
},
};
13 changes: 12 additions & 1 deletion src/database/models/UserChallenge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { DataTypes } from 'sequelize';
import Sequelize from '../connection';
import { User } from './User';

import { ChallengeTypeValues } from '~/shared/userChallenge';
import {
ChallengeStatusValues,
ChallengeTypeValues,
} from '~/shared/userChallenge';

export const UserChallenge = Sequelize.define(
'userChallenge',
Expand Down Expand Up @@ -55,6 +58,14 @@ export const UserChallenge = Sequelize.define(
},
},

status: {
type: DataTypes.ENUM(...ChallengeStatusValues),
allowNull: true,
validate: {
isIn: [ChallengeStatusValues],
},
},

userId: {
type: DataTypes.UUIDV4,
allowNull: false,
Expand Down
3 changes: 2 additions & 1 deletion src/shared/userChallenge/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ChallengeType } from './types';
import { ChallengeStatus, ChallengeType } from './types';

export const ChallengeTypeValues = Object.values(ChallengeType);
export const ChallengeStatusValues = Object.values(ChallengeStatus);
5 changes: 5 additions & 0 deletions src/shared/userChallenge/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,8 @@ export enum ChallengeType {
Sleep = 'SLEEP',
Other = 'OTHER',
}

export enum ChallengeStatus {
'ACTIVE' = 'ACTIVE',
'COMPLETED' = 'COMPLETED',
}
Loading