Skip to content

Commit

Permalink
refactor: cred-def controller APIs (#661)
Browse files Browse the repository at this point in the history
* refactor: get all cred defs api

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

* refactor: cred def controller apis

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

* resolved comments

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

* refactor: update import

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

---------

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>
Signed-off-by: KulkarniShashank <shashank.kulkarni@ayanworks.com>
  • Loading branch information
bhavanakarwade authored and KulkarniShashank committed Sep 11, 2024
1 parent cd20554 commit 53beca8
Show file tree
Hide file tree
Showing 8 changed files with 116 additions and 122 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Controller, Logger, Post, Body, UseGuards, Get, Query, HttpStatus, Res, Param, UseFilters, ParseUUIDPipe, BadRequestException } from '@nestjs/common';
import { CredentialDefinitionService } from './credential-definition.service';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiUnauthorizedResponse, ApiForbiddenResponse, ApiQuery } from '@nestjs/swagger';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiUnauthorizedResponse, ApiForbiddenResponse } from '@nestjs/swagger';
import { ApiResponseDto } from 'apps/api-gateway/src/dtos/apiResponse.dto';
import { UnauthorizedErrorDto } from 'apps/api-gateway/src/dtos/unauthorized-error.dto';
import { ForbiddenErrorDto } from 'apps/api-gateway/src/dtos/forbidden-error.dto';
import { User } from '../authz/decorators/user.decorator';
import { AuthGuard } from '@nestjs/passport';
import IResponseType, { IResponse } from '@credebl/common/interfaces/response.interface';
import { IResponse } from '@credebl/common/interfaces/response.interface';
import { ResponseMessages } from '@credebl/common/response-messages';
import { Response } from 'express';
import { GetAllCredDefsDto } from './dto/get-all-cred-defs.dto';
Expand All @@ -31,90 +31,94 @@ export class CredentialDefinitionController {

@Get('/orgs/:orgId/cred-defs/:credDefId')
@ApiOperation({
summary: 'Get an existing credential definition by Id',
description: 'Get an existing credential definition by Id'
summary: 'Get credential definition by credential definition Id',
description: 'Get credential definition details by credential definition Id'
})
@ApiResponse({ status: HttpStatus.CREATED, description: 'Success', type: ApiResponseDto })
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER, OrgRoles.MEMBER)
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
async getCredentialDefinitionById(
@Param('orgId') orgId: string,
@Param('orgId', new ParseUUIDPipe({exceptionFactory: (): Error => { throw new BadRequestException(ResponseMessages.organisation.error.invalidOrgId); }})) orgId: string,
@Param('credDefId') credentialDefinitionId: string,
@Res() res: Response
): Promise<object> {
): Promise<Response> {
const credentialsDefinitionDetails = await this.credentialDefinitionService.getCredentialDefinitionById(credentialDefinitionId, orgId);
const credDefResponse: IResponseType = {
const credDefResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.credentialDefinition.success.fetch,
data: credentialsDefinitionDetails.response
data: credentialsDefinitionDetails
};
return res.status(HttpStatus.OK).json(credDefResponse);
}

@Get('/verifiation/cred-defs/:schemaId')
@ApiOperation({
summary: 'Get an existing credential definitions by schema Id',
description: 'Get an existing credential definitions by schema Id'
summary: 'Get all credential definitions by schema Id',
description: 'Get all credential definitions by schema Id for verification'
})
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
@UseGuards(AuthGuard('jwt'))
async getCredentialDefinitionBySchemaId(
@Param('schemaId') schemaId: string,
@Res() res: Response
): Promise<object> {
): Promise<Response> {

const credentialsDefinitions = await this.credentialDefinitionService.getCredentialDefinitionBySchemaId(schemaId);
const credDefResponse: IResponseType = {
const credDefResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.credentialDefinition.success.fetch,
data: credentialsDefinitions.response
data: credentialsDefinitions
};
return res.status(HttpStatus.OK).json(credDefResponse);
}

@Get('/orgs/:orgId/cred-defs')
@ApiOperation({
summary: 'Fetch all credential definitions of provided organization id with pagination',
description: 'Fetch all credential definitions from metadata saved in database of provided organization id.'
summary: 'Fetch all credential definitions by organization Id',
description: 'Fetch all credential definitions of provided organization Id with pagination'
})
@ApiQuery(
{ name: 'pageNumber', required: false }
)
@ApiQuery(
{ name: 'searchByText', required: false }
)
@ApiQuery(
{ name: 'pageSize', required: false }
)
@ApiQuery(
{ name: 'sorting', required: false }
)
@ApiQuery(
{ name: 'sortByValue', required: false }
)
@ApiQuery(
{ name: 'revocable', required: false }
)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER, OrgRoles.MEMBER)
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
async getAllCredDefs(
@Param('orgId') orgId: string,
@Param('orgId', new ParseUUIDPipe({exceptionFactory: (): Error => { throw new BadRequestException(ResponseMessages.organisation.error.invalidOrgId); }})) orgId: string,
@Query() getAllCredDefs: GetAllCredDefsDto,
@User() user: IUserRequestInterface,
@Res() res: Response
): Promise<object> {
): Promise<Response> {
const credentialsDefinitionDetails = await this.credentialDefinitionService.getAllCredDefs(
getAllCredDefs,
user,
orgId
);
const credDefResponse: IResponseType = {
const credDefResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.credentialDefinition.success.fetch,
data: credentialsDefinitionDetails.response
data: credentialsDefinitionDetails
};
return res.status(HttpStatus.OK).json(credDefResponse);
}

@Get('/orgs/:orgId/bulk/cred-defs')
@ApiOperation({
summary: 'Fetch all credential definitions for bulk opeartion',
description: 'Retrieve all credential definitions for bulk operation'
})
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER)
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
async getAllCredDefAndSchemaForBulkOperation(
@Param('orgId', new ParseUUIDPipe({exceptionFactory: (): Error => { throw new BadRequestException(ResponseMessages.organisation.error.invalidOrgId); }})) orgId: string,
@Res() res: Response
): Promise<Response> {
const credentialsDefinitionDetails = await this.credentialDefinitionService.getAllCredDefAndSchemaForBulkOperation(orgId);
const credDefResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.credentialDefinition.success.fetch,
data: credentialsDefinitionDetails
};
return res.status(HttpStatus.CREATED).json(credDefResponse);
}

@Post('/orgs/:orgId/cred-defs')
@ApiOperation({
summary: 'Sends a credential definition to ledger',
Expand All @@ -126,7 +130,7 @@ export class CredentialDefinitionController {
async createCredentialDefinition(
@User() user: IUserRequestInterface,
@Body() credDef: CreateCredentialDefinitionDto,
@Param('orgId', new ParseUUIDPipe({exceptionFactory: (): Error => { throw new BadRequestException(`Invalid format for orgId`); }})) orgId: string,
@Param('orgId', new ParseUUIDPipe({exceptionFactory: (): Error => { throw new BadRequestException(ResponseMessages.organisation.error.invalidOrgId); }})) orgId: string,
@Res() res: Response
): Promise<Response> {

Expand All @@ -140,24 +144,4 @@ export class CredentialDefinitionController {
return res.status(HttpStatus.CREATED).json(credDefResponse);
}

@Get('/orgs/:orgId/bulk/cred-defs')
@ApiOperation({
summary: 'Fetch all credential definition for bulk opeartion',
description: 'Fetch all credential definition from metadata saved in database for bulk opeartion.'
})
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER)
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
async getAllCredDefAndSchemaForBulkOperation(
@Param('orgId') orgId: string,
@Res() res: Response
): Promise<object> {
const credentialsDefinitionDetails = await this.credentialDefinitionService.getAllCredDefAndSchemaForBulkOperation(orgId);
const credDefResponse: IResponseType = {
statusCode: HttpStatus.OK,
message: ResponseMessages.credentialDefinition.success.fetch,
data: credentialsDefinitionDetails.response
};
return res.status(HttpStatus.CREATED).json(credDefResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { CreateCredentialDefinitionDto } from './dto/create-cred-defs.dto';
import { BaseService } from '../../../../libs/service/base.service';
import { IUserRequestInterface } from '../interfaces/IUserRequestInterface';
import { GetAllCredDefsDto } from '../dtos/get-cred-defs.dto';
import { ICredDef, ICredDefs, ICredentialDefinition } from './interfaces';
import { ICredDefData } from '@credebl/common/interfaces/cred-def.interface';

@Injectable()
export class CredentialDefinitionService extends BaseService {
Expand All @@ -14,29 +16,28 @@ export class CredentialDefinitionService extends BaseService {
super('CredentialDefinitionService');
}

createCredentialDefinition(credDef: CreateCredentialDefinitionDto, user: IUserRequestInterface): Promise<object> {
const payload = { credDef, user };

createCredentialDefinition(credDef: CreateCredentialDefinitionDto, user: IUserRequestInterface): Promise<ICredDef> {
const payload = { credDef, user };
return this.sendNatsMessage(this.credDefServiceProxy, 'create-credential-definition', payload);
}

getCredentialDefinitionById(credentialDefinitionId: string, orgId: string): Promise<{ response: object }> {
getCredentialDefinitionById(credentialDefinitionId: string, orgId: string): Promise<object> {
const payload = { credentialDefinitionId, orgId };
return this.sendNats(this.credDefServiceProxy, 'get-credential-definition-by-id', payload);
return this.sendNatsMessage(this.credDefServiceProxy, 'get-credential-definition-by-id', payload);
}

getAllCredDefs(credDefSearchCriteria: GetAllCredDefsDto, user: IUserRequestInterface, orgId: string): Promise<{ response: object }> {
getAllCredDefs(credDefSearchCriteria: GetAllCredDefsDto, user: IUserRequestInterface, orgId: string): Promise<ICredDefData> {
const payload = { credDefSearchCriteria, user, orgId };
return this.sendNats(this.credDefServiceProxy, 'get-all-credential-definitions', payload);
return this.sendNatsMessage(this.credDefServiceProxy, 'get-all-credential-definitions', payload);
}

getCredentialDefinitionBySchemaId(schemaId: string): Promise<{ response: object }> {
getCredentialDefinitionBySchemaId(schemaId: string): Promise<ICredDefs> {
const payload = { schemaId };
return this.sendNats(this.credDefServiceProxy, 'get-all-credential-definitions-by-schema-id', payload);
return this.sendNatsMessage(this.credDefServiceProxy, 'get-all-credential-definitions-by-schema-id', payload);
}

getAllCredDefAndSchemaForBulkOperation(orgId:string): Promise<{ response: object }> {
getAllCredDefAndSchemaForBulkOperation(orgId:string): Promise<ICredentialDefinition> {
const payload = { orgId };
return this.sendNats(this.credDefServiceProxy, 'get-all-schema-cred-defs-for-bulk-operation', payload);
return this.sendNatsMessage(this.credDefServiceProxy, 'get-all-schema-cred-defs-for-bulk-operation', payload);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import { ApiProperty } from '@nestjs/swagger';
export class CreateCredentialDefinitionDto {

@ApiProperty({ 'example': 'default' })
@IsDefined({ message: 'Tag is required.' })
@IsNotEmpty({ message: 'Please provide a tag' })
@IsString({ message: 'Tag id should be string' })
tag: string;

@ApiProperty({ 'example': 'WgWxqztrNooG92RXvxSTWv:2:schema_name:1.0' })
@IsDefined({ message: 'schemaLedgerId is required.' })
@IsNotEmpty({ message: 'Please provide a schema id' })
@IsString({ message: 'Schema id should be string' })
schemaLedgerId: string;

orgId: string;

@ApiProperty({ required: false })
Expand Down
27 changes: 26 additions & 1 deletion apps/api-gateway/src/credential-definition/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,29 @@ export interface IOrgAgentInterface {
walletName: string;
agentsTypeId: string;
orgId: string;
}
}
export interface ICredDef {
id: string;
createDateTime: string;
createdBy: string;
credentialDefinitionId: string;
tag: string;
schemaLedgerId: string;
schemaId: string;
revocable: boolean;
orgId: string;
}

export interface ICredDefs extends ICredDef{
lastChangedDateTime: string;
lastChangedBy: string;
}

export interface ICredentialDefinition {
credentialDefinitionId: string;
schemaCredDefName: string;
schemaName: string;
schemaVersion: string;
schemaAttributes: string;
credentialDefinition: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { GetAllCredDefsPayload, GetCredDefBySchemaId } from './interfaces/creat
import { CreateCredDefPayload, GetCredDefPayload } from './interfaces/create-credential-definition.interface';
import { credential_definition } from '@prisma/client';
import { CredDefSchema } from './interfaces/credential-definition.interface';

import { ICredDefDetails } from '@credebl/common/interfaces/cred-def.interface';
@Controller('credential-definitions')
export class CredentialDefinitionController {
private logger = new Logger();
Expand All @@ -26,24 +26,7 @@ export class CredentialDefinitionController {
}

@MessagePattern({ cmd: 'get-all-credential-definitions' })
async getAllCredDefs(payload: GetAllCredDefsPayload): Promise<{
totalItems: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
nextPage: number;
previousPage: number;
lastPage: number;
data: {
createDateTime: Date;
createdBy: string;
credentialDefinitionId: string;
tag: string;
schemaLedgerId: string;
schemaId: string;
orgId: string;
revocable: boolean;
}[]
}> {
async getAllCredDefs(payload: GetAllCredDefsPayload): Promise<ICredDefDetails> {
return this.credDefService.getAllCredDefs(payload);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import { credential_definition } from '@prisma/client';
import { ResponseMessages } from '@credebl/common/response-messages';
import { CreateCredDefAgentRedirection, CredDefSchema, GetCredDefAgentRedirection } from './interfaces/credential-definition.interface';
import { map } from 'rxjs/operators';
import { OrgAgentType } from '@credebl/enum/enum';
import { OrgAgentType, SortValue } from '@credebl/enum/enum';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { ICredDefDetails } from '@credebl/common/interfaces/cred-def.interface';
@Injectable()
export class CredentialDefinitionService extends BaseService {
constructor(
Expand Down Expand Up @@ -201,6 +202,7 @@ export class CredentialDefinitionService extends BaseService {
if (credDefResponse.response.resolutionMetadata.error) {
throw new NotFoundException(ResponseMessages.credentialDefinition.error.credDefIdNotFound);
}

return credDefResponse;
} catch (error) {
this.logger.error(`Error retrieving credential definition with id ${payload.credentialDefinitionId}`);
Expand All @@ -219,6 +221,7 @@ export class CredentialDefinitionService extends BaseService {
async _getCredentialDefinitionById(payload: GetCredDefAgentRedirection): Promise<{
response: string;
}> {

try {
const pattern = {
cmd: 'agent-get-credential-definition'
Expand Down Expand Up @@ -246,24 +249,7 @@ export class CredentialDefinitionService extends BaseService {
}
}

async getAllCredDefs(payload: GetAllCredDefsPayload): Promise<{
totalItems: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
nextPage: number;
previousPage: number;
lastPage: number;
data: {
createDateTime: Date;
createdBy: string;
credentialDefinitionId: string;
tag: string;
schemaLedgerId: string;
schemaId: string;
orgId: string;
revocable: boolean;
}[]
}> {
async getAllCredDefs(payload: GetAllCredDefsPayload): Promise<ICredDefDetails> {
try {
const { credDefSearchCriteria, orgId } = payload;
const response = await this.credentialDefinitionRepository.getAllCredDefs(credDefSearchCriteria, orgId);
Expand Down Expand Up @@ -303,7 +289,7 @@ export class CredentialDefinitionService extends BaseService {
try {
const payload = {
orgId,
sortValue: 'ASC',
sortValue: SortValue.ASC,
credDefSortBy: 'id'
};

Expand Down
Loading

0 comments on commit 53beca8

Please sign in to comment.