Skip to content

Commit

Permalink
Merge pull request #241 from souravbhowmik1999/paginationNew
Browse files Browse the repository at this point in the history
PS-1349 User list API Error handling should be proper for wrongly passed filters combination
  • Loading branch information
vijaykhollam authored Jul 10, 2024
2 parents 81e8194 + c2a13f7 commit 0755eef
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 113 deletions.
73 changes: 1 addition & 72 deletions src/adapters/hasura/user.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class HasuraUserService implements IServicelocator {
checkUser(body: any, response: any) {
throw new Error("Method not implemented.");
}
public async findUserDetails(userID: any, username: String,tenantId:string) {
public async findUserDetails(userID: any, username: String, tenantId: string) {

}
public async getUsersDetailsById(userData: UserData, response: any) { }
Expand Down Expand Up @@ -550,78 +550,7 @@ export class HasuraUserService implements IServicelocator {
userSearchDto: UserSearchDto,
request: any
) {
// function to search users within the user tables
try {
let offset = 0;
if (userSearchDto.page > 1) {
offset = userSearchDto.limit * userSearchDto.page - 1;
}

const filters = userSearchDto.filters;

//add tenantid
filters["tenantId"] = { _eq: tenantId ? tenantId : "" };

Object.keys(userSearchDto.filters).forEach((item) => {
Object.keys(userSearchDto.filters[item]).forEach((e) => {
if (!e.startsWith("_")) {
filters[item][`_${e}`] = filters[item][e];
delete filters[item][e];
}
});
});

const data = {
query: `query SearchUser($filters:Users_bool_exp,$limit:Int, $offset:Int) {
Users_aggregate(where:$filters, limit: $limit, offset: $offset,) {
aggregate {
count
}
}
Users(where:$filters, limit: $limit, offset: $offset,) {
userId
name
username
email
district
state
address
pincode
mobile
dob
role
tenantId
createdAt
updatedAt
createdBy
updatedBy
}
}`,
variables: {
limit: userSearchDto.limit,
offset: offset,
filters: userSearchDto.filters,
},
};

const config = {
method: "post",
url: process.env.REGISTRYHASURA,
headers: {
Authorization: request.headers.authorization,
"x-hasura-admin-secret": process.env.REGISTRYHASURAADMINSECRET,
"Content-Type": "application/json",
},
data: data,
};

const response = await this.axios(config);

return response;
} catch (e) {
console.error(e);
return e;
}
}

public async deleteUserById(userId) { }
Expand Down
39 changes: 17 additions & 22 deletions src/adapters/postgres/fields-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ export class PostgresFieldsService implements IServicelocatorfields {
HttpStatus.OK, 'Field Values fetched successfully.')
}


async findDynamicOptions(tableName, whereClause?: {}) {
let query: string;
let result;
Expand Down Expand Up @@ -451,7 +452,7 @@ export class PostgresFieldsService implements IServicelocatorfields {
return result;
}

async getUserIdUsingStateDistBlock(stateDistBlockData: any) {
async filterUserUsingCustomFields(stateDistBlockData: any) {
let searchKey = [];
let whereCondition = ` WHERE `;
let index = 0;
Expand Down Expand Up @@ -483,6 +484,8 @@ export class PostgresFieldsService implements IServicelocatorfields {
}

async getFieldValuesData(id: string, context: string, contextType?: string, getFields?: string[], requiredFieldOptions?: Boolean) {
requiredFieldOptions = true;

let customField;
let fieldsArr = [];
const [filledValues, customFields] = await Promise.all([
Expand All @@ -506,34 +509,26 @@ export class PostgresFieldsService implements IServicelocatorfields {
value: fieldValue || '',
};

if (requiredFieldOptions == true) {
customField['options'] = data?.fieldParams?.['options'] || {}
}

if (data?.sourceDetails) {
//If the value of the "dependsOn" field is true, do not retrieve values from the "custom table", "fieldParams" and the JSON file also.
if (data?.dependsOn === false) {
if (data?.sourceDetails?.source === 'table') {
let dynamicOptions = await this.findDynamicOptions(data?.sourceDetails?.table);
customField.options = dynamicOptions;
} else if (data?.sourceDetails?.source === 'jsonFile') {
const filePath = path.join(
process.cwd(),
`${data?.sourceDetails?.filePath}`,
);
customField = JSON.parse(readFileSync(filePath, 'utf-8'));
}
if (requiredFieldOptions == true && data?.dependsOn === false) {
if (data?.sourceDetails?.source === 'table') {
let dynamicOptions = await this.findDynamicOptions(data?.sourceDetails?.table);
customField.options = dynamicOptions;
} else if (data?.sourceDetails?.source === 'jsonFile') {
const filePath = path.join(
process.cwd(),
`${data?.sourceDetails?.filePath}`,
);
customField = JSON.parse(readFileSync(filePath, 'utf-8'));
} else {
customField.options = [];
}
} else {
if (requiredFieldOptions == true) {
customField.options = data?.fieldParams?.['options'] || null;
}
} else {
customField.options = null;
}
fieldsArr.push(customField);
}
}

return fieldsArr;
}

Expand Down
35 changes: 19 additions & 16 deletions src/adapters/postgres/user-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,12 @@ export class PostgresUserService implements IServicelocator {

async findAllUserDetails(userSearchDto) {

let { limit, page, filters, exclude, sort } = userSearchDto;
let offset = 0;
let { limit, offset, filters, exclude, sort } = userSearchDto;
let excludeCohortIdes;
let excludeUserIdes;
if (page > 1) {
offset = parseInt(limit) * (page - 1);
}

offset = offset ? `OFFSET ${offset}` : '';
limit = limit ? `LIMIT ${limit}` : ''
let result = {
getUserDetails: [],
};
Expand Down Expand Up @@ -141,14 +140,20 @@ export class PostgresUserService implements IServicelocator {
orderingCondition = `ORDER BY U."${sort[0]}" ${sort[1]}`;
}

let getUserIdUsingStateDistBlock
let getUserIdUsingCustomFields;

//If source config in source details from fields table is not exist then return false
if (Object.keys(searchCustomFields).length > 0) {
getUserIdUsingStateDistBlock = await this.fieldsService.getUserIdUsingStateDistBlock(searchCustomFields);
getUserIdUsingCustomFields = await this.fieldsService.filterUserUsingCustomFields(searchCustomFields);
if (getUserIdUsingCustomFields.length == 0) {
return false;
}
}

if (getUserIdUsingStateDistBlock && getUserIdUsingStateDistBlock.length > 0) {
const stateDistBlockUserIds = getUserIdUsingStateDistBlock.map(userId => `'${userId}'`).join(',');
whereCondition += `${index > 0 ? ' AND ' : ''} U."userId" IN (${stateDistBlockUserIds})`;

if (getUserIdUsingCustomFields && getUserIdUsingCustomFields.length > 0) {
const userIdsDependsOnCustomFields = getUserIdUsingCustomFields.map(userId => `'${userId}'`).join(',');
whereCondition += `${index > 0 ? ' AND ' : ''} U."userId" IN (${userIdsDependsOnCustomFields})`;
index++;
}

Expand All @@ -173,8 +178,7 @@ export class PostgresUserService implements IServicelocator {
INNER JOIN public."UserRolesMapping" UR
ON UR."userId" = U."userId"
INNER JOIN public."Roles" R
ON R."roleId" = UR."roleId" ${whereCondition} GROUP BY U."userId", R."name" ${orderingCondition}`

ON R."roleId" = UR."roleId" ${whereCondition} GROUP BY U."userId", R."name" ${orderingCondition} ${offset} ${limit}`

let userDetails = await this.usersRepository.query(query);

Expand All @@ -184,12 +188,13 @@ export class PostgresUserService implements IServicelocator {
let contextType = userData.role.toUpperCase();
let isRequiredFieldOptions = false;
let customFields = await this.fieldsService.getFieldValuesData(userData.userId, context, contextType, userSearchDto.fields, isRequiredFieldOptions);
userData['customFields'] = customFields
userData['customFields'] = customFields;
result.getUserDetails.push(userData);
}
} else {
result.getUserDetails.push(userDetails);
}

return result;
}

Expand Down Expand Up @@ -430,14 +435,12 @@ export class PostgresUserService implements IServicelocator {
userCreateDto.createdBy = decoded?.sub
userCreateDto.updatedBy = decoded?.sub
// const emailId = decoded?.email;
console.log(userCreateDto.createdBy, "cfeatbby");


let email = await this.usersRepository.findOne({
where: { userId: userCreateDto.createdBy }, select
: ['email']
})
console.log(email, "email");


if (userCreateDto.customFields && userCreateDto.customFields.length > 0) {
await this.validateCustomField(userCreateDto, response, apiId);
Expand Down
2 changes: 1 addition & 1 deletion src/cohortMembers/dto/cohortMembers-search.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class CohortMembersSearchDto {
@ApiProperty({
type: Object,
description: "Filters",
example: { cohortId: "", userId: "", role:"" }, // Adding example for Swagger
example: { cohortId: "", userId: "", role: "" }, // Adding example for Swagger
})
@ApiPropertyOptional()
filters: { cohortId?: string; userId?: string; role?: string }; // Define cohortId and userId properties
Expand Down
4 changes: 2 additions & 2 deletions src/user/dto/user-search.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,11 @@ export class UserSearchDto {

@ApiProperty({
type: Number,
description: "Page",
description: "Offset",
})
@Expose()
@IsOptional()
page: number;
offset: number;

@ApiProperty({
type: setFilters,
Expand Down

0 comments on commit 0755eef

Please sign in to comment.