Separation of Concerns in API
Where applicable, an endpoint that handles different data flows should be separated in endpoints that handle the different cases, e.g.
@Get('credential/:id?')
@ApiQuery({ name: 'page', required: false })
@ApiQuery({ name: 'pageSize', required: false })
@ApiQuery({ name: 'state', required: false })
@ApiQuery({ name: 'isReceived', required: false })
@ApiQuery({ name: 'threadId', required: false })
async getCredential(
@Param() params: GetCredentialParams,
@Query() query: GetCredentialQuery,
@Res() response: Response,
) {
let res: ResponseType;
try {
if (params.id) {
const result = await this.attestationService.findCredentialById(
params.id,
);
if (result) {
res = {
statusCode: HttpStatus.OK,
message: 'Credential fetch successfully',
data: result,
};
} else {
response.status(HttpStatus.NOT_FOUND);
res = {
statusCode: HttpStatus.NOT_FOUND,
message: 'No Data found',
};
}
} else if (query.threadId) {
const result = await this.attestationService.findCredentialByThreadId(
query.threadId,
);
if (result) {
res = {
statusCode: HttpStatus.OK,
message: 'Credential fetch successfully',
data: result,
};
} else {
response.status(HttpStatus.NOT_FOUND);
res = {
statusCode: HttpStatus.NOT_FOUND,
message: 'No Data found',
};
}
} else if (query.isReceived) {
const result = await this.attestationService.findReceivedCredentials();
if (result && result.length > 0) {
res = {
statusCode: HttpStatus.OK,
message: 'Credential fetch successfully',
data: result,
};
} else {
response.status(HttpStatus.NOT_FOUND);
res = {
statusCode: HttpStatus.NOT_FOUND,
message: 'No Data found',
};
}
} else {
const result = await this.attestationService.findCredential(
query.pageSize ? parseInt(query.pageSize, 10) : 10,
query.page ? parseInt(query.page, 10) : 0,
query.state ? query.state : false,
);
if (result) {
if (result[0]) {
res = {
statusCode: HttpStatus.OK,
message: 'Credential fetch successfully',
data: {
count: result[0],
records: result[1],
},
};
} else {
response.status(HttpStatus.NOT_FOUND);
res = {
statusCode: HttpStatus.NOT_FOUND,
message: 'No Data found',
};
}
} else {
response.status(HttpStatus.INTERNAL_SERVER_ERROR);
res = {
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'Something went wrong please try again',
};
}
}
return response.send(res);
} catch (error) {
if (error instanceof PrismaClientUnknownRequestError) {
throw new InternalServerErrorException(error.message);
} else {
throw new InternalServerErrorException(error);
}
}
}
This endpoint should be separated in an endpoint that returns a single credential, based on a condition and another endpoint that returns all credentials in the wallet of the OCM (getAllCredentials for example).