Skip to content

Commit

Permalink
fix count and limit issue in getMembers api
Browse files Browse the repository at this point in the history
  • Loading branch information
tusheer committed Mar 4, 2022
1 parent cf7e674 commit ec83cb8
Show file tree
Hide file tree
Showing 13 changed files with 2,315 additions and 2,311 deletions.
2 changes: 1 addition & 1 deletion client/src/api/members/getAllMembers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface ISinginBody {
}

interface IParams {
offset: number;
skip: number;
limit: number;
}

Expand Down
12 changes: 6 additions & 6 deletions client/src/modules/common/hooks/useInfiniteScroll.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useEffect, useRef, useState } from 'react';

interface IuseInfiniteScroll {
fetchAction: ({ limit, offset }: { limit: number; offset: number }) => void;
fetchAction: ({ limit, skip }: { limit: number; skip: number }) => void;
limit: number;
offset: number;
skip: number;
totalCount: number;
}

const useInfiniteScroll = ({ offset, limit, fetchAction, totalCount }: IuseInfiniteScroll) => {
const useInfiniteScroll = ({ skip, limit, fetchAction, totalCount }: IuseInfiniteScroll) => {
const scrollActiveRef = useRef<boolean>(false);

const handleScroll = (event: Event) => {
Expand All @@ -18,8 +18,8 @@ const useInfiniteScroll = ({ offset, limit, fetchAction, totalCount }: IuseInfin
scrollActiveRef.current = true;
}
} else {
if (offset < totalCount) {
fetchAction({ limit, offset });
if (skip < totalCount) {
fetchAction({ limit, skip });
}
scrollActiveRef.current = false;
}
Expand All @@ -29,7 +29,7 @@ const useInfiniteScroll = ({ offset, limit, fetchAction, totalCount }: IuseInfin
window.addEventListener('scroll', handleScroll, { passive: true });

return () => window.removeEventListener('scroll', handleScroll);
}, [scrollActiveRef.current, totalCount, offset]);
}, [scrollActiveRef.current, totalCount, skip]);
};

export default useInfiniteScroll;
14 changes: 6 additions & 8 deletions client/src/modules/dashboard/components/MemberLists/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const MemberLists = () => {
const [selectedMember, setSelectedMember] = useState<IMember>();
useEffect(() => {
if (!members.length) {
dispatch(fetchMembers({ limit: 6, offset: 0 }));
dispatch(fetchMembers({ limit: 6, skip: 0 }));
}
}, []);

Expand All @@ -31,15 +31,13 @@ const MemberLists = () => {
setEditModalOpen(true);
};



useInfiniteScroll({
totalCount: meta?.count || 0,
limit: 6,
offset: members.length,
fetchAction: ({ limit, offset }) => {
skip: members.length,
fetchAction: ({ limit, skip }) => {
if (!paginationLoading && !loading) {
dispatch(fetchMembers({ limit, offset }));
dispatch(fetchMembers({ limit, skip }));
}
},
});
Expand Down Expand Up @@ -73,8 +71,8 @@ const MemberLists = () => {
<Spinner className='mt-40' />
) : (
<div className='max-w-6xl px-5 mx-auto relative'>
{members.map((member, index) => {
return <List onSelect={handleSelectMember} key={index} member={member} />;
{members.map((member) => {
return <List onSelect={handleSelectMember} key={member._id} member={member} />;
})}
{paginationLoading ? <Spinner className='mt-10' /> : null}
</div>
Expand Down
6 changes: 3 additions & 3 deletions client/src/reducers/membersReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const memebersSlice = createSlice({
} else {
const meta: IMeta = {
count: 1,
offset: 1,
skip: 1,
};
state.meta = meta;
}
Expand Down Expand Up @@ -56,9 +56,9 @@ const memebersSlice = createSlice({
},
});

export const fetchMembers = createAsyncThunk('members/fetch', async ({ limit, offset }: { limit: number; offset: number }) => {
export const fetchMembers = createAsyncThunk('members/fetch', async ({ limit, skip }: { limit: number; skip: number }) => {
process.env.NODE_ENV !== 'production' && (await sleep(500));
const response = await getAllMembers({ limit, offset });
const response = await getAllMembers({ limit, skip });
return response;
});

Expand Down
9 changes: 1 addition & 8 deletions client/src/types/Meta.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
export interface IMeta {
count: number;
offset: number;
skip: number;
limit?: number;
totalPages?: number;
page?: number;
pagingCounter?: number;
hasPrevPage?: boolean;
hasNextPage?: boolean;
prevPage?: number | null;
nextPage?: number | null;
}
30 changes: 13 additions & 17 deletions server/common/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,20 @@ const findOne = async (modelName, request) => {
return model;
};

const getWithPagination = async (modelName, { limit, offset }: { page: number; limit: number; offset: number }) => {
const mongoModel = mongoose.models[modelName] as any;
const myCustomLabels = {
totalDocs: 'count',
docs: 'result',
meta: 'meta',
};
const options = {
sort: { createdAt: -1 },
limit: limit,
customLabels: myCustomLabels,
offset: offset,
const getWithPagination = async (modelName, { limit, skip }: { page: number; limit: number; skip: number }) => {
const mongoModel = mongoose.models[modelName];

const totalCount = await mongoModel.count();
const result = await mongoModel.find().sort({ createdAt: -1 }).skip(skip).limit(limit).exec();

return {
result: result,
meta: {
limit,
skip,
count: totalCount,
},
};
const model = await mongoModel.paginate({}, options);
if (model == null) {
throw new Error('Product not found by the id: ');
}
return model;
};

export { save, update, deleteById, getById, getAll, getWithPagination, findOne };
4 changes: 2 additions & 2 deletions server/controllers/members/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ const deleteHandler = async (req, res, next) => {
};

const getHandler = async (req, res, next) => {
const { page = 1, limit = 10, offset = 0 } = req.query;
const { page = 1, limit = 10, skip = 0 } = req.query;
try {
const data = await get({ page, limit, offset });
const data = await get({ page, limit, skip });
res.status(200).send(data);
} catch (error) {
return next(error, req, res);
Expand Down
17 changes: 10 additions & 7 deletions server/core/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,18 @@ const connectWithDb = async (): Promise<void> => {
const memberData = await getAllMembers();
if (!memberData.length) {
console.log('Connected to MongoDB');
await Promise.all(
memberJson.map(async (member) => {
await save({
...(member as any),
for (let i = 0; i < memberJson.length; i++) {
create(() =>
save({
...(memberJson[i] as any),
uid: 'CM-' + randomId(6),
});
})
);
})
);
}
console.log('Seeded members');
}
};

const create = (fn) => new Promise((resolve) => setTimeout(() => resolve(fn()), 100));

export default connectWithDb;
2 changes: 0 additions & 2 deletions server/models/member/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Schema, model } from 'mongoose';
import mongoosePaginate from 'mongoose-paginate-v2';

type MembershipType = 'VIP' | 'CHILDREN' | 'WOMEN' | 'PLAYER' | 'FOREIGNER' | 'NORMAL';

Expand Down Expand Up @@ -46,7 +45,6 @@ const schema = new Schema<IMember>(
{ timestamps: true }
);

schema.plugin(mongoosePaginate);
const Member = model<IMember>('Member', schema);

export default Member;
14 changes: 0 additions & 14 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"express": "^4.17.3",
"joi": "^17.6.0",
"jsonwebtoken": "^8.5.1",
"mongoose-paginate-v2": "^1.6.2",
"multer": "^1.4.4"
}
}
4 changes: 2 additions & 2 deletions server/services/member/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import { NotFound } from '../../common/errors';

const modelName = 'Member';

const get = async ({ page, limit, offset }: { page: number; limit: number; offset: number }) => {
const result = await getWithPagination(modelName, { page, limit, offset });
const get = async ({ page, limit, skip }: { page: number; limit: number; skip: number }) => {
const result = await getWithPagination(modelName, { page, limit, skip });
return result;
};

Expand Down
Loading

0 comments on commit ec83cb8

Please sign in to comment.