class-transformer#ClassConstructor TypeScript Examples
The following examples show how to use
class-transformer#ClassConstructor.
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: map-class.ts From Discord-Bot-TypeScript-Template with MIT License | 9 votes |
export function mapClass(cls: ClassConstructor<object>): RequestHandler {
return async (req: Request, res: Response, next: NextFunction) => {
// Map to class
let obj: object = plainToInstance(cls, req.body);
// Validate class
let errors = await validate(obj, {
skipMissingProperties: true,
whitelist: true,
forbidNonWhitelisted: false,
forbidUnknownValues: true,
});
if (errors.length > 0) {
res.status(400).send({ error: true, errors: formatValidationErrors(errors) });
return;
}
// Set validated class to locals
res.locals.input = obj;
next();
};
}
Example #2
Source File: classes.ts From epicgames-freegames-node with MIT License | 6 votes |
notifierSubtypes: {
value: ClassConstructor<NotifierConfig>;
name: string;
}[] = [
{ value: EmailConfig, name: NotificationType.EMAIL },
{ value: DiscordConfig, name: NotificationType.DISCORD },
{ value: PushoverConfig, name: NotificationType.PUSHOVER },
{ value: LocalConfig, name: NotificationType.LOCAL },
{ value: TelegramConfig, name: NotificationType.TELEGRAM },
{ value: AppriseConfig, name: NotificationType.APPRISE },
{ value: GotifyConfig, name: NotificationType.GOTIFY },
]
Example #3
Source File: validateObject.ts From next-api-decorators with MIT License | 6 votes |
export async function validateObject(
cls: ClassConstructor<any>,
value: Record<string, string>,
validatorOptions?: ValidationPipeOptions
): Promise<any> {
const classValidator = loadPackage('class-validator');
if (!classValidator) {
return value;
}
const classTransformer = loadPackage('class-transformer');
if (!classTransformer) {
return value;
}
const bodyValue = classTransformer.plainToClass(cls, value, {
enableImplicitConversion: true,
...validatorOptions?.transformOptions
});
const validationErrors = await classValidator.validate(bodyValue, {
enableDebugMessages: process.env.NODE_ENV === 'development',
...validatorOptions
});
if (validationErrors.length) {
const flattenedErrors = flattenValidationErrors(validationErrors);
throw new BadRequestException(flattenedErrors[0], flattenedErrors);
}
return bodyValue;
}
Example #4
Source File: handler.ts From next-api-decorators with MIT License | 4 votes |
async function runMainLayer(
this: TypedPropertyDescriptor<any>,
target: object,
propertyKey: string | symbol,
originalHandler: any,
req: NextApiRequest,
res: NextApiResponse
): Promise<void> {
const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_TOKEN, target.constructor, propertyKey);
const parameterDecorators: MetaParameter[] = (
Reflect.getMetadata(PARAMETER_TOKEN, target.constructor, propertyKey) ?? []
).sort((a: MetaParameter, b: MetaParameter) => a.index - b.index);
const classHeaders: Map<string, string> | undefined = Reflect.getMetadata(HEADER_TOKEN, target.constructor);
const methodHeaders: Map<string, string> | undefined = Reflect.getMetadata(
HEADER_TOKEN,
target.constructor,
propertyKey
);
const parameterTypes: ClassConstructor<any>[] = Reflect.getMetadata('design:paramtypes', target, propertyKey);
const isDownloadable: boolean = Reflect.getMetadata(HTTP_DOWNLOAD_TOKEN, target.constructor, propertyKey) ?? false;
const parameters = await Promise.all(
parameterDecorators.map(async ({ location, name, pipes, index, fn }) => {
if (location === 'custom') {
return fn?.call(null, req);
}
const paramType =
index < parameterTypes.length &&
typeof parameterTypes[index] === 'function' &&
/^class\s/.test(Function.prototype.toString.call(parameterTypes[index]))
? parameterTypes[index]
: undefined;
let returnValue = getParameterValue(req, res, {
location,
name,
index
});
if (pipes && pipes.length) {
for (const pipeFn of pipes) {
returnValue = pipeFn.name
? // Bare pipe function. i.e: `ParseNumberPipe`
await pipeFn.call(null, null).call(null, returnValue, { name, metaType: paramType })
: // Pipe with options. i.e: `ParseNumberPipe({ nullable: false })`
await pipeFn.call(null, returnValue, {
name,
metaType: paramType
});
}
}
return returnValue;
})
);
classHeaders?.forEach((value, name) => res.setHeader(name, value));
methodHeaders?.forEach((value, name) => res.setHeader(name, value));
const returnValue = await originalHandler.call(this, ...parameters);
if (returnValue instanceof ServerResponse || isResponseSent(res)) {
return;
}
res.status(httpCode ?? (returnValue != null ? 200 : 204));
if (returnValue instanceof Stream) {
returnValue.pipe(res);
} else if (
isDownloadable &&
typeof returnValue === 'object' &&
'filename' in returnValue &&
'contents' in returnValue
) {
res.setHeader('Content-Disposition', `attachment; filename="${returnValue.filename}"`);
if ('contentType' in returnValue) {
res.setHeader('Content-Type', returnValue.contentType);
}
if (returnValue.contents instanceof Stream) {
returnValue.contents.pipe(res);
} else {
res.send(returnValue.contents);
}
} else {
res.send(returnValue ?? null);
}
}