8000 feat: update schema details and add alias in schema table by pallavighule · Pull Request #1129 · credebl/platform · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: update schema details and add alias in schema table #1129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/api-gateway/src/dtos/create-schema.dto.ts
10000
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,13 @@ export class GenericSchemaDTO {
@IsNotEmpty({ message: 'Type is required' })
type: SchemaTypeEnum;

@ApiPropertyOptional()
@Transform(({ value }) => trim(value))
@IsOptional()
@IsString({ message: 'alias must be a string' })
@IsNotEmpty({ message: 'alias is required' })
alias: string;

@ApiProperty({
type: Object,
oneOf: [
Expand Down
23 changes: 23 additions & 0 deletions apps/api-gateway/src/schema/dtos/update-schema-dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';

export class UpdateSchemaDto {
@ApiProperty()
@Transform(({ value }) => value?.trim())
@IsNotEmpty({ message: 'Alias is required.' })
@IsString({ message: 'Alias must be in string format.' })
alias: string;

@ApiProperty()
@Transform(({ value }) => value?.trim())
@IsNotEmpty({ message: 'schemaLedgerId is required.' })
@IsString({ message: 'schemaLedgerId must be in string format.' })
schemaLedgerId: string;

@ApiPropertyOptional()
@IsOptional()
@Transform(({ value }) => value?.trim())
@IsUUID('4')
orgId?: string;
}
29 changes: 27 additions & 2 deletions apps/api-gateway/src/schema/schema.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Controller, Logger, Post, Body, HttpStatus, UseGuards, Get, Query, BadRequestException, Res, UseFilters, Param, ParseUUIDPipe } from '@nestjs/common';
import { Controller, Logger, Post, Body, HttpStatus, UseGuards, Get, Query, BadRequestException, Res, UseFilters, Param, ParseUUIDPipe, Put } from '@nestjs/common';
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable camelcase */
import { ApiOperation, ApiResponse, ApiTags, ApiBearerAuth, ApiForbiddenResponse, ApiUnauthorizedResponse, ApiQuery, ApiExtraModels, ApiBody, getSchemaPath } from '@nestjs/swagger';
import { ApiOperation, ApiResponse, ApiTags, ApiBearerAuth, ApiForbiddenResponse, ApiUnauthorizedResponse, ApiQuery, ApiExcludeEndpoint } from '@nestjs/swagger';
import { SchemaService } from './schema.service';
import { AuthGuard } from '@nestjs/passport';
import { ApiResponseDto } from '../dtos/apiResponse.dto';
Expand All @@ -21,6 +21,7 @@ import { GenericSchemaDTO } from '../dtos/create-schema.dto';
import { CustomExceptionFilter } from 'apps/api-gateway/common/exception-handler';
import { CredDefSortFields, SortFields } from '@credebl/enum/enum';
import { TrimStringParamPipe } from '@credebl/common/cast.helper';
import { UpdateSchemaDto } from './dtos/update-schema-dto';

@UseFilters(CustomExceptionFilter)
@Controller('orgs')
Expand Down Expand Up @@ -186,4 +187,28 @@ export class SchemaController {
};
return res.status(HttpStatus.CREATED).json(finalResponse);
}

/**
* Update an schema alias
* @param updateSchemaDto The details of the schema to be updated
* @returns Success message
*/
@Put('/schema')
@ApiOperation({ summary: 'Update schema', description: 'Update the details of the schema' })
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
@ApiExcludeEndpoint()
@ApiBearerAuth()
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN)
@UseGuards(AuthGuard('jwt'))
async updateSchema(@Body() updateSchemaDto: UpdateSchemaDto, @Res() res: Response): Promise<Response> {

await this.appService.updateSchema(updateSchemaDto);

const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.schema.success.update
};
return res.status(HttpStatus.OK).json(finalResponse);
}

}
8 changes: 8 additions & 0 deletions apps/api-gateway/src/schema/schema.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { ICredDefWithPagination, ISchemaData, ISchemasWithPagination } from '@cr
import { GetCredentialDefinitionBySchemaIdDto } from './dtos/get-all-schema.dto';
import { NATSClient } from '@credebl/common/NATSClient';

import { UpdateSchemaResponse } from 'apps/ledger/src/schema/interfaces/schema.interface';
import { UpdateSchemaDto } from './dtos/update-schema-dto';

@Injectable()
export class SchemaService extends BaseService {

Expand Down Expand Up @@ -36,4 +39,9 @@ export class SchemaService extends BaseService {
const payload = { schemaSearchCriteria, user };
return this.natsClient.sendNatsMessage(this.schemaServiceProxy, 'get-cred-def-list-by-schemas-id', payload);
}

updateSchema(schemaDetails: UpdateSchemaDto): Promise<UpdateSchemaResponse> {
const payload = { schemaDetails };
return this.natsClient.sendNatsMessage(this.schemaServiceProxy, 'update-schema', payload);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface ISchema {
endorserWriteTxn?: string;
orgDid?: string;
type?: string;
alias?: string;
}

export interface IAttributeValue {
Expand Down
12 changes: 12 additions & 0 deletions apps/ledger/src/schema/interfaces/schema.interface.ts
< A3D4 td class="blob-code blob-code-addition js-file-line"> export interface UpdateSchemaResponse {
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export interface ICreateW3CSchema {
schemaType: JSONSchemaType;
}
export interface IGenericSchema {
alias:string;
type: SchemaTypeEnum;
schemaPayload: ICreateSchema | ICreateW3CSchema;
}
Expand Down Expand Up @@ -123,4 +124,15 @@ export interface ISchemasResult {
export interface ISchemasList {
schemasCount: number;
schemasResult: ISchemasResult[];
}


export interface IUpdateSchema {
alias: string;
schemaLedgerId: string;
orgId?: string;
}

count: number;
}
75 changes: 48 additions & 27 deletions apps/ledger/src/schema/repositories/schema.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { PrismaService } from '@credebl/prisma-service';
import { ledgers, org_agents, org_agents_type, organisation, Prisma, schema } from '@prisma/client';
import { ISchema, ISchemaExist, ISchemaSearchCriteria, ISaveSchema } from '../interfaces/schema-payload.interface';
import { ResponseMessages } from '@credebl/common/response-messages';
import { AgentDetails, ISchemasWithCount } from '../interfaces/schema.interface';
import { AgentDetails, ISchemasWithCount, IUpdateSchema, UpdateSchemaResponse } from '../interfaces/schema.interface';
import { SchemaType, SortValue } from '@credebl/enum/enum';
import { ICredDefWithCount, IPlatformSchemas } from '@credebl/common/interfaces/schema.interface';
import { ISchemaId } from '../schema.interface';
Expand Down Expand Up @@ -38,7 +38,8 @@ export class SchemaRepository {
orgId: schemaResult.orgId,
ledgerId: schemaResult.ledgerId,
type: schemaResult.type,
isSchemaArchived: false
isSchemaArchived: false,
alias: schemaResult.alias
}
});
return saveResult;
Expand Down Expand Up @@ -119,8 +120,9 @@ export class SchemaRepository {
publisherDid: true,
orgId: true,
issuerId: true,
alias: true,
organisation: {
select:{
select: {
name: true,
userOrgRoles: {
select: {
Expand Down Expand Up @@ -299,11 +301,11 @@ export class SchemaRepository {
try {
const { ledgerId, schemaType, searchByText, sortField, sortBy, pageSize, pageNumber } = payload;
let schemaResult;
/**
* This is made so because the default pageNumber is set to 1 in DTO,
/**
* This is made so because the default pageNumber is set to 1 in DTO,
* If there is any 'searchByText' field, we ignore the pageNumbers and search
* in all available records.
*
*
* Because in that case pageNumber would be insignificant.
*/
if (searchByText) {
Expand All @@ -316,7 +318,8 @@ export class SchemaRepository {
{ name: { contains: searchByText, mode: 'insensitive' } },
{ version: { contains: searchByText, mode: 'insensitive' } },
{ schemaLedgerId: { contains: searchByText, mode: 'insensitive' } },
{ issuerId: { contains: searchByText, mode: 'insensitive' } }
{ issuerId: { contains: searchByText, mode: 'insensitive' } },
{ alias: { contains: searchByText, mode: 'insensitive' } }
]
},
select: {
Expand All @@ -328,9 +331,10 @@ export class SchemaRepository {
isSchemaArchived: true,
createdBy: true,
publisherDid: true,
orgId: true, // This field can be null
orgId: true, // This field can be null
issuerId: true,
type: true
type: true,
alias: true
},
orderBy: {
[sortField]: SortValue.DESC === sortBy ? SortValue.DESC : SortValue.ASC
Expand All @@ -356,9 +360,10 @@ export class SchemaRepository {
isSchemaArchived: true,
createdBy: true,
publisherDid: true,
orgId: true, // This field can be null
orgId: true, // This field can be null
issuerId: true,
type: true
type: true,
alias: true
},
orderBy: {
[sortField]: SortValue.DESC === sortBy ? SortValue.DESC : SortValue.ASC
Expand All @@ -376,7 +381,7 @@ export class SchemaRepository {
});

// Handle null orgId in the response
const schemasWithDefaultOrgId = schemaResult.map(schema => ({
const schemasWithDefaultOrgId = schemaResult.map((schema) => ({
...schema,
orgId: schema.orgId || null // Replace null orgId with 'N/A' or any default value
}));
Expand Down Expand Up @@ -429,21 +434,23 @@ export class SchemaRepository {
}
}

async schemaExist(payload: ISchemaExist): Promise<{
id: string;
createDateTime: Date;
createdBy: string;
lastChangedDateTime: Date;
lastChangedBy: string;
name: string;
version: string;
attributes: string;
schemaLedgerId: string;
publisherDid: string;
issuerId: string;
orgId: string;
ledgerId: string;
}[]> {
async schemaExist(payload: ISchemaExist): Promise<
{
id: string;
createDateTime: Date;
createdBy: string;
lastChangedDateTime: Date;
lastChangedBy: string;
name: string;
version: string;
attributes: string;
schemaLedgerId: string;
publisherDid: string;
issuerId: string;
orgId: string;
ledgerId: string;
}[]
> {
try {
return this.prisma.schema.findMany({
where: {
Expand All @@ -456,4 +463,18 @@ export class SchemaRepository {
throw error;
}
}

async updateSchema(schemaDetails: IUpdateSchema): Promise<UpdateSchemaResponse> {
const { alias, schemaLedgerId, orgId } = schemaDetails;

try {
return await this.prisma.schema.updateMany({
where: orgId ? { schemaLedgerId, orgId } : { schemaLedgerId },
data: { alias }
});
} catch (error) {
this.logger.error(`Error in updating schema details: ${error}`);
throw error;
}
}
}
7 changes: 7 additions & 0 deletions apps/ledger/src/schema/schema.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
} from '@credebl/common/interfaces/schema.interface';
import { IschemaPayload } from './interfaces/schema.interface';
import { ISchemaId } from './schema.interface';
import { UpdateSchemaDto } from 'apps/api-gateway/src/schema/dtos/update-schema-dto';


@Controller('schema')
export class SchemaController {
Expand Down Expand Up @@ -96,4 +98,9 @@ export class SchemaController {
async getSchemaRecordBySchemaId(payload: {schemaId: string}): Promise<schema> {
return this.schemaService.getSchemaBySchemaId(payload.schemaId);
}

@MessagePattern({ cmd: 'update-schema' })
updateSchema(payload:{schemaDetails:UpdateSchemaDto}): Promise<object> {
return this.schemaService.updateSchema(payload.schemaDetails);
}
}
32 changes: 25 additions & 7 deletions apps/ledger/src/schema/schema.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { SchemaRepository } from './repositories/schema.repository';
import { Prisma, schema } from '@prisma/client';
import { ISaveSchema, ISchema, ISchemaCredDeffSearchInterface, ISchemaExist, ISchemaSearchCriteria, W3CCreateSchema } from './interfaces/schema-payload.interface';
import { ResponseMessages } from '@credebl/common/response-messages';
import { ICreateSchema, ICreateW3CSchema, IGenericSchema, IUserRequestInterface } from './interfaces/schema.interface';
import { ICreateSchema, ICreateW3CSchema, IGenericSchema, IUpdateSchema, IUserRequestInterface, UpdateSchemaResponse } from './interfaces/schema.interface';
import { CreateSchemaAgentRedirection, GetSchemaAgentRedirection, ISchemaId } from './schema.interface';
import { map } from 'rxjs/operators';
import { JSONSchemaType, LedgerLessConstant, LedgerLessMethods, OrgAgentType, SchemaType, SchemaTypeEnum } from '@credebl/enum/enum';
Expand Down Expand Up @@ -48,7 +48,7 @@ export class SchemaService extends BaseService {

const userId = user.id;
try {
const {schemaPayload, type} = schemaDetails;
const {schemaPayload, type, alias} = schemaDetails;

if (type === SchemaTypeEnum.INDY) {

Expand Down Expand Up @@ -247,7 +247,7 @@ export class SchemaService extends BaseService {
}
} else if (type === SchemaTypeEnum.JSON) {
const josnSchemaDetails = schemaPayload as unknown as ICreateW3CSchema;
const createW3CSchema = await this.createW3CSchema(orgId, josnSchemaDetails, user.id);
const createW3CSchema = await this.createW3CSchema(orgId, josnSchemaDetails, user.id, alias);
return createW3CSchema;
}
} catch (error) {
Expand All @@ -259,7 +259,7 @@ export class SchemaService extends BaseService {
}
}

async createW3CSchema(orgId:string, schemaPayload: ICreateW3CSchema, user: string): Promise<ISchemaData> {
async createW3CSchema(orgId:string, schemaPayload: ICreateW3CSchema, user: string, alias: string): Promise<ISchemaData> {
try {
let createSchema;

Expand Down Expand Up @@ -325,7 +325,7 @@ export class SchemaService extends BaseService {
createSchema.schemaUrl = `${process.env.SCHEMA_FILE_SERVER_URL}${createSchemaPayload.data.schemaId}`;
}

const storeW3CSchema = await this.storeW3CSchemas(createSchema, user, orgId, attributes);
const storeW3CSchema = await this.storeW3CSchemas(createSchema, user, orgId, attributes, alias);

if (!storeW3CSchema) {
throw new BadRequestException(ResponseMessages.schema.error.storeW3CSchema, {
Expand Down Expand Up @@ -524,7 +524,7 @@ export class SchemaService extends BaseService {
return W3CSchema;
}

private async storeW3CSchemas(schemaDetails, user, orgId, attributes): Promise <schema> {
private async storeW3CSchemas(schemaDetails, user, orgId, attributes, alias): Promise <schema> {
let ledgerDetails;
const schemaServerUrl = `${process.env.SCHEMA_FILE_SERVER_URL}${schemaDetails.schemaId}`;
const schemaRequest = await this.commonService
Expand Down Expand Up @@ -563,7 +563,8 @@ export class SchemaService extends BaseService {
publisherDid: schemaDetails.did,
orgId,
ledgerId: ledgerDetails.id,
type: SchemaType.W3C_Schema
type: SchemaType.W3C_Schema,
alias
};
const saveResponse = await this.schemaRepository.saveSchema(
storeSchemaDetails
Expand Down Expand Up @@ -928,4 +929,21 @@ export class SchemaService extends BaseService {
throw new RpcException(error.response ? error.response : error);
}
}


async updateSchema(schemaDetails:IUpdateSchema): Promise<UpdateSchemaResponse> {
try {
const schemaSearchResult = await this.schemaRepository.updateSchema(schemaDetails);

if (0 === schemaSearchResult?.count) {
throw new NotFoundException('Records with given condition not found');
}

return schemaSearchResult;
} catch (error) {
this.logger.error(`Error in updateSchema: ${error}`);
throw new RpcException(error.response ? error.response : error);
}
}

}
Loading
0