class-transformer#plainToClass TypeScript Examples
The following examples show how to use
class-transformer#plainToClass.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: write-events-prepublish.service.ts From nestjs-geteventstore with MIT License | 6 votes |
// transform to dto each event and validate it
async validate(events: T[]) {
let errors = [];
for (const event of events) {
this.logger.debug(`Validating ${event.constructor.name}`);
// @todo JDM class-transformer is not converting data property !
// (metadata is working, so it might be related to inheritance)
const validateEvent: any = plainToClass(event.constructor as any, event);
errors = [...errors, ...(await validate(validateEvent))];
}
return errors;
}
Example #2
Source File: controller.base.template.ts From amplication with Apache License 2.0 | 6 votes |
// @ts-ignore
@common.UseInterceptors(AclFilterResponseInterceptor)
@nestAccessControl.UseRoles({
resource: ENTITY_NAME,
action: "read",
possession: "any",
})
@common.Get()
@swagger.ApiOkResponse({ type: [ENTITY] })
@swagger.ApiForbiddenResponse()
@ApiNestedQuery(FIND_MANY_ARGS)
async FIND_MANY_ENTITY_FUNCTION(
@common.Req() request: Request
): Promise<ENTITY[]> {
const args = plainToClass(FIND_MANY_ARGS, request.query);
return this.service.findMany({
...args,
select: SELECT,
});
}
Example #3
Source File: interface.ts From cloudformation-cli-typescript-plugin with Apache License 2.0 | 6 votes |
public static deserialize<T extends BaseDto>(
this: new () => T,
jsonData: Dict,
options: ClassTransformOptions = {}
): T {
if (jsonData == null) {
return null;
}
return plainToClass(this, jsonData, {
enableImplicitConversion: false,
excludeExtraneousValues: true,
...options,
});
}
Example #4
Source File: helpers.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
validateBody = async <T>(
obj: ClassType<T>,
body: string | null,
validateOptions?: ValidationOptions
): Promise<T> => {
const raw: any = plainToClass(obj, JSON.parse(body ?? '{}'));
await validateOrReject(raw, {
...validateOptions,
whitelist: true,
forbidUnknownValues: true
});
return raw;
}
Example #5
Source File: mentor.controller.ts From codeclannigeria-backend with MIT License | 6 votes |
@Get('submissions')
@HttpCode(HttpStatus.OK)
@ApiResponse({ status: HttpStatus.OK, type: PagedListSubmissionDto })
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.MENTOR)
@ApiBearerAuth()
@ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
async getSubmissions(
@Query() query: FindDto,
@Req() req: Request
): Promise<PagedListSubmissionDto> {
const { skip, limit, search, opts } = query;
const conditions = search && JSON.parse(search);
const options = opts && JSON.parse(opts);
const mentorId = req.user['userId'];
const submissions = await this.SubmissionModel.find(
{ ...conditions, mentor: mentorId },
null,
{ ...options, limit, skip }
);
const items = plainToClass(SubmissionDto, submissions, {
enableImplicitConversion: true,
excludeExtraneousValues: true
}) as any;
const totalCount = await this.mentorService.countSubmissions(mentorId);
return { totalCount, items };
}
Example #6
Source File: Model.entity.repository.ts From cyan with MIT License | 6 votes |
private mapping(row: any, repositoryInfo?: RepositoryInfo, prefix?: string): T {
const x = plainToClass(
(repositoryInfo || this.repositoryInfo).target,
Object.keys(row)
.filter(e => !prefix || e.startsWith(`${prefix}${joinSeparator}`))
.reduce((p, c) => {
const col = !prefix ? c : c.substring(prefix.length + 1);
if (!col.includes(joinSeparator)) {
p[col] = row[c];
} else {
const [join] = col.split(joinSeparator);
if (!p[join]) {
p[join] = this.mapping(
row,
(repositoryInfo || this.repositoryInfo).oneToOneRelations[join].repository,
!prefix ? join : `${prefix}_${join}`
);
}
}
return p;
}, {})
);
return x;
}
Example #7
Source File: role-controller.ts From ddd-cqrs-es-aws-sam with MIT License | 6 votes |
listHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
initApplication();
try {
_applicationContainer.logger.debug('Role List Handler Event: %o', event);
const roleListDto = Object.assign(new RoleListDto(), event.queryStringParameters) as RoleListDto;
await validateOrReject(plainToClass(RoleListDto, roleListDto));
const repository = _applicationContainer.get<ProjectionRepository<RoleProjection>>(DynamoProjectionRepository);
const roleProjections = await repository.list(process.env.projectionRolesTable, roleListDto);
return { statusCode: HttpStatus.OK, body: JSON.stringify(roleProjections) };
} catch (error) {
return ApplicationController.handleError(_applicationContainer, error);
}
}
Example #8
Source File: FileSystemStoredFile.ts From nestjs-form-data with MIT License | 6 votes |
static async create(originalName, encoding, mimetype, stream: NodeJS.ReadableStream, config: FormDataInterceptorConfig): Promise<FileSystemStoredFile> {
await mkdirp.native(config.fileSystemStoragePath);
const filePath = path.resolve(config.fileSystemStoragePath, FileSystemStoredFile.makeFileNameWithSalt(originalName));
return new Promise<FileSystemStoredFile>((res, rej) => {
const outStream = fs.createWriteStream(filePath);
let size: number = 0;
stream.on('data', (chunk) => size += chunk.length);
outStream.on('error', rej);
outStream.on('finish', () => {
const file: FileSystemStoredFile = plainToClass(FileSystemStoredFile, {
originalName,
encoding,
mimetype,
path: filePath,
size,
});
res(file);
});
stream.pipe(outStream);
});
}
Example #9
Source File: map-api-result.ts From etherspot-sdk with MIT License | 6 votes |
/**
* @ignore
*/
export function mapApiResult<T extends {}, K extends keyof T>(
data: T,
models?: {
[key in K]: { new (...args: any): T[K] };
},
): T {
const mappedData = { ...data };
if (models) {
const keys = Object.keys(models);
for (const key of keys) {
const plain = mappedData[key];
const model = models[key];
if (model && plain && !(plain instanceof model)) {
mappedData[key] = plainToClass(model, plain);
}
}
}
return mappedData;
}
Example #10
Source File: appUtils.ts From SFDX-Data-Move-Utility-Desktop-App with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static async execForceOrgList(): Promise<{ orgs: Array<ForceOrgListResult>, commandOutput: string }> {
try {
//let responseString = SfdxUtils.execSfdx("force:org:list --json", undefined);
let response = await AppUtils.execSfdxCommand("force:org:list --json", undefined);
let jsonObject = JSON.parse(response.commandOutput);
let responseObject = plainToClass(ForceOrgListCommandResponse, jsonObject, {
enableImplicitConversion: true,
excludeExtraneousValues: true
});
if (responseObject.status == 0) {
return {
orgs: [
...responseObject.result.nonScratchOrgs,
...responseObject.result.scratchOrgs.map(x => {
x.isScratchOrg = true;
return x;
})],
commandOutput: response.commandOutput
};
}
} catch (ex) {
}
return {
orgs: new Array<ForceOrgListResult>(),
commandOutput: RESOURCES.Home_Error_ExecuteSFDXFailed
};
}
Example #11
Source File: data_source_mapper.ts From Deep-Lynx with MIT License | 6 votes |
// Reprocess takes a data source and will remove all previous data ingested by it, then attempt
// to queue up all data it's received in the past for reprocessing. Generally used by someone who
// has made changes to the ontology and mappings, this insures the data they have in the system
// is the latest
public async ReprocessDataSource(dataSourceID: string): Promise<Result<boolean>> {
// first we delete the old nodes/edges - don't wait though, the sql handles not deleting
// any records created after the time you start this statement
void super.runAsTransaction(...this.deleteDataStatement(dataSourceID));
// now we stream process this part because a data source might have a large number of
// records and we really don't want to read that into memory - we also don't wait
// for this to complete as it could take a night and a day
const queue = await QueueFactory();
void PostgresAdapter.Instance.Pool.connect((err, client, done) => {
const stream = client.query(new QueryStream(this.listStagingForSourceStreaming(dataSourceID)));
stream.on('data', (data) => {
void queue.Put(Config.process_queue, plainToClass(DataStaging, data as object));
});
stream.on('end', () => done());
// we pipe to devnull because we need to trigger the stream and don't
// care where the data ultimately ends up
stream.pipe(devnull({objectMode: true}));
});
return Promise.resolve(Result.Success(true));
}