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

#104 @AssertType rejects a promise when used in async methods #105

Merged
merged 1 commit into from
Nov 1, 2021
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
68 changes: 68 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,74 @@ new A().method(42) === 42; // true
new A().method('42' as any); // will throw error
```

### async and `Promise` returning methods
`AssertType` can also work correctly with `async` methods, returning promise rejected with `TypeGuardError`

To enable this functionality, you need to emit decorators metadata for your TypeScript project.

```json
{
"compilerOptions": {
"emitDecoratorMetadata": true
}
}
```

Then `AssertType` will work with async methods and `Promise` returning methods automatically.
```typescript
import { ValidateClass, AssertType } from 'typescript-is';

@ValidateClass()
class A {
async method(@AssertType({ async: true }) value: number) {
// You can safely use value as a number
return value;
}

methodPromise(@AssertType({ async: true }) value: number): Promise<number> {
// You can safely use value as a number
return Promise.resolve(value);
}
}

new A().method(42).then(value => value === 42 /* true */);
new A().method('42' as any).catch(error => {
// error will be of TypeGuardError type
})
new A().methodPromise('42' as any).catch(error => {
// error will be of TypeGuardError type
})
```

If you want to throw synchronously for some reason, you can override the behaviour using with `@AssertType({ async: false })`:
```typescript
import { ValidateClass, AssertType } from 'typescript-is';

@ValidateClass()
class A {
async method(@AssertType({ async: false }) value: number) {
// You can safely use value as a number
return value;
}
}

new A().method(42).then(value => value === 42 /* true */);
new A().method('42' as any); // will throw error
```

If you cannot or don't want to enable decorators metadata, you still make AssertType reject with promise using `@AssertType({ async: true })`
```typescript
import { ValidateClass, AssertType } from 'typescript-is';

@ValidateClass()
class A {
async method(@AssertType({ async: true }) value: number) {
// You can safely use value as a number
return value;
}
}
```

## Strict equality (`equals`, `createEquals`, `assertEquals`, `createAssertEquals`)

This family of functions check not only whether the passed object is assignable to the specified type, but also checks that the passed object does not contain any more than is necessary. In other words: the type is also "assignable" to the object. This functionality is equivalent to specifying `disallowSuperfluousObjectProperties` in the options, the difference is that this will apply only to the specific function call. For example:
Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export function createAssertEquals<T>(): (object: any) => T;
new A().method('0' as any); // will throw an error
```
*/
export function AssertType(): (target: object, propertyKey: string | symbol, parameterIndex: number) => void;
export function AssertType(options?: { async: boolean }): (target: object, propertyKey: string | symbol, parameterIndex: number) => void;

/**
* Overrides methods in the target class with a proxy that will first validate the argument types.
Expand Down
13 changes: 11 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ function AssertType(assertion, options = {}) {
require('reflect-metadata');
return function (target, propertyKey, parameterIndex) {
const assertions = Reflect.getOwnMetadata(assertionsMetadataKey, target, propertyKey) || [];
assertions[parameterIndex] = { assertion, options };
if(Reflect.getOwnMetadata('design:returntype', target, propertyKey) === Promise) {
assertions[parameterIndex] = { assertion, options: Object.assign({ async: true }, options) };
} else {
assertions[parameterIndex] = { assertion, options };
}
Reflect.defineMetadata(assertionsMetadataKey, assertions, target, propertyKey);
};
}
Expand All @@ -64,7 +68,12 @@ function ValidateClass(errorConstructor = TypeGuardError) {
}
const errorObject = assertions[i].assertion(args[i]);
if (errorObject !== null) {
throw new errorConstructor(errorObject, args[i]);
const errorInstance = new errorConstructor(errorObject, args[i]);
if(assertions[i].options.async) {
return Promise.reject(errorInstance);
} else {
throw errorInstance;
}
}
}
return originalMethod.apply(this, args);
Expand Down
21 changes: 21 additions & 0 deletions test-fixtures/issue-104.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {AssertType, ValidateClass} from '../index';

@ValidateClass()
export class AsyncMethods {
async asyncMethod(@AssertType() body: { test: string }): Promise<boolean> {
return true
}
async asyncMethodNoExplicitReturn(@AssertType() body: { test: string }) {
return true
}
promiseReturnMethod(@AssertType() body: { test: string }): Promise<boolean> {
return Promise.resolve(true)
}
async asyncOverride(@AssertType({ async: false }) body: { test: string }): Promise<boolean> {
return true
}
promiseOrOtherReturnMethod(@AssertType() body: { test: string }): Promise<boolean> | boolean{
return Promise.resolve(true)
}
}

25 changes: 25 additions & 0 deletions test/issue-104.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import * as assert from 'assert';
import {AsyncMethods} from '../test-fixtures/issue-104';

describe('@ValidateClass(), @AssertType()', () => {
it('should return rejected promise for async methods', () => {
const instance = new AsyncMethods()
assert.rejects(instance.asyncMethod({invalid: 123} as any))
})
it('should return rejected promise for async methods with not explicit return type', () => {
const instance = new AsyncMethods()
assert.rejects(instance.asyncMethodNoExplicitReturn({invalid: 123} as any))
})
it('should return rejected promise for methods returning promise', () => {
const instance = new AsyncMethods()
assert.rejects(instance.promiseReturnMethod({invalid: 123} as any))
})
it('should throw synchronously if { async: false } option is set', () => {
const instance = new AsyncMethods()
assert.throws(() => instance.asyncOverride({invalid: 123} as any))
})
it('should throw synchronously method may return something other than promise', () => {
const instance = new AsyncMethods()
assert.throws(() => instance.promiseOrOtherReturnMethod({invalid: 123} as any))
})
})
3 changes: 2 additions & 1 deletion tsconfig-test.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"lib": [
"es6"
],
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": true,
"noUnusedLocals": true,
Expand All @@ -20,4 +21,4 @@
"include": [
"test"
]
}
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"lib": [
"es6"
],
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": true,
"noUnusedLocals": true,
Expand All @@ -17,4 +18,4 @@
"include": [
"src"
]
}
}