Skip to content

Commit

Permalink
feat: clean up and fix types
Browse files Browse the repository at this point in the history
  • Loading branch information
Kronos66 committed Nov 17, 2024
1 parent ca0742c commit c19c6a5
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 91 deletions.
10 changes: 2 additions & 8 deletions admin/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ export const getApiClient = once((fetch: ReturnType<typeof getFetchClient>) => (
async query(id: number | string, filters: any) {
const queryFilters = !isEmpty(filters) ? `?${stringify(filters, { encode: false })}` : '';
const response = await fetch.get(`/${URL_PREFIX}/moderate/single/${id}${queryFilters}`);
return commentDetailsSchema.parseAsync(response.data).catch((error) => {
console.log('error', error);
throw error;
});
return commentDetailsSchema.parseAsync(response.data);
},
},
approve(id: number) {
Expand Down Expand Up @@ -113,10 +110,7 @@ export const getApiClient = once((fetch: ReturnType<typeof getFetchClient>) => (
},
async query(queryParams?: Record<string, string>) {
const response = await fetch.get(`/${URL_PREFIX}/moderate/reports${queryParams ? `?${stringify(queryParams, { encode: false })}` : ''}`);
return reportsSchema.parseAsync(response.data).catch((error) => {
console.log('error', error);
throw error;
});
return reportsSchema.parseAsync(response.data);
},
},
resolve({ id, reportId }: { id: number, reportId: number }) {
Expand Down
1 change: 0 additions & 1 deletion admin/src/components/ReportsTableRow/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export const ReportsTableRow: FC<ReportsTableRowProps> = ({ item, isChecked, onS
const onCheckedChange = () => {
onSelectionChange(item.id);
};
console.log('isChecked', isChecked);

return (
<Tr>
Expand Down
13 changes: 0 additions & 13 deletions admin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ export default {
permissions: pluginPermissions.access,
});

console.log('app', app);


app.createSettingSection(
{
id: pluginId,
Expand All @@ -45,16 +42,6 @@ export default {
},
],
);
//
// app.addReducers(reducers);
// app.registerPlugin({
// id: pluginId,
// initializer: Initializer,
// isReady: false,
// name,
// });
//
// registerCustomFields(app);
},

registerTrads: async function ({ locales = [] }: { locales: string[] }) {
Expand Down
84 changes: 34 additions & 50 deletions server/src/controllers/utils/parsers.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
import { ToBeFixed } from '../../@types-v5';
import PluginError from '../../utils/error';
import { client } from '../../validators/api';

const assertNotEmpty: <T>(
value: T | null | undefined,
customError?: Error,
) => asserts value is T = (value, customError) => {
if (value) {
return value;
}
// Define base interface for filters
interface BaseFilters {
$or?: Record<string, any>[];
content?: any;
authorName?: any;
createdAt?: any;
approvalStatus?: any;
[key: string]: any;
}

throw (
customError ?? new PluginError(400, 'Non-empty value expected, empty given')
);
// Union type of all possible input types
type FlatInputParams = client.FindAllFlatSchema | client.FindAllInHierarchyValidatorSchema | client.FindAllPerAuthorValidatorSchema;

const assertNotEmpty = <T>(value: T | null | undefined, customError?: Error): asserts value is T => {
if (value) return;
throw customError ?? new PluginError(400, 'Non-empty value expected, empty given');
};
// TODO: TBD with @Mateusz
export const flatInput = <T>(payload: T): T => {

export const flatInput = <T extends FlatInputParams>(payload: T): T => {
const {
relation,
sort,
pagination,
fields,
omit,
filters,
filters = {} as BaseFilters,
populate = {},
filterBy,
filterByValue,
} = payload as any;
console.log('query', filters);
relation,
pagination,
} = payload as FlatInputParams & {
filters?: BaseFilters;
populate?: Record<string, boolean | { populate: boolean }>;
pagination?: client.FindAllFlatSchema['pagination'];
relation?: client.FindAllFlatSchema['relation'];
};

const orOperator = (filters?.$or || []).filter(
(_: ToBeFixed) => !Object.keys(_).includes('removed'),
const orOperator = (filters.$or || []).filter(
(item) => !Object.keys(item).includes('removed'),
);

let basePopulate = {
Expand All @@ -41,12 +49,12 @@ export const flatInput = <T>(payload: T): T => {
populate: {
authorUser: true,
...populate,
},
} as { authorUser: boolean | { populate: boolean }, [key: string]: boolean | { populate: boolean } },
},
};

// Cover case when someone wants to populate author instead of authorUser
if (populate.author) {
if ('author' in populate) {
const { author, ...restPopulate } = populate;
basePopulate = {
...restPopulate,
Expand All @@ -57,36 +65,12 @@ export const flatInput = <T>(payload: T): T => {
populate: {
authorUser: author,
...restPopulate,
},
} as { authorUser: boolean | { populate: boolean }, [key: string]: boolean | { populate: boolean } },
},
};
}

if (filterBy === 'DATE_CREATED') {
const date = new Date(filterByValue);

if (!filterByValue || Number.isNaN(+date)) {
throw new PluginError(400, 'Invalid date specified in "filterByValue"');
}

const start = date.setHours(0, 0, 0, 0);
const end = date.setHours(23, 59, 59, 999);

filters.createdAt = {
$between: [start, end],
};
}

if (filterBy === 'APPROVAL_STATUS') {
assertNotEmpty(
filterByValue,
new PluginError(400, 'Empty "filterByValue" parameter'),
);

filters.approvalStatus = filterByValue;
}

console.log('filters', filters);
const updatedFilters = { ...filters };

return {
...payload,
Expand All @@ -103,5 +87,5 @@ export const flatInput = <T>(payload: T): T => {
sort,
fields,
omit,
} as unknown as T;
} as T;
};
2 changes: 1 addition & 1 deletion server/src/services/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default ({ strapi }: StrapiContext) => {
});

const relatedEntities = await this.getCommonService().findRelatedEntitiesFor(results);
console.log("🚀 ~ findAll ~ relatedEntities:", relatedEntities)

return {
pagination,
result: results.map((_) => this.getCommonService().sanitizeCommentEntity(_, [], []))
Expand Down
2 changes: 1 addition & 1 deletion server/src/services/common.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const commonService = ({ strapi }: StrapiContext) => ({
limit: limit || PAGE_SIZE,
offset: skip || 0,
});
console.log('entries', entries);

let paginationData: Pagination = undefined;
if (pagination?.withCount) {
paginationData = await getCommentRepository(strapi).findWithCount({ where: { ...filters, ...(locale ? { locale } : {}) } }).then((result) => result.pagination);
Expand Down
42 changes: 26 additions & 16 deletions server/src/services/utils/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import { Comment, CommentWithRelated } from '../../validators/repositories';

declare var strapi: CoreStrapi;

interface StrapiAuthorUser {
id: Id;
username: string;
email: string;
avatar?: string | object;
[key: string]: unknown;
}

export const buildNestedStructure = (
entities: Array<Comment | CommentWithRelated>,
id: Id | null = null,
Expand Down Expand Up @@ -62,8 +70,7 @@ export const filterOurResolvedReports = (item: Comment): Comment =>
: item;

export const buildAuthorModel = (
// TODO
item: any,
item: Comment | CommentWithRelated,
blockedAuthorProps: Array<string>,
fieldsToPopulate: Array<string> = [],
): Comment => {
Expand All @@ -77,20 +84,18 @@ export const buildAuthorModel = (
} = item;
let author: CommentAuthor = {} as CommentAuthor;

if (authorUser) {
if (authorUser && typeof authorUser !== 'string') {
const user = authorUser as StrapiAuthorUser;
author = fieldsToPopulate.reduce(
(prev, curr) => ({
...prev,
[curr]: authorUser[curr],
[curr]: user[curr],
}),
{
id: authorUser.id,
name: authorUser.username,
email: authorUser.email,
avatar:
isString(authorUser.avatar) || isObject(authorUser.avatar)
? authorUser.avatar
: undefined,
id: user.id,
name: user.username,
email: user.email,
avatar: user.avatar,
},
);
} else if (authorId) {
Expand All @@ -110,7 +115,7 @@ export const buildAuthorModel = (
return {
...rest,
author,
};
} as Comment;
};

export const buildConfigQueryProp = (
Expand All @@ -125,12 +130,17 @@ export const resolveUserContextError = (user?: AdminUser | StrapiUser): PluginEr
}
};

export const getAuthorName = (author: StrapiAdmin): string => {
type AuthorNameProps = {
lastname?: string;
firstname?: string;
username?: string;
};

export const getAuthorName = (author: AuthorNameProps): string => {
const { lastname, username, firstname } = author;

if (lastname)
if (lastname && firstname) {
return `${firstname} ${lastname}`;
else
return username || firstname;
}
return username || firstname || '';
};
1 change: 0 additions & 1 deletion server/src/utils/PluginError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export default class PluginError extends Error {
super();
this.name = 'Strapi:Plugin:Comments';
this.status = status || 500;
console.log('message', message);
this.message = message || 'Internal error';
this.payload = payload;

Expand Down

0 comments on commit c19c6a5

Please sign in to comment.