A TypeScript custom transformer to obtain json schema for fastest-validator from TypeScript interface
$ npm install ts-transformer-json-schema --save
TypeScript >= 2.4.1 TTypeScript
import { schema } from 'ts-transformer-json-schema';
import Validator from 'fastest';
interface IExample {
str: string;
}
const v = new Validator();
v.validate({ str: 'string' }, schema<IExample>());
import { schema } from 'ts-transformer-json-schema';
interface IUser {
name: string;
}
const GreeterService: ServiceSchema = {
actions: {
welcome: {
params: schema<IUser>(),
handler({ params: user }: Context<IUser>) {
return `Welcome, ${user.name}`;
}
}
}
}
There is moleculer template that comes with this transformer and configure compiler to use it: https://github.com/ipetrovic11/moleculer-template-typescript
Unfortunately, TypeScript itself does not currently provide any easy way to use custom transformers (See microsoft/TypeScript#14419).
See ttypescript's README for how to use this with module bundlers such as webpack or Rollup.
// tsconfig.json
{
"compilerOptions": {
// ...
"plugins": [
{ "transform": "ts-transformer-json-schema/transformer" }
]
},
// ...
}
Currently transformer can handle:
-
Interfaces
-
Neasted interfaces
-
Extended interfaces
-
Intersections and Unions
-
Enums
-
Emails - Predefined - IEmail
-
Dates - Predefined - IDate
-
UUID - Predefined - IUUID
-
Forbidden - Predefined - IForbidden
-
Additional properties
Take a look at tests for all possibilities. All cases from fastest-validator should be covered, if not please report the issue.
MIT