Skip to content

Commit

Permalink
Push 29 mai tutorat avec Robin Offset Limit Pagination Try text
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan7594 committed May 29, 2024
1 parent 5242c76 commit 2ddf080
Show file tree
Hide file tree
Showing 3 changed files with 152 additions and 67 deletions.
172 changes: 114 additions & 58 deletions server/controllers/mediatheque.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,66 +7,66 @@ import { Controller } from './controller';

const mediathequeController = new Controller('/mediatheque');

mediathequeController.post({ path: '' }, async (req, res) => {
const filters: Array<Filter[]> = req?.body?.filters || [];
const offset = req?.query?.offset || 0;

let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

filters.map((filter, index) => {
subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
new Brackets((qb) => {
filter.map(({ table, column, values }, subQueryIndex) => {
let condition = '';
values.map((_value, valueIndex) => {
condition += valueIndex > 0 ? ' or ' : '(';
condition += `${table}.${column} = ${values[valueIndex]}`;
});
condition += ')';
qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
});
}),
);
});
const activities = await subQueryBuilder
.limit(6)
.offset(offset as number)
const getMedias = async (result: any[], queryBuilder, offset, limit) => {

Check warning on line 10 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
const activities: Array<any> = await queryBuilder

Check warning on line 11 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
.limit(limit ? parseInt(limit) : undefined)
.offset(offset ? parseInt(offset) : undefined)
.getMany();
res.send(activities);
});

mediathequeController.post({ path: '/count' }, async (req, res) => {
try {
const filters: Array<Filter[]> = req?.body?.filters || [];

let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

filters.map((filter, index) => {
subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
new Brackets((qb) => {
filter.map(({ table, column, values }, subQueryIndex) => {
let condition = '';
values.map((_value, valueIndex) => {
condition += valueIndex > 0 ? ' or ' : '(';
condition += `${table}.${column} = ${values[valueIndex]}`;
});
condition += ')';
qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
});
console.log('offset');

Check failure on line 15 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log(offset);

Check failure on line 16 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log('limit');

Check failure on line 17 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log(limit);

Check failure on line 18 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log('activities');

Check failure on line 19 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log(activities);

Check failure on line 20 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
const activitiesMediaFinder = activities.map(({ id, content, subType, type, villageId, userId }) => {
const result = { id, subType, type, villageId, userId, medias: [] };
if (content.game) {
content.game.map(({ inputs }) =>
inputs.map((input) => {
if (input.type === 3 || input.type === 4) {
result.medias.push({ type: input.type === 3 ? 'image' : 'video', value: input.selectedValue });
}
}),
);
});
const count = await subQueryBuilder.getMany();
res.status(200).json({ count });
} catch (error) {
console.error('Error fetching count:', error);
res.status(500).json({ error: 'Internal Server Error' });
} else {
content.map(({ type, value }) => {
const wantedTypes = ['image', 'video', 'sound'];
if (wantedTypes.includes(type)) {
result.medias.push({ type, value });
}
});
}
return result;
});

const activitiesWithMediaOnly = activitiesMediaFinder.filter((a) => a.medias.length > 0);
result = [...result, ...activitiesWithMediaOnly];

if (!limit) {
return { activities: result, offset: offset + limit };
}
});
const oldLength = result.length;
result = result.slice(0, limit);
console.log('resultPOPOPO');

Check failure on line 50 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log(result);

Check failure on line 51 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
const newLength = result.length;
const hasReduced = oldLength !== newLength;

mediathequeController.post({ path: '/all' }, async (req, res) => {
const filters: Array<Filter[]> = req?.body?.filters || [];
if (result.length < limit) {
if (activities.length < limit) {
return { activities: result, offset: offset + limit };
}
const lastActivityInResultIndex = activities.findIndex((a) => a.id === result[result.length - 1]);
const newOffset = hasReduced ? offset + lastActivityInResultIndex + 1 : offset + limit;
return await getMedias(result, queryBuilder, newOffset, limit);
}
return { activities: result, offset: offset + limit };
};

mediathequeController.post({ path: '' }, async (req, res) => {
const filters: Array<Filter[]> = req?.body?.filters || [];
const offset: string | undefined = req?.query?.offset as string;
const limit: string | undefined = req?.query?.limit as string;
let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

filters.map((filter, index) => {
Expand All @@ -84,12 +84,68 @@ mediathequeController.post({ path: '/all' }, async (req, res) => {
}),
);
});
const activities = await subQueryBuilder.getMany();

const filterActivities = activities.map((activities) => activities);
console.log(filterActivities);
// if (limit) {
// subQueryBuilder = subQueryBuilder.limit(parseInt(limit));
// }
const activitiesWithMediaOnly = await getMedias([], subQueryBuilder, offset ? parseInt(offset) : undefined, limit ? parseInt(limit) : undefined);
console.log('activitiesWithMediaOnly');

Check failure on line 92 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
console.log(activitiesWithMediaOnly);

Check failure on line 93 in server/controllers/mediatheque.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

res.send(activities);
res.send(activitiesWithMediaOnly);
});

// mediathequeController.post({ path: '/count' }, async (req, res) => {
// try {
// const filters: Array<Filter[]> = req?.body?.filters || [];

// let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

// filters.map((filter, index) => {
// subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
// new Brackets((qb) => {
// filter.map(({ table, column, values }, subQueryIndex) => {
// let condition = '';
// values.map((_value, valueIndex) => {
// condition += valueIndex > 0 ? ' or ' : '(';
// condition += `${table}.${column} = ${values[valueIndex]}`;
// });
// condition += ')';
// qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
// });
// }),
// );
// });
// const count = await subQueryBuilder.getMany();
// res.status(200).json({ count });
// } catch (error) {
// console.error('Error fetching count:', error);
// res.status(500).json({ error: 'Internal Server Error' });
// }
// });

// mediathequeController.post({ path: '/all' }, async (req, res) => {
// const filters: Array<Filter[]> = req?.body?.filters || [];

// let subQueryBuilder = AppDataSource.getRepository(Activity).createQueryBuilder('activity').innerJoin('activity.user', 'user');

// filters.map((filter, index) => {
// subQueryBuilder = subQueryBuilder[index === 0 ? 'where' : 'orWhere'](
// new Brackets((qb) => {
// filter.map(({ table, column, values }, subQueryIndex) => {
// let condition = '';
// values.map((_value, valueIndex) => {
// condition += valueIndex > 0 ? ' or ' : '(';
// condition += `${table}.${column} = ${values[valueIndex]}`;
// });
// condition += ')';
// qb[subQueryIndex === 0 ? 'where' : 'andWhere'](condition);
// });
// }),
// );
// });
// const activities = await subQueryBuilder.getMany();

// });

export { mediathequeController };
9 changes: 5 additions & 4 deletions src/api/mediatheque/mediatheque.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { useQuery } from 'react-query';
import { axiosRequest } from 'src/utils/axiosRequest';
import type { Filter } from 'types/mediatheque.type';

async function getMediatheque(params: { offset: number | null; filters: Array<Filter[]> }) {
const { offset, filters } = params;
async function getMediatheque(params: { filters: Array<Filter[]>; offset?: number; limit?: number }) {
const { offset, filters, limit } = params;

return (
await axiosRequest({
Expand All @@ -13,6 +13,7 @@ async function getMediatheque(params: { offset: number | null; filters: Array<Fi
url: '/mediatheque',
params: {
offset: offset,
limit: limit,
},
data: {
filters: filters,
Expand All @@ -21,6 +22,6 @@ async function getMediatheque(params: { offset: number | null; filters: Array<Fi
).data;
}

export const useGetMediatheque = (offset: number | null, filters: Array<Filter[]>) => {
return useQuery(['Mediatheque', offset, filters], () => getMediatheque({ filters, offset }));
export const useGetMediatheque = (filters: Array<Filter[]>, offset?: number, limit?: number) => {
return useQuery(['Mediatheque', filters, offset, limit], () => getMediatheque({ filters, offset, limit }));
};
38 changes: 33 additions & 5 deletions src/contexts/mediathequeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type MediathequeProviderProps = {
type MediathequeContextType = {
filters: Array<Filter[]>;
setFilters: Dispatch<SetStateAction<Array<Filter[]>>>;
offset: number;
filtered: [];
setOffset: Dispatch<SetStateAction<number>>;
count: number;
Expand All @@ -23,6 +24,7 @@ const MediathequeContext: React.Context<MediathequeContextType> = createContext<
filters: [],
setFilters: () => {},
filtered: [],
offset: 0,
setOffset: () => {},
count: 0,
allFiltered: [],
Expand All @@ -31,13 +33,39 @@ const MediathequeContext: React.Context<MediathequeContextType> = createContext<
export const MediathequeProvider: FC<MediathequeProviderProps> = ({ children }) => {
const [filters, setFilters] = useState<Array<Filter[]>>([[]]);
const [offset, setOffset] = useState<number>(0);
const { data: filtered } = useGetMediatheque(offset, filters);
const { data: count } = useGetMediathequeCount(filters);
const { data: allFiltered } = useGetMediathequeAll(filters);
console.log(allFiltered);
// const r = useGetMediatheque(filters, offset, 2);
// console.log(r);
const { data } = useGetMediatheque(filters, offset, 6);
console.log(data);
const { data: allData } = useGetMediatheque(filters);

if (!data) {
return null;
}
// const {
// data: { activities: filtered, offset: newOffset },
// } = useGetMediatheque(filters, offset, 6);
// const { data: count } = useGetMediathequeCount(filters);

// const {
// data: { activities: allFiltered },
// } = useGetMediatheque(filters);

return (
<MediathequeContext.Provider value={{ filters, setFilters, filtered, setOffset, count, allFiltered }}>{children}</MediathequeContext.Provider>
<MediathequeContext.Provider
value={{
filters,
offset: data?.newOffset,
setFilters,
filtered: data?.activities,
setOffset,
count: allData?.activities?.length,
allFiltered: allData?.activities,
}}
>
{/* <MediathequeContext.Provider value={{ filters, offset: 0, setFilters, filtered: [], setOffset, count: 12, allFiltered: [] }}> */}
{children}
</MediathequeContext.Provider>
);
};

Expand Down

0 comments on commit 2ddf080

Please sign in to comment.