schemasToTS.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import fs from 'fs'
  2. import path from 'path'
  3. import { compileFromFile } from 'json-schema-to-typescript'
  4. // TODO: This will require publishing @joystream/prettier-config if we want to include it in joystream-js
  5. import prettierConfig from '@joystream/prettier-config'
  6. const SCHEMAS_LOCATION = path.join(__dirname, '../schemas')
  7. const OUTPUT_TYPES_LOCATION = path.join(__dirname, '../types')
  8. const SUBDIRS_INCLUDED = ['extrinsics', 'entities'] as const
  9. async function main() {
  10. // Create typescript files
  11. for (const subdirName of fs.readdirSync(SCHEMAS_LOCATION)) {
  12. if (!SUBDIRS_INCLUDED.includes(subdirName as any)) {
  13. console.log(`Subdir/filename not included: ${subdirName} - skipping...`)
  14. continue
  15. }
  16. const schemaSubdir = subdirName as typeof SUBDIRS_INCLUDED[number]
  17. const indexExportedTypes: string[] = []
  18. for (const schemaFilename of fs.readdirSync(path.join(SCHEMAS_LOCATION, schemaSubdir))) {
  19. const schemaFilePath = path.join(SCHEMAS_LOCATION, schemaSubdir, schemaFilename)
  20. const mainTypeName = schemaFilename.replace('.schema.json', '')
  21. const outputFilename = mainTypeName + '.d.ts'
  22. indexExportedTypes.push(mainTypeName)
  23. const outputDir = path.join(OUTPUT_TYPES_LOCATION, schemaSubdir)
  24. if (!fs.existsSync(outputDir)) {
  25. fs.mkdirSync(outputDir)
  26. }
  27. const outputFilePath = path.join(outputDir, outputFilename)
  28. try {
  29. await compileFromFile(schemaFilePath, {
  30. cwd: path.join(SCHEMAS_LOCATION, schemaSubdir),
  31. style: prettierConfig,
  32. }).then((ts) => {
  33. fs.writeFileSync(outputFilePath, ts)
  34. console.log(`${outputFilePath} succesfully generated!`)
  35. })
  36. } catch (e) {
  37. console.log(`${outputFilePath} compilation FAILED!`)
  38. console.error(e)
  39. }
  40. }
  41. // Generate main index.d.ts export file for entities
  42. const indexFilePath = path.join(OUTPUT_TYPES_LOCATION, schemaSubdir, 'index.d.ts')
  43. fs.writeFileSync(
  44. indexFilePath,
  45. indexExportedTypes.reduce((content, typeName) => (content += `export { ${typeName} } from './${typeName}'\n`), '')
  46. )
  47. console.log(`${indexFilePath} succesfully generated!`)
  48. }
  49. }
  50. main()
  51. .then(() => process.exit())
  52. .catch((e) => console.error(e))