Skip to content
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

feat(ajv): add returnsCoercedValues option to keep the coerced value by ajv #2504

Merged
merged 3 commits into from
Nov 2, 2023
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
66 changes: 63 additions & 3 deletions docs/docs/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,66 @@ The @@Nullable@@ decorator is used allow a null value on a field while preservin
</Tab>
</Tabs>

::: warning

Since the v7.43.0, `ajv.returnsCoercedValues` is available to solve the following issue: [#2355](https://github.com/tsedio/tsed/issues/2355)
If `returnsCoercedValues` is true, AjvService will return the coerced value instead of the original value. In this case, `@Nullable()` will be mandatory to
allow the coercion of the value to `null`.

For example if `returnsCoercedValues` is `false` (default behavior), Ts.ED will allow null value on a field without `@Nullable()` decorator:

```typescript
class NullableModel {
@Proprety()
propString: string; // null => null

@Proprety()
propNumber: number; // null => null

@Property()
propBool: boolean; // null => null
}
```

Ajv won't emit validation error if the value is null due to his coercion behavior. AjvService will return the original value and not the Ajv coerced value.
Another problem is, the typings of the model doesn't reflect the real coerced value.

Using the `returnsCoercedValues` option, AjvService will return the coerced type. In this case, our previous model will have the following behavior:

```typescript
class NullableModel {
@Proprety()
propString: string; // null => ''

@Proprety()
propNumber: number; // null => 0

@Property()
propBool: boolean; // null => false
}
```

Now `@Nullable` usage is mandatory to allow `null` value on properties:

```typescript
class NullableModel {
@Nullable(String)
propString: string | null; // null => null

@Nullable(Number)
propNumber: number | null; // null => null

@Nullable(Boolean)
propBool: boolean | null; // null => null
}
```

:::

::: warning
`returnsCoercedValue` will become true by default in the next major version of Ts.ED.
:::

## Any

The @@Any@@ decorator is used to allow any types:
Expand Down Expand Up @@ -677,7 +737,7 @@ So by using the @@deserialize@@ function with the extra groups options, we can m
<Tab label="Creation">

```typescript
import { deserialize } from '@tsed/json-mapper';
import {deserialize} from "@tsed/json-mapper";

const result = deserialize<User>(
{
Expand All @@ -697,7 +757,7 @@ console.log(result); // User {firstName, lastName, email, password}
<Tab label="With group">

```typescript
import { deserialize } from '@tsed/json-mapper';
import {deserialize} from "@tsed/json-mapper";

const result = deserialize<User>(
{
Expand All @@ -718,7 +778,7 @@ console.log(result); // User {id, firstName, lastName, email, password}
<Tab label="With glob pattern">

```typescript
import { deserialize } from '@tsed/json-mapper';
import {deserialize} from "@tsed/json-mapper";

const result = deserialize<User>(
{
Expand Down
8 changes: 7 additions & 1 deletion docs/tutorials/ajv.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ import {Configuration} from "@tsed/common";
import "@tsed/ajv"; // import ajv ts.ed module

@Configuration({
ajv: {}
ajv: {
returnsCoercedValues: true // returns coerced value to the next pipe instead of returns original value (See #2355)
}
})
export class Server {}
```
Expand Down Expand Up @@ -227,6 +229,10 @@ describe("Product", () => {
});
```

::: warning
If you planed to create keyword that transform the data, you have to set `returnsCoercedValues` to `true` in your configuration.
:::

### With "code" function

Starting from v7 Ajv uses [CodeGen module](https://github.com/ajv-validator/ajv/blob/master/lib/compile/codegen/index.ts) for all pre-defined keywords - see [codegen.md](https://ajv.js.org/codegen.html) for details.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class ValidationPipe implements PipeMethods {
customKeys: true
});

await this.validator.validate(value, {
value = await this.validator.validate(value, {
schema,
type: metadata.isClass ? metadata.type : undefined,
collectionType: metadata.collectionType
Expand Down
2 changes: 1 addition & 1 deletion packages/specs/ajv/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
},
coverageThreshold: {
global: {
branches: 86.88,
branches: 87.87,
functions: 100,
lines: 99.71,
statements: 99.71
Expand Down
1 change: 1 addition & 0 deletions packages/specs/ajv/src/interfaces/IAjvSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ export type ErrorFormatter = (error: AjvErrorObject) => string;
export interface IAjvSettings extends Options {
Ajv?: any;
errorFormatter?: ErrorFormatter;
returnsCoercedValues?: boolean;
}
1 change: 1 addition & 0 deletions packages/specs/ajv/src/services/AjvService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {AjvService} from "./AjvService";
describe("AjvService", () => {
beforeEach(() => PlatformTest.create());
afterEach(() => PlatformTest.reset());

it("should use the function api as schema", async () => {
const ajvService = PlatformTest.get<AjvService>(AjvService);

Expand Down
9 changes: 8 additions & 1 deletion packages/specs/ajv/src/services/AjvService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export class AjvService {
@Constant("ajv.errorFormatter", defaultErrorFormatter)
protected errorFormatter: ErrorFormatter;

@Constant("ajv.returnsCoercedValues")
protected returnsCoercedValues: boolean;

@Inject()
protected ajv: Ajv;

Expand All @@ -30,7 +33,7 @@ export class AjvService {
const schema = defaultSchema || getJsonSchema(type, {...additionalOptions, customKeys: true});

if (schema) {
const localValue = deepClone(value);
const localValue = this.returnsCoercedValues ? value : deepClone(value);
const validate = this.ajv.compile(schema);

const valid = await validate(localValue);
Expand All @@ -44,6 +47,10 @@ export class AjvService {
value: localValue
});
}

EinfachHans marked this conversation as resolved.
Show resolved Hide resolved
if (this.returnsCoercedValues) {
return localValue;
}
}

return value;
Expand Down
187 changes: 187 additions & 0 deletions packages/specs/ajv/test/integration/nullable.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import "../../src/index";
import {BodyParams, ParamTypes, ParamValidationError, PlatformTest, Post, QueryParams, UseParam, ValidationPipe} from "@tsed/common";
import {BadRequest} from "@tsed/exceptions";
import {CollectionOf, getJsonSchema, JsonParameterStore, MinLength, Nullable, Property, Required, Schema, string} from "@tsed/schema";

async function validate(value: any, metadata: any) {
const pipe: ValidationPipe = await PlatformTest.invoke<ValidationPipe>(ValidationPipe);

try {
return await pipe.transform(value, metadata);
} catch (er) {
if (er instanceof BadRequest) {
return ParamValidationError.from(metadata, er);
}

throw er;
}
}

class NestedModel {
@Property()
id: string;
}

class NullModel {
@Nullable(String)
prop1: string | null;

@Nullable(Number)
prop2: number;

@Nullable(Date)
prop3: Date | null;

@Nullable(NestedModel)
prop4: NestedModel | null;

@Nullable(Array)
prop5: string[] | null;
}

class NoNullableModel {
@Property()
prop1: string;

@Property()
prop2: number;

@Property()
prop3: Date;

@Property()
prop4: NestedModel;

@CollectionOf(String)
prop5: string[];
}

describe("Nullable model", () => {
describe("when returnsCoercedValues is false", () => {
beforeEach(() =>
PlatformTest.create({
ajv: {
coerceTypes: "array"
}
})
);
afterEach(() => PlatformTest.reset());
it("should validate object and returns the original value (NullModel)", async () => {
class Ctrl {
get(@BodyParams() value: NullModel) {}
}

const value = {
prop1: null,
prop2: null,
prop3: null,
prop4: null,
prop5: null
};

const result = await validate(value, JsonParameterStore.get(Ctrl, "get", 0));

expect(result).toEqual({
prop1: null,
prop2: null,
prop3: null,
prop4: null,
prop5: null
});

const result2 = await validate(
{
prop1: "test",
prop2: 1,
prop3: "2020-01-01",
prop4: {
id: "id"
},
prop5: ["test"]
},
JsonParameterStore.get(Ctrl, "get", 0)
);

expect(result2).toEqual({
prop1: "test",
prop2: 1,
prop3: "2020-01-01",
prop4: {
id: "id"
},
prop5: ["test"]
});
});
it("should validate object and returns the original value (NoNullableModel)", async () => {
class Ctrl {
get(@BodyParams() value: NoNullableModel) {}
}

const value = {
prop1: null,
prop2: null,
prop3: null,
prop5: null
};

const result = await validate(value, JsonParameterStore.get(Ctrl, "get", 0));

expect(result).toEqual({
prop1: null,
prop2: null,
prop3: null,
prop5: null
});
});
});
describe("when returnsCoercedValues is true", () => {
beforeEach(() =>
PlatformTest.create({
ajv: {
verbose: true,
coerceTypes: "array",
returnsCoercedValues: true
}
})
);
afterEach(() => PlatformTest.reset());
it("should validate object and return the coerced value (NullModel)", async () => {
class Ctrl {
get(@BodyParams() value: NullModel) {}
}

const value = {
prop1: null,
prop2: null,
prop3: null,
prop4: null,
prop5: null
};

const result = await validate(value, JsonParameterStore.get(Ctrl, "get", 0));

expect(result).toEqual(value);
});
it("should validate object and return the coerced value (NoNullableModel)", async () => {
class Ctrl {
get(@BodyParams() value: NoNullableModel) {}
}

const value = {
prop1: null,
prop2: null,
prop3: null,
prop5: null
};

const result = await validate(value, JsonParameterStore.get(Ctrl, "get", 0));

expect(result).toEqual({
prop1: "",
prop2: 0,
prop3: "",
prop5: [""]
});
});
});
});
Loading
Loading