schemasToTS.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. for (const subdirName of fs.readdirSync(SCHEMAS_LOCATION)) {
  11. if (!SUBDIRS_INCLUDED.includes(subdirName as any)) {
  12. console.log(`Subdir/filename not included: ${subdirName} - skipping...`)
  13. continue
  14. }
  15. const schemaSubdir = subdirName as typeof SUBDIRS_INCLUDED[number]
  16. for (const schemaFilename of fs.readdirSync(path.join(SCHEMAS_LOCATION, schemaSubdir))) {
  17. const schemaFilePath = path.join(SCHEMAS_LOCATION, schemaSubdir, schemaFilename)
  18. const outputFilename = schemaFilename.replace('.schema.json', '.d.ts')
  19. const outputDir = path.join(OUTPUT_TYPES_LOCATION, schemaSubdir)
  20. if (!fs.existsSync(outputDir)) {
  21. fs.mkdirSync(outputDir)
  22. }
  23. const outputFilePath = path.join(outputDir, outputFilename)
  24. try {
  25. await compileFromFile(schemaFilePath, {
  26. cwd: path.join(SCHEMAS_LOCATION, schemaSubdir),
  27. style: prettierConfig,
  28. }).then((ts) => {
  29. fs.writeFileSync(outputFilePath, ts)
  30. console.log(`${outputFilePath} succesfully generated!`)
  31. })
  32. } catch (e) {
  33. console.log(`${outputFilePath} compilation FAILED!`)
  34. console.error(e)
  35. }
  36. }
  37. }
  38. }
  39. main()
  40. .then(() => process.exit())
  41. .catch((e) => console.error(e))