项目作者: mrjono1

项目描述 :
Convert Joi Schemas to TypeScript interfaces
高级语言: TypeScript
项目地址: git://github.com/mrjono1/joi-to-typescript.git
创建时间: 2020-09-02T08:32:16Z
项目社区:https://github.com/mrjono1/joi-to-typescript

开源协议:MIT License

下载


joi-to-typescript

NPM version Latest Build NPM Release Build GitHub top language codecov
npm downloads
Known Vulnerabilities

joi-to-typescript on GitHub

Convert Joi Schemas to TypeScript interfaces

This will allow you to use generate TypeScript interfaces from Joi Schemas giving you confidence the schema and interface match. You no longer have to manually create the same structure again, saving you time and reducing errors.

Works with any TypeScript project and also perfectly with Hapi API requests/responses.

For generating Open Api/Swagger this project works with

The use of .meta({className:'') is preferred over .label(''), because Joi.label() is intended to be used for meaningful error message, using it for another purpose makes Joi lose a standard feature, this is especially noticeable for frontend usages of Joi. The choice of the property className is because this property is used by joi-to-swagger making this project work with other projects.

Installation Notes

This package is intended as a development time tool, so it should be installed in the devDependencies

  1. yarn add joi-to-typescript --dev
  2. # or
  3. npm install joi-to-typescript --save-dev

You will also need to install joi in the dependencies

  1. yarn add joi
  2. # or
  3. npm install joi
  • This has been built for "joi": "^17" and will not work for older versions
  • Supported node versions 18, 20

Suggested Usage

  1. Create a Schemas Folder eg. src/schemas
  2. Create a interfaces Folder eg. src/interfaces
  3. Create Joi Schemas in the Schemas folder with a file name suffix of Schemas eg. AddressSchema.ts
    • The file name suffix ensures that type file and schema file imports are not confusing

Example

Example Project

Explore the Example Projects for recommended setup, execute yarn types to run each one.

Example Schema

This example can be found in src/__tests__/readme

  1. import Joi from 'joi';
  2. // Input
  3. export const JobSchema = Joi.object({
  4. businessName: Joi.string().required(),
  5. jobTitle: Joi.string().required()
  6. }).meta({ className: 'Job' });
  7. export const WalletSchema = Joi.object({
  8. usd: Joi.number().required(),
  9. eur: Joi.number().required()
  10. })
  11. .unknown()
  12. .meta({ className: 'Wallet', unknownType: 'number' });
  13. export const PersonSchema = Joi.object({
  14. firstName: Joi.string().required(),
  15. lastName: Joi.string().required().description('Last Name'),
  16. job: JobSchema,
  17. wallet: WalletSchema
  18. }).meta({ className: 'Person' });
  19. export const PeopleSchema = Joi.array()
  20. .items(PersonSchema)
  21. .required()
  22. .meta({ className: 'People' })
  23. .description('A list of People');
  24. // Output
  25. /**
  26. * This file was automatically generated by joi-to-typescript
  27. * Do not modify this file manually
  28. */
  29. export interface Job {
  30. businessName: string;
  31. jobTitle: string;
  32. }
  33. /**
  34. * A list of People
  35. */
  36. export type People = Person[];
  37. export interface Person {
  38. firstName: string;
  39. job?: Job;
  40. /**
  41. * Last Name
  42. */
  43. lastName: string;
  44. wallet?: Wallet;
  45. }
  46. export interface Wallet {
  47. /**
  48. * Number Property
  49. */
  50. [x: string]: number;
  51. eur: number;
  52. usd: number;
  53. }
Points of Interest
  • export const PersonSchema schema must be exported
  • export const PersonSchema includes a suffix of Schema so the schema and interface are not confused when using import statements (recommended not required)
  • .meta({ className: 'Person' }); Sets interface name using TypeScript conventions (TitleCase Interface name, camelCase property name)
  • .meta({ unknownType: 'number' }); assert unknown type to number

Upgrade Notice

  • Version 1 used .label('Person') as the way to define the interface name, to use this option set { useLabelAsInterfaceName: true }

Example Call

  1. import { convertFromDirectory } from 'joi-to-typescript';
  2. convertFromDirectory({
  3. schemaDirectory: './src/schemas',
  4. typeOutputDirectory: './src/interfaces',
  5. debug: true
  6. });
  7. // or to get an interface as a string. Please note that this method is limited
  8. import { convertSchema } from 'joi-to-typescript';
  9. const resultingInterface = convertSchema({}, JobSchema);
  10. resultingInterface?.content = // the interface as a string

Settings

  1. export interface Settings {
  2. /**
  3. * The input/schema directory
  4. * Directory must exist
  5. */
  6. schemaDirectory: string;
  7. /**
  8. * The output/type directory
  9. * Will also attempt to create this directory
  10. */
  11. typeOutputDirectory: string;
  12. /**
  13. * Use .label('InterfaceName') instead of .meta({className:'InterfaceName'}) for interface names
  14. */
  15. useLabelAsInterfaceName: boolean;
  16. /**
  17. * If defined, when a schema name ends with "schema", replaces the ending in the generated type by default
  18. * with this string.
  19. * E.g. when this setting is "Interface", a `TestSchema` object generates a `TestInterface` type
  20. */
  21. defaultInterfaceSuffix?: string;
  22. /**
  23. * Should interface properties be defaulted to optional or required
  24. * @default false
  25. */
  26. defaultToRequired: boolean;
  27. /**
  28. * What schema file name suffix will be removed when creating the interface file name
  29. * @default "Schema"
  30. * This ensures that an interface and Schema with the file name are not confused
  31. */
  32. schemaFileSuffix: string;
  33. /**
  34. * If provided, appends this suffix to the generated interface filenames
  35. * @default ""
  36. */
  37. interfaceFileSuffix: string;
  38. /**
  39. * If `true` the console will include more information
  40. * @default false
  41. */
  42. debug: boolean;
  43. /**
  44. * File Header content for generated files
  45. */
  46. fileHeader: string;
  47. /**
  48. * If true will sort properties on interface by name
  49. * @default true
  50. */
  51. sortPropertiesByName: boolean;
  52. /**
  53. * If true will not output to subDirectories in output/interface directory. It will flatten the structure.
  54. */
  55. flattenTree: boolean;
  56. /**
  57. * If true will only read the files in the root directory of the input/schema directory. Will not parse through sub-directories.
  58. */
  59. rootDirectoryOnly: boolean;
  60. /**
  61. * If true will write all exports *'s to root index.ts in output/interface directory.
  62. */
  63. indexAllToRoot: boolean;
  64. /**
  65. * Comment every interface and property even with just a duplicate of the interface and property name
  66. * @default false
  67. */
  68. commentEverything: boolean;
  69. /**
  70. * List of files or folders that should be ignored from conversion. These can either be
  71. * filenames (AddressSchema.ts) or filepaths postfixed with a / (addressSchemas/)
  72. * @default []
  73. */
  74. ignoreFiles: string[];
  75. /**
  76. * The indentation characters
  77. * @default ' ' (two spaces)
  78. */
  79. indentationChacters: string;
  80. /**
  81. * If set to true, will use double quotes for strings
  82. * @default false
  83. */
  84. doublequoteEscape: boolean;
  85. /**
  86. * If a field has a default and is optional, consider it as required
  87. * @default false
  88. */
  89. treatDefaultedOptionalAsRequired: boolean;
  90. /**
  91. * If a field has a default, modify the resulting field to equal
  92. * `field: <default> | type` rather than `field: type`
  93. * @default false
  94. */
  95. supplyDefaultsInType: boolean;
  96. /**
  97. * If a field has a default value, add its stringified representation
  98. * to the JsDoc using the @default annotation
  99. * @default false
  100. */
  101. supplyDefaultsInJsDoc: boolean;
  102. /**
  103. * Filter files you wish to parse
  104. * The class `InputFileFilter` contains some default options
  105. * @default *.ts files
  106. */
  107. inputFileFilter: RegExp;
  108. /**
  109. * If true, skips the creation of index.ts files in the generated interface directories
  110. * @default false
  111. */
  112. omitIndexFiles: boolean
  113. /**
  114. * If provided, prepends the content returned by the function to the
  115. * generated interface/type code (including and JSDoc).
  116. */
  117. tsContentHeader?: (type: ConvertedType) => string;
  118. /**
  119. * If provided, appends the content returned by the function to the
  120. * generated interface/type code.
  121. */
  122. tsContentFooter?: (type: ConvertedType) => string;
  123. /**
  124. * If defined, place every member of a union on a new line
  125. */
  126. unionNewLine?: boolean;
  127. /**
  128. * If defined, place every member of a tuple on a new line
  129. */
  130. tupleNewLine?: boolean;
  131. }

Joi Features Supported

  • .meta({className:'InterfaceName'}) - interface Name and in jsDoc
  • .description('What this interface is for') - jsdoc
  • .optional() - optional properties ?
  • .required() - required properties
  • .valid(['red', 'green', 'blue']) - enumerations - allow can be used for enumerations but valid works better see _tests_/allow/allow.ts for more information
  • .allow('') - will be ignored on a string
  • .allow(null) - will add as an optional type eg string | null
  • .array(), .object(), .string(), .number(), .boolean() - standard Joi schemas
  • .alternatives() - try is supported, conditionals would be converted to any
  • .unknown(true) - will add a property [x: string]: unknown; to the interface
    • Assert unknown to some type with a stringified type or a Joi schema, e.g.:
      1. .meta({ unknownType: 'some-type' })
      1. .meta({ unknownType: Joi.object({ id: Joi.string() }) })`
  • .example() - jsdoc
  • .cast() - currently will honor casting to string and number types, map and set to be added later
  • .forbidden() will set the type to undefined
  • .meta({ readonly: true }) to create readonly properties like readonly property: string;
  • .ordered()
  • And many others

Contributing

Recommended Editor is VS Code, this project is setup with VSCode settings in the ./.vscode directory to keep development consistent.

Best developed on macOS, Linux, or on Windows via WSL.

Install nodejs via nvm so you can have multiple versions installed

  1. nvm use # using NVM to select node version
  2. yarn install # using yarn
  3. yarn test # run local tests
  4. yarn coverage # test coverage report
  5. yarn lint # lint the code

Change Log

See GitHub Releases