Skip to content

Commit 819740b

Browse files
Merge pull request #3 from arizworld/feat/npm_pulish
Dev - fixed prettier issue
2 parents ca62fb1 + d8c954b commit 819740b

File tree

14 files changed

+84
-92
lines changed

14 files changed

+84
-92
lines changed

CHANGELOG.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
# Changelog
22

33
_This changelog follows the [keep a changelog][keep-a-changelog]_ format to maintain a human readable changelog.
4+
45
### [0.0.1](https://github.com/arizworld/class-validator-custom-errors/pull/1/) (2024-03-21)
56

67
### Added
8+
79
- added `transformFunction` in validatorOptions to customize the message for each time of validation.
8-
- added `transformKey` in validationOptions to pass specific keys to transformFunction for
9-
specific properties.
10+
- added `transformKey` in validationOptions to pass specific keys to transformFunction for
11+
specific properties.
1012

1113
### [0.14.0](https://github.com/typestack/class-validator/compare/v0.13.2...v0.14.0) (2022-12-09)
1214

README.md

+5-9
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ validate(post, {
8080
//pass a transform function to overwrite the default implementation for this validation only
8181
transformFunction: (key: string) => `I was called with ${key}`,
8282
},
83-
}).then((errors) => {
83+
}).then(errors => {
8484
// errors is an array of validation errors
8585
if (errors.length > 0) {
8686
console.log('validation failed. errors: ', errors);
@@ -94,23 +94,20 @@ validateOrReject(post, {
9494
//pass a transform function to overwrite the default implementation for this validation only
9595
transformFunction: (key: string) => `I was called with ${key}`,
9696
},
97-
}).catch((errors) => {
97+
}).catch(errors => {
9898
console.log('Promise rejected (validation failed). Errors: ', errors);
9999
});
100100
// or
101101
async function validateOrRejectExample(input: any) {
102102
try {
103-
await validateOrReject(input,{
103+
await validateOrReject(input, {
104104
validationError: {
105105
//pass a transform function to overwrite the default implementation for this validation only
106106
transformFunction: (key: string) => `I was called with ${key}`,
107107
},
108108
});
109109
} catch (errors) {
110-
console.log(
111-
'Caught promise rejection (validation failed). Errors: ',
112-
errors
113-
);
110+
console.log('Caught promise rejection (validation failed). Errors: ', errors);
114111
}
115112
}
116113
```
@@ -257,6 +254,7 @@ import app from './server'
257254
console.log('responseFrench: ', JSON.stringify(responseFrench.json(), null, 2))
258255
})()
259256
```
257+
260258
See this for more of the basic [class-validator documentation](https://github.com/typestack/class-validator)
261259

262260
## Validation decorators
@@ -384,5 +382,3 @@ See this for more of the basic [class-validator documentation](https://github.co
384382

385383
Take a look on samples in [./sample](https://github.com/arizworld/class-validator-custom-errors/tree/develop/sample) for more examples of
386384
usages.
387-
388-

docs/basics/validating-objects.md

-1
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,3 @@ async function awaitExample() {
5757
}
5858
}
5959
```
60-

docs/introduction/installation.md

-1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,3 @@ To install the stable version:
55
```
66
npm install --save class-validator-custom-errors
77
```
8-

sample/basic-usage/index.ts

+4-18
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,4 @@
1-
import {
2-
validate,
3-
validateOrReject,
4-
Contains,
5-
IsInt,
6-
Length,
7-
IsEmail,
8-
IsFQDN,
9-
IsDate,
10-
Min,
11-
Max,
12-
} from '../../src';
1+
import { validate, validateOrReject, Contains, IsInt, Length, IsEmail, IsFQDN, IsDate, Min, Max } from '../../src';
132

143
export class Post {
154
@Length(10, 20)
@@ -47,7 +36,7 @@ validate(post, {
4736
//pass a transform function to overwrite the default implemention for this validation only
4837
transformFunction: (key: string) => `I was called with ${key}`,
4938
},
50-
}).then((errors) => {
39+
}).then(errors => {
5140
// errors is an array of validation errors
5241
if (errors.length > 0) {
5342
console.log('validation failed. errors: ', errors);
@@ -61,7 +50,7 @@ validateOrReject(post, {
6150
//pass a transform function to overwrite the default implemention for this validation only
6251
transformFunction: (key: string) => `I was called with ${key}`,
6352
},
64-
}).catch((errors) => {
53+
}).catch(errors => {
6554
console.log('Promise rejected (validation failed). Errors: ', errors);
6655
});
6756
// or
@@ -74,9 +63,6 @@ async function validateOrRejectExample(input: any) {
7463
},
7564
});
7665
} catch (errors) {
77-
console.log(
78-
'Caught promise rejection (validation failed). Errors: ',
79-
errors
80-
);
66+
console.log('Caught promise rejection (validation failed). Errors: ', errors);
8167
}
8268
}

sample/i18next/Readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
This repo shows an example of integrating internationalization and validation with i18next and class-validator-custom-errors
1+
This repo shows an example of integrating internationalization and validation with i18next and class-validator-custom-errors

sample/i18next/src/main.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
import inject from 'light-my-request'
2-
import app from './server'
1+
import inject from 'light-my-request';
2+
import app from './server';
33
(async function () {
44
const responseEnglish = await inject(app, {
55
method: 'POST',
66
url: '/urls/create',
77
headers: {
8-
"content-type": "application/json"
8+
'content-type': 'application/json',
99
},
10-
payload: JSON.stringify({ query: {} })
11-
})
12-
console.log('responseEnglish: ', JSON.stringify(responseEnglish.json(), null, 2))
10+
payload: JSON.stringify({ query: {} }),
11+
});
12+
console.log('responseEnglish: ', JSON.stringify(responseEnglish.json(), null, 2));
1313
const responseFrench = await inject(app, {
1414
method: 'POST',
1515
url: '/urls/create',
1616
headers: {
17-
"content-type": "application/json",
18-
"accept-language": "fr"
17+
'content-type': 'application/json',
18+
'accept-language': 'fr',
1919
},
20-
payload: JSON.stringify({ query: {} })
21-
})
22-
console.log('responseFrench: ', JSON.stringify(responseFrench.json(), null, 2))
23-
})()
20+
payload: JSON.stringify({ query: {} }),
21+
});
22+
console.log('responseFrench: ', JSON.stringify(responseFrench.json(), null, 2));
23+
})();

sample/i18next/src/schemas/Url.ts

+15-15
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
import { Type } from "class-transformer";
2-
import { IsArray, IsEnum, IsObject, IsOptional, IsString, ValidateNested } from "class-validator-custom-errors";
1+
import { Type } from 'class-transformer';
2+
import { IsArray, IsEnum, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator-custom-errors';
33

44
export enum HttpProtocols {
5-
http = "http",
6-
https = "https",
7-
ws = "ws",
8-
wss = "wss",
9-
ftp = "ftp"
5+
http = 'http',
6+
https = 'https',
7+
ws = 'ws',
8+
wss = 'wss',
9+
ftp = 'ftp',
1010
}
1111

1212
export class Query {
1313
@IsString()
14-
search!: string
14+
search!: string;
1515

1616
@IsArray()
1717
@IsOptional()
1818
@ValidateNested()
19-
select: string[] = []
19+
select: string[] = [];
2020
}
2121

2222
export class Url {
2323
@IsString({
24-
transformKey: 'uniqueString'
24+
transformKey: 'uniqueString',
2525
})
26-
host!: string
26+
host!: string;
2727

2828
@IsEnum(HttpProtocols)
29-
protocol!: string
29+
protocol!: string;
3030

3131
@IsString()
32-
tld!: string
32+
tld!: string;
3333

3434
@IsObject()
3535
@ValidateNested()
3636
@Type(() => Query)
37-
query!: Query
38-
}
37+
query!: Query;
38+
}

sample/i18next/src/server.ts

+13-17
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
1-
import express, { NextFunction, Request, Response } from 'express'
1+
import express, { NextFunction, Request, Response } from 'express';
22
import i18next from 'i18next';
3-
import middleware from 'i18next-http-middleware'
4-
import './utils/i18nextSetup'
5-
import 'reflect-metadata'
3+
import middleware from 'i18next-http-middleware';
4+
import './utils/i18nextSetup';
5+
import 'reflect-metadata';
66
import { validateOrReject } from 'class-validator-custom-errors';
77
import { plainToClass } from 'class-transformer';
88
import { Url } from './schemas/Url';
9-
const app = express()
10-
app.use([
11-
middleware.handle(i18next),
12-
express.json(),
13-
express.urlencoded({ extended: true }),
14-
]);
9+
const app = express();
10+
app.use([middleware.handle(i18next), express.json(), express.urlencoded({ extended: true })]);
1511
app.post('/urls/create', async (req: Request, res: Response, next: NextFunction) => {
1612
try {
1713
await validateOrReject(plainToClass(Url, req.body), {
1814
whitelist: true,
1915
validationError: {
2016
target: false,
21-
transformFunction: (key: string) => req.t(`validation.${key}`)
22-
}
23-
})
24-
res.json({ success: true, message: req.t("success"), errors: null })
17+
transformFunction: (key: string) => req.t(`validation.${key}`),
18+
},
19+
});
20+
res.json({ success: true, message: req.t('success'), errors: null });
2521
} catch (error) {
26-
res.json({ success: false, message: req.t("failure"), errors: error })
22+
res.json({ success: false, message: req.t('failure'), errors: error });
2723
}
28-
})
29-
export default app
24+
});
25+
export default app;
+5-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1-
import i18next from "i18next";
2-
import I18NexFsBackend from "i18next-fs-backend";
3-
import middleware from 'i18next-http-middleware'
1+
import i18next from 'i18next';
2+
import I18NexFsBackend from 'i18next-fs-backend';
3+
import middleware from 'i18next-http-middleware';
44

55
i18next
66
.use(I18NexFsBackend)
77
.use(middleware.LanguageDetector)
88
.init({
9-
fallbackLng: "en",
9+
fallbackLng: 'en',
1010
backend: {
11-
loadPath: "./locales/{{lng}}/translation.json",
11+
loadPath: './locales/{{lng}}/translation.json',
1212
},
1313
});
14-

src/decorator/ValidationOptions.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export interface ValidationOptions {
3333
/**
3434
* While using transformFunction if provided then the transformFunction will be called with this.
3535
*/
36-
transformKey?: string
36+
transformKey?: string;
3737
}
3838

3939
export function isValidationOptions(val: any): val is ValidationOptions {

src/metadata/ValidationMetadata.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export class ValidationMetadata {
4747
/**
4848
* While using transformFunction to customize error messages the transformFunction will be called with this key.
4949
*/
50-
transformKey?: string
50+
transformKey?: string;
5151
/**
5252
* Validation groups used for this validation.
5353
*/

src/validation/ValidationExecutor.ts

+22-7
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export class ValidationExecutor {
3030
// Constructor
3131
// -------------------------------------------------------------------------
3232

33-
constructor(private validator: Validator, private validatorOptions?: ValidatorOptions) { }
33+
constructor(private validator: Validator, private validatorOptions?: ValidatorOptions) {}
3434

3535
// -------------------------------------------------------------------------
3636
// Public Methods
@@ -46,8 +46,8 @@ export class ValidationExecutor {
4646
if (!this.metadataStorage.hasValidationMetaData && this.validatorOptions?.enableDebugMessages === true) {
4747
console.warn(
4848
`No validation metadata found. No validation will be performed. There are multiple possible reasons:\n` +
49-
` - There may be multiple class-validator versions installed. You will need to flatten your dependencies to fix the issue.\n` +
50-
` - This validation runs before any file with validation decorator was parsed by NodeJS.`
49+
` - There may be multiple class-validator versions installed. You will need to flatten your dependencies to fix the issue.\n` +
50+
` - This validation runs before any file with validation decorator was parsed by NodeJS.`
5151
);
5252
}
5353

@@ -68,15 +68,30 @@ export class ValidationExecutor {
6868
const groupedMetadatas = this.metadataStorage.groupByPropertyName(targetMetadatas);
6969

7070
/**if transformationFunction is provided then overwrite the message with the transformationFunction */
71-
if (this.validatorOptions?.validationError?.transformFunction && typeof this.validatorOptions?.validationError?.transformFunction === 'function') {
71+
if (
72+
this.validatorOptions?.validationError?.transformFunction &&
73+
typeof this.validatorOptions?.validationError?.transformFunction === 'function'
74+
) {
7275
targetMetadatas.forEach(e => {
73-
e.message = () => (this.validatorOptions?.validationError?.transformFunction as Function)(e.transformKey || e.name || e.type || 'This validation does not have an name or type associated with it, please add one.')
76+
e.message = () =>
77+
(this.validatorOptions?.validationError?.transformFunction as Function)(
78+
e.transformKey ||
79+
e.name ||
80+
e.type ||
81+
'This validation does not have an name or type associated with it, please add one.'
82+
);
7483
});
7584
Object.keys(groupedMetadatas).forEach(prop => {
7685
groupedMetadatas[prop].forEach(e => {
77-
e.message = () => (this.validatorOptions?.validationError?.transformFunction as Function)(e.transformKey || e.name || e.type || 'This validation does not have an name or type associated with it, please add one.')
86+
e.message = () =>
87+
(this.validatorOptions?.validationError?.transformFunction as Function)(
88+
e.transformKey ||
89+
e.name ||
90+
e.type ||
91+
'This validation does not have an name or type associated with it, please add one.'
92+
);
7893
});
79-
})
94+
});
8095
}
8196

8297
if (forbidUnknownValues && !targetMetadatas.length) {

src/validation/ValidatorOptions.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ export interface ValidatorOptions {
7575
* @param key the name of the error.
7676
* @returns string. it will be shown instead of the default error message.
7777
*/
78-
transformFunction?: (key: string) => string
78+
transformFunction?: (key: string) => string;
7979
};
8080

8181
/**

0 commit comments

Comments
 (0)