class-validator#validate TypeScript Examples
The following examples show how to use
class-validator#validate.
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: ValidatorRequest.ts From node-experience with MIT License | 6 votes |
static async handle(request: any)
{
const errors = await validate(request);
if (!_.isEmpty(errors))
{
throw new ErrorHttpException(StatusCode.HTTP_UNPROCESSABLE_ENTITY, { message: 'Failed Request.' }, errors);
}
}
Example #2
Source File: map-class.ts From Discord-Bot-TypeScript-Template with MIT License | 6 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 #3
Source File: local.strategy.ts From nest-js-boilerplate with MIT License | 6 votes |
async validate(req: ExpressRequest, email: string, password: string): Promise<ValidateUserOutput> {
const errors = await validate(new SignInDto(req.body)) as ValidationError[];
if (errors.length > 0) {
throw new ValidationExceptions(errors);
}
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
Example #4
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 #5
Source File: student.routes.ts From Typescript_TypeORM with Apache License 2.0 | 6 votes |
studentRouter.post('/', async (request, response) => {
try {
const repo = getRepository(Student);
const { key, name, email, discipline } = request.body;
const student = repo.create({
key,
name,
email,
discipline,
});
const errors = await validate(student);
if (errors.length === 0) {
const res = await repo.save(student);
return response.status(201).json(res);
}
return response.status(400).json(errors);
} catch (err) {
console.log('err.message :>> ', err.message);
return response.status(400).send();
}
});
Example #6
Source File: AuthController.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 6 votes |
static changePassword = async (req: Request, res: Response) => {
//Get ID from JWT
const id = res.locals.jwtPayload.userId;
//Get parameters from the body
const { oldPassword, newPassword } = req.body;
if (!(oldPassword && newPassword)) {
res.status(400).send();
return;
}
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail(id);
} catch (id) {
res.status(401).send();
return;
}
if (!user.checkIfUnencryptedPasswordIsValid(oldPassword)) {
res.status(401).send();
return;
}
user.password = newPassword;
const errors = await validate(user);
if (errors.length > 0) {
res.status(400).send(errors);
return;
}
user.hashPassword();
await userRepository.save(user);
res.status(204).send();
};
Example #7
Source File: AuthController.ts From mysql_node_angular with MIT License | 6 votes |
static changePassword = async (req: Request, res: Response) => {
const { userId } = res.locals.jwtPayload;
const { oldPassword, newPassword } = req.body;
if (!(oldPassword && newPassword)) {
res.status(400).json({ message: 'Old password & new password are required' });
}
const userRepository = getRepository(Users);
let user: Users;
try {
user = await userRepository.findOneOrFail(userId);
} catch (e) {
res.status(400).json({ message: 'Somenthing goes wrong!' });
}
if (!user.checkPassword(oldPassword)) {
return res.status(401).json({ message: 'Check your old Password' });
}
user.password = newPassword;
const validationOps = { validationError: { target: false, value: false } };
const errors = await validate(user, validationOps);
if (errors.length > 0) {
return res.status(400).json(errors);
}
// Hash password
user.hashPassword();
userRepository.save(user);
res.json({ message: 'Password change!' });
};
Example #8
Source File: products.controller.ts From rest-api.ts with MIT License | 6 votes |
@httpPost('/', TYPES.FetchLoggedUserMiddleware)
public async create(
@requestBody() body: Partial<Product>,
req: Request & {user: User},
res: Response,
) {
const repository = await this.databaseService.getRepository(
ProductRepository,
);
const product = new Product();
product.title = body.title;
product.published = body.published;
product.price = Number(body.price);
product.user = req.user;
const errors = await validate(product);
if (errors.length !== 0) {
return res.status(400).json({errors});
}
await repository.save(product);
return res.sendStatus(201);
}
Example #9
Source File: validation.pipe.ts From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 | 6 votes |
async transform(value: any, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length) {
console.log(this.formatErrors(errors));
throw new HttpException(
`Validation error : ${this.formatErrors(errors)}`,
HttpStatus.BAD_REQUEST,
);
}
return value;
}
Example #10
Source File: ClassValidator.ts From typescript-clean-architecture with MIT License | 6 votes |
// eslint-disable-next-line @typescript-eslint/ban-types
public static async validate<TTarget extends object>(target: TTarget, context?: string): Promise<Optional<ClassValidationDetails>> {
let details: Optional<ClassValidationDetails>;
const errors: ValidationError[] = await validate(target);
if (errors.length > 0) {
details = {
context: context || target.constructor.name,
errors : []
};
for (const error of errors) {
details.errors.push({
property: error.property,
message : error.constraints ? Object.values(error.constraints) : []
});
}
}
return details;
}
Example #11
Source File: validation.pipe.ts From nestjs-starter with MIT License | 6 votes |
async transform(value, metadata: ArgumentMetadata) {
if (!value) {
throw new BadRequestException('No data submitted');
}
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException(this.buildError(errors), 'Input data validation failed');
}
return value;
}
Example #12
Source File: form-validator.directive.ts From nestjs-angular-starter with MIT License | 6 votes |
/**
* Goes through all of the form and checks for any issues, updates all of the fields accordingly.
*/
updateForm(): Promise<boolean> {
return validate(this.appFormValidator).then((validationErrors) => {
const prevIsFormValid = this._isFormValid;
this._isFormValid = true;
this.getFormGroupInputs().forEach((input: HTMLInputElement) => {
const name = input.name;
const validationError = this.getValidationErrorFromFieldName(
name,
validationErrors
);
this.updateFormField(input, validationError);
if (validationError) this._isFormValid = false;
});
if (prevIsFormValid !== this._isFormValid)
this.appFormValidatorIsFormValidChange.emit(this._isFormValid);
return this._isFormValid;
});
}
Example #13
Source File: assessment.controller.ts From bulwark with MIT License | 6 votes |
createAssessment = async (req: UserRequest, res: Response) => {
if (isNaN(req.body.asset)) {
return res.status(400).json('Asset ID is invalid');
}
const asset = await getConnection()
.getRepository(Asset)
.findOne(req.body.asset, { relations: ['organization'] });
if (!asset) {
return res.status(404).json('Asset does not exist');
}
const hasAccess = await hasAssetWriteAccess(req, asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
if (!req.body.testers) {
return res.status(400).json('No testers have been selected');
}
const testers = await userController.getUsersById(req.body.testers);
const assessment = new Assessment();
assessment.asset = asset;
assessment.name = req.body.name;
assessment.executiveSummary = req.body.executiveSummary;
assessment.jiraId = req.body.jiraId;
assessment.testUrl = req.body.testUrl;
assessment.prodUrl = req.body.prodUrl;
assessment.scope = req.body.scope;
assessment.tag = req.body.tag;
assessment.startDate = new Date(req.body.startDate);
assessment.endDate = new Date(req.body.endDate);
assessment.testers = testers;
const errors = await validate(assessment);
if (errors.length > 0) {
return res.status(400).send('Assessment form validation failed');
} else {
await getConnection().getRepository(Assessment).save(assessment);
res.status(200).json('Assessment created succesfully');
}
}
Example #14
Source File: object-validator.service.ts From nest-amqp with MIT License | 6 votes |
/**
* Transforme and validate a source object by a decorated class. It works with
* the `class-validator` and the `class-transformer` packages.
*
* By default, the validator will strip every property that is not explicitly exposed
*
* @param {new (...params: unknown[]) => T} type Class with validation and transformation decorators.
* @param {unknown} plain Source object which will be transformed and validated.
* @param {ObjectValidationOptions} options Transformation and validations options.
*
* @return {Promise<T>} The transformed and validated object.
*
* {@link https://www.npmjs.com/package/class-transformer class-transformer}
* {@link https://www.npmjs.com/package/class-validator class-validator}
*
* @public
*/
public async validate<T>(type: new (...params: unknown[]) => T, plain: unknown, options?: ObjectValidationOptions): Promise<T> {
if (plain === null || plain === undefined) {
throw new ValidationNullObjectException(type.name);
}
const transformerOptions = options?.transformerOptions ?? {};
const validatorOptions = options?.validatorOptions ?? {};
const object: T = plainToClass<T, unknown>(type, plain, { strategy: 'excludeAll', ...transformerOptions });
const errors = await validate(object as any, validatorOptions);
if (errors.length !== 0) {
throw new ValidationException(errors);
}
return object;
}
Example #15
Source File: DataHolderOidcResponse.ts From ADR-Gateway with MIT License | 5 votes |
DataHolderOidcResponse = async (dhOidcResponse:DataholderOidcResponse) => {
let errors = await validate(dhOidcResponse)
if (errors.length > 0) throw errors; // TODO standardize Validate errors
return true;
}
Example #16
Source File: ParametersValidator.ts From affinidi-core-sdk with Apache License 2.0 | 5 votes |
static async validate(schemas: any) {
const allErrors: any = []
for (const [index, schema] of schemas.entries()) {
const { isArray, type, isRequired, value: SchemaValue } = schema
let errors: any = []
const isArrayValid = Array.isArray(SchemaValue) && SchemaValue
if (isArray && isArrayValid && SchemaValue.length === 0) {
continue
}
if (isArray && !isArrayValid) {
const message = `Parameter at index [${index}] should be an array.`
const error = { value: SchemaValue, message }
allErrors.push(error)
continue
}
if (isArray) {
const items = SchemaValue
for (const item of items) {
errors = await ParametersValidator.process({ type, isRequired, value: item }, index)
allErrors.push(...errors)
}
} else {
errors = await ParametersValidator.process(schema, index)
allErrors.push(...errors)
}
}
if (allErrors.length > 0) {
throw new SdkErrorFromCode('COR-1', { errors: allErrors })
}
}
Example #17
Source File: UserController.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 5 votes |
static newUser = async (req: Request, res: Response) => {
let username = req.body.user;
let password = req.body.password;
let role = req.body.role;
// console.log(req.body)
if (isUndefined(username)) {
res.status(400).send("user missing");
return;
}
if (isUndefined(password)) {
res.status(400).send("password missing");
return;
}
if (isUndefined(role)) {
res.status(400).send("role missing");
return;
}
let user = new User();
user.name = username;
user.password = password;
user.role = role;
const errors = await validate(user);
if (errors.length > 0) {
res.status(400).send(errors);
return;
}
user.hashPassword();
const userRepository = getRepository(User);
try {
await userRepository.save(user);
} catch (e) {
res.status(409).send("Username already in use");
return;
}
res.status(201).send("User created");
};
Example #18
Source File: pipe-transtorm.ts From malagu with MIT License | 5 votes |
public async transform(value: any, metadata: ArgumentMetadata): Promise<any> {
const opts = this.options || {};
const { argType } = metadata;
if (!argType || !this.toValidate(metadata)) {
return value;
}
const originalValue = value;
value = this.toEmptyIfNil(value);
const isNil = value !== originalValue;
const isPrimitive = this.isPrimitive(value);
this.stripProtoKeys(value);
let entity = plainToInstance(
argType,
value,
opts.transformOptions,
);
const originalEntity = entity;
const isCtorNotEqual = entity.constructor !== argType;
if (isCtorNotEqual && !isPrimitive) {
entity.constructor = argType;
} else if (isCtorNotEqual) {
// when "entity" is a primitive value, we have to temporarily
// replace the entity to perform the validation against the original
// metatype defined inside the handler
entity = { constructor: argType } as any;
}
const errors = await validate(entity, opts.validatorOptions);
if (errors.length > 0) {
throw new ValidationErrors(opts.detailedOutputDisabled ? undefined : errors);
}
if (isPrimitive) {
// if the value is a primitive value and the validation process has been successfully completed
// we have to revert the original value passed through the pipe
entity = originalEntity;
}
if (opts.transformEnabled) {
return entity;
}
if (isNil) {
// if the value was originally undefined or null, revert it back
return originalValue;
}
return Object.keys(opts.validatorOptions).length > 0
? instanceToPlain(entity, opts.transformOptions)
: value;
}
Example #19
Source File: validate-dto.ts From etherspot-sdk with MIT License | 5 votes |
/**
* @ignore
*/
export async function validateDto<T extends {}>(
dto: Partial<T>,
DtoConstructor: { new (): T },
options: {
addressKeys?: (keyof T)[];
} = {},
): Promise<T> {
const result = new DtoConstructor();
const { addressKeys } = options;
try {
let dtoWithoutUndefined = Object.entries(dto).reduce((result, [key, value]) => {
if (typeof value !== 'undefined') {
result = {
...result,
[key]: value,
};
}
return result;
}, {}) as T;
if (addressKeys) {
dtoWithoutUndefined = prepareAddresses(dtoWithoutUndefined, ...addressKeys);
}
Object.assign(result, dtoWithoutUndefined);
} catch (err) {
//
}
const errors = await validate(result, {
forbidUnknownValues: true,
validationError: {
target: false,
value: false,
},
});
if (errors && errors.length) {
throw new ValidationException(errors);
}
return result;
}
Example #20
Source File: base_domain_class.ts From Deep-Lynx with MIT License | 5 votes |
async validationErrors(): Promise<string[] | null> {
const errors = await validate(this);
if (errors.length > 0) return Promise.resolve(errors.map((e) => e.toString(false)));
return Promise.resolve(null);
}
Example #21
Source File: asset.controller.ts From bulwark with MIT License | 5 votes |
createAsset = async (req: UserRequest, res: Response) => {
if (isNaN(+req.params.id)) {
return res.status(400).json('Organization ID is not valid');
}
const org = await getConnection()
.getRepository(Organization)
.findOne(req.params.id);
if (!org) {
return res.status(404).json('Organization does not exist');
}
if (!req.body.name) {
return res.status(400).send('Asset is not valid');
}
let asset = new Asset();
asset.name = req.body.name;
asset.organization = org;
asset.status = status.active;
const errors = await validate(asset);
if (errors.length > 0) {
return res.status(400).send('Asset form validation failed');
} else {
asset = await getConnection().getRepository(Asset).save(asset);
if (
req.body.jira &&
req.body.jira.username &&
req.body.jira.host &&
req.body.jira.apiKey
) {
try {
await addJiraIntegration(
req.body.jira.username,
req.body.jira.host,
req.body.jira.apiKey,
asset
);
} catch (err) {
return res.status(400).json(err);
}
} else {
return res
.status(200)
.json(
'Asset saved successfully. Unable to integrate Jira. JIRA integration requires username, host, and API key.'
);
}
return res.status(200).json('Asset saved successfully');
}
}
Example #22
Source File: UserValidations.test.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe('UserValidations', () => {
test('User should always have a first name', async (done) => {
const user = new User();
const errorsOne = await validate(user);
user.firstName = 'TestName';
const errorsTwo = await validate(user);
expect(errorsOne.length).toBeGreaterThan(errorsTwo.length);
done();
});
test('User should always have a last name', async (done) => {
const user = new User();
const errorsOne = await validate(user);
user.lastName = 'TestName';
const errorsTwo = await validate(user);
expect(errorsOne.length).toBeGreaterThan(errorsTwo.length);
done();
});
test('User should always have a email', async (done) => {
const user = new User();
const errorsOne = await validate(user);
user.email = '[email protected]';
const errorsTwo = await validate(user);
expect(errorsOne.length).toBeGreaterThan(errorsTwo.length);
done();
});
test('User validation should succeed with all required fields', async (done) => {
const user = new User();
user.firstName = 'TestName';
user.lastName = 'TestName';
user.email = '[email protected]';
user.username = 'test';
user.password = '1234';
const errors = await validate(user);
expect(errors.length).toEqual(0);
done();
});
});
Example #23
Source File: create-user.dto.ts From uniauth-backend with MIT License | 5 votes |
/** college registration number of user */
@ApiProperty({ description: 'registration number of user', example: '19BCE2669' })
@IsNotEmpty()
@Validate(RegistrationNumber)
registrationNumber: string;
Example #24
Source File: user.inputs.ts From convoychat with GNU General Public License v3.0 | 5 votes |
@Field({ nullable: false })
@IsHexColor()
@Validate(ValidateColor)
color: string;
Example #25
Source File: create-collection.dto.ts From aqualink-app with MIT License | 5 votes |
@ApiProperty({ example: 1 })
@IsNotEmpty()
@IsNumber()
@Validate(EntityExists, [User])
userId: number;
Example #26
Source File: data_source.ts From Deep-Lynx with MIT License | 5 votes |
@IsOptional()
@Validate(DataRetentionDays)
data_retention_days = 30;
Example #27
Source File: environment.model.ts From relate with GNU General Public License v3.0 | 5 votes |
@IsOptional()
@Validate(ServerConfigModel)
public serverConfig?: ServerConfigModel;
Example #28
Source File: RevisionRecordController.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 4 votes |
static listAll = async (req: Request, res: Response) => {
console.log(util.inspect(req.query.knowledgeVector, false, null, true /* enable colors */));
if (isEmpty(req.query.knowledgeVector)) {
res
.status(400)
.send(
'Must send an array of knowledge vectors as query param. An empty knowledge vector would be { processes: [{ id : "validUUIDv4" , clock : 0 } ]}'
);
return;
}
// Thorough JSON validation using JSON Schema, TypedJSON and class-validator
const ajv = new Ajv();
const valid = ajv.validate(kvSchema, req.query.knowledgeVector);
if (!valid) {
console.log(ajv.errors);
res.status(400).send(ajv.errors);
return;
}
let incomingKV: KnowledgeVector;
try {
incomingKV = new TypedJSON(KnowledgeVector).parse(req.query.knowledgeVector);
} catch (error) {
res.status(400).send("JSON schema error");
return;
}
console.log(util.inspect(incomingKV, false, null, true /* enable colors */));
const errors = await validate(incomingKV);
if (errors.length > 0) {
res.status(400).send(errors);
return;
}
//console.log(util.inspect(incomingKV, false, null, true /* enable colors */));
let returnRevRecord = new OCKRevisionRecord();
returnRevRecord.entities = [];
// Case 1 : iOS device is syncing for the first time, it has no knowledge of the servers clock
if (isEmpty(incomingKV.processes.find((process) => process.id === uuid))) {
// store incoming clock locally
let clockRepo = getMongoRepository(Process);
for (const process of incomingKV.processes) {
assert(isUUID(process.id));
const processExists = await clockRepo.findOne({ id: process.id });
if (isEmpty(processExists)) {
assert(isNotEmpty(process.id));
await clockRepo.save(process);
}
}
// send all outcomes and tasks
const taskRepository = getMongoRepository(OCKTask);
const tasks = await taskRepository.find({});
const outcomeRepository = getMongoRepository(OCKOutcome);
const outcomes = await outcomeRepository.find({});
tasks.map((entity) => {
delete entity.kv;
returnRevRecord.entities.push({ type: "task", object: entity });
});
outcomes.map((entity) => {
delete entity.kv;
returnRevRecord.entities.push({ type: "outcome", object: entity });
});
// set kv for revisionRecord
returnRevRecord.knowledgeVector = await getLatestKnowledgeVector();
//console.log(util.inspect(returnRevRecord, false, null, true /* enable colors */));
res.status(201).send(returnRevRecord);
return;
}
// Case 2 : It has synced before but its clock might be older than local, send entities newer than clock
const clock = incomingKV.processes.find((process) => process.id === uuid).clock;
assert(!isEmpty(clock), "clock cannot be undefined at this point");
const taskRepository = getMongoRepository(OCKTask);
const tasks = await taskRepository.find({
$and: [{ "kv.processes.clock": { $gt: clock } }, { "kv.processes.id": { $eq: uuid } }],
});
const outcomeRepository = getMongoRepository(OCKOutcome);
const outcomes = await outcomeRepository.find({
$and: [{ "kv.processes.clock": { $gt: clock } }, { "kv.processes.id": { $eq: uuid } }],
});
tasks.map((entity) => {
delete entity.kv;
returnRevRecord.entities.push({ type: "task", object: entity });
});
outcomes.map((entity) => {
delete entity.kv;
returnRevRecord.entities.push({ type: "outcome", object: entity });
});
// set kv for revisionRecord
returnRevRecord.knowledgeVector = await getLatestKnowledgeVector();
//console.log(util.inspect(returnRevRecord, false, null, true /* enable colors */));
res.status(201).send(returnRevRecord);
};
Example #29
Source File: vulnerability.controller.ts From bulwark with MIT License | 4 votes |
patchVulnById = async (req: UserRequest, res: Response) => {
req = await fileUploadController.uploadFileArray(req, res);
if (isNaN(+req.body.assessment) || !req.body.assessment) {
return res.status(400).json('Invalid Assessment ID');
}
const assessment = await getConnection()
.getRepository(Assessment)
.findOne(req.body.assessment, { relations: ['asset'] });
if (!assessment) {
return res.status(404).json('Assessment does not exist');
}
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
if (isNaN(+req.params.vulnId)) {
return res.status(400).json('Vulnerability ID is invalid');
}
const vulnerability = await getConnection()
.getRepository(Vulnerability)
.findOne(req.params.vulnId);
if (!vulnerability) {
return res.status(404).json('Vulnerability does not exist');
}
const callback = (resStatus: number, message: any) => {
res.status(resStatus).send(message);
};
vulnerability.id = +req.params.vulnId;
vulnerability.impact = req.body.impact;
vulnerability.likelihood = req.body.likelihood;
vulnerability.risk = req.body.risk;
vulnerability.status = req.body.status;
vulnerability.description = req.body.description;
vulnerability.remediation = req.body.remediation;
vulnerability.jiraId = req.body.jiraId;
vulnerability.cvssScore = req.body.cvssScore;
vulnerability.cvssUrl = req.body.cvssUrl;
vulnerability.detailedInfo = req.body.detailedInfo;
vulnerability.assessment = assessment;
vulnerability.name = req.body.name;
vulnerability.systemic = req.body.systemic;
const errors = await validate(vulnerability);
if (errors.length > 0) {
return res.status(400).send('Vulnerability form validation failed');
} else {
await getConnection().getRepository(Vulnerability).save(vulnerability);
// Remove deleted files
if (req.body.screenshotsToDelete) {
const existingScreenshots = await getConnection()
.getRepository(File)
.find({ where: { vulnerability: vulnerability.id } });
const existingScreenshotIds = existingScreenshots.map(
(screenshot) => screenshot.id
);
let screenshotsToDelete = JSON.parse(req.body.screenshotsToDelete);
// We only want to remove the files associated to the vulnerability
screenshotsToDelete = existingScreenshotIds.filter((value) =>
screenshotsToDelete.includes(value)
);
for (const screenshotId of screenshotsToDelete) {
getConnection().getRepository(File).delete(screenshotId);
}
}
saveScreenshots(req.files, vulnerability, callback);
// Remove deleted problem locations
if (req.body.problemLocations.length) {
const clientProdLocs = JSON.parse(req.body.problemLocations);
const clientProdLocsIds = clientProdLocs.map((value) => value.id);
const existingProbLocs = await getConnection()
.getRepository(ProblemLocation)
.find({ where: { vulnerability: vulnerability.id } });
const existingProbLocIds = existingProbLocs.map((probLoc) => probLoc.id);
const prodLocsToDelete = existingProbLocIds.filter(
(value) => !clientProdLocsIds.includes(value)
);
for (const probLoc of prodLocsToDelete) {
getConnection().getRepository(ProblemLocation).delete(probLoc);
}
saveProblemLocations(clientProdLocs, vulnerability, callback);
}
// Remove deleted resources
if (req.body.resources.length) {
const clientResources = JSON.parse(req.body.resources);
const clientResourceIds = clientResources.map((value) => value.id);
const existingResources = await getConnection()
.getRepository(Resource)
.find({ where: { vulnerability: vulnerability.id } });
const existingResourceIds = existingResources.map(
(resource) => resource.id
);
const resourcesToDelete = existingResourceIds.filter(
(value) => !clientResourceIds.includes(value)
);
for (const resource of resourcesToDelete) {
getConnection().getRepository(Resource).delete(resource);
}
saveResources(clientResources, vulnerability, callback);
}
return res.status(200).json('Vulnerability patched successfully');
}
}