inputSchemasToEntitySchemas.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import fs from 'fs'
  2. import path from 'path'
  3. import {
  4. AddClassSchema,
  5. HashProperty,
  6. Property,
  7. ReferenceProperty,
  8. SinglePropertyVariant,
  9. TextProperty,
  10. VecPropertyVariant,
  11. } from '../types/extrinsics/AddClassSchema'
  12. import PRIMITIVE_PROPERTY_DEFS from '../schemas/propertyValidationDefs.schema.json'
  13. import { getInputs } from '../src/helpers/inputs'
  14. import { getSchemasLocation, SCHEMA_TYPES } from '../src/helpers/schemas'
  15. import { JSONSchema7 } from 'json-schema'
  16. const schemaInputs = getInputs<AddClassSchema>('schemas')
  17. const strictObjectDef = (def: Record<string, any>): JSONSchema7 => ({
  18. type: 'object',
  19. additionalProperties: false,
  20. ...def,
  21. })
  22. const onePropertyObjectDef = (propertyName: string, propertyDef: Record<string, any>): JSONSchema7 =>
  23. strictObjectDef({
  24. required: [propertyName],
  25. properties: {
  26. [propertyName]: propertyDef,
  27. },
  28. })
  29. const TextPropertyDef = ({ Text: maxLength }: TextProperty): JSONSchema7 => ({
  30. type: 'string',
  31. maxLength,
  32. })
  33. const HashPropertyDef = ({ Hash: maxLength }: HashProperty): JSONSchema7 => ({
  34. type: 'string',
  35. maxLength,
  36. })
  37. const ReferencePropertyDef = ({ Reference: ref }: ReferenceProperty): JSONSchema7 => ({
  38. 'oneOf': [
  39. onePropertyObjectDef('new', { '$ref': `./${ref.className}Entity.schema.json` }),
  40. onePropertyObjectDef('existing', { '$ref': `../entityReferences/${ref.className}Ref.schema.json` }),
  41. PRIMITIVE_PROPERTY_DEFS.definitions.Uint64 as JSONSchema7,
  42. ],
  43. })
  44. const SinglePropertyDef = ({ Single: singlePropType }: SinglePropertyVariant): JSONSchema7 => {
  45. if (typeof singlePropType === 'string') {
  46. return PRIMITIVE_PROPERTY_DEFS.definitions[singlePropType] as JSONSchema7
  47. } else if ((singlePropType as TextProperty).Text) {
  48. return TextPropertyDef(singlePropType as TextProperty)
  49. } else if ((singlePropType as HashProperty).Hash) {
  50. return HashPropertyDef(singlePropType as HashProperty)
  51. } else if ((singlePropType as ReferenceProperty).Reference) {
  52. return ReferencePropertyDef(singlePropType as ReferenceProperty)
  53. }
  54. throw new Error(`Unknown single proprty type: ${JSON.stringify(singlePropType)}`)
  55. }
  56. const VecPropertyDef = ({ Vector: vec }: VecPropertyVariant): JSONSchema7 => ({
  57. type: 'array',
  58. maxItems: vec.max_length,
  59. 'items': SinglePropertyDef({ Single: vec.vec_type }),
  60. })
  61. const PropertyDef = ({ property_type: propertyType, description }: Property): JSONSchema7 => ({
  62. ...((propertyType as SinglePropertyVariant).Single
  63. ? SinglePropertyDef(propertyType as SinglePropertyVariant)
  64. : VecPropertyDef(propertyType as VecPropertyVariant)),
  65. description,
  66. })
  67. // Mkdir entity schemas directories if they do not exist
  68. SCHEMA_TYPES.forEach((type) => {
  69. if (!fs.existsSync(getSchemasLocation(type))) {
  70. fs.mkdirSync(getSchemasLocation(type))
  71. }
  72. })
  73. // Run schema conversion:
  74. schemaInputs.forEach(({ fileName, data: inputData }) => {
  75. const schemaName = fileName.replace('Schema.json', '')
  76. if (inputData.newProperties && !inputData.existingProperties) {
  77. const properites = inputData.newProperties
  78. const propertiesObj = properites.reduce((pObj, p) => {
  79. pObj[p.name] = PropertyDef(p)
  80. return pObj
  81. }, {} as Record<string, ReturnType<typeof PropertyDef>>)
  82. const EntitySchema: JSONSchema7 = {
  83. $schema: 'http://json-schema.org/draft-07/schema',
  84. $id: `https://joystream.org/entities/${schemaName}Entity.schema.json`,
  85. title: `${schemaName}Entity`,
  86. description: `JSON schema for entities based on ${schemaName} runtime schema`,
  87. ...strictObjectDef({
  88. required: properites.filter((p) => p.required).map((p) => p.name),
  89. properties: propertiesObj,
  90. }),
  91. }
  92. const ReferenceSchema: JSONSchema7 = {
  93. $schema: 'http://json-schema.org/draft-07/schema',
  94. $id: `https://joystream.org/entityReferences/${schemaName}Ref.schema.json`,
  95. title: `${schemaName}Reference`,
  96. description: `JSON schema for reference to ${schemaName} entity based on runtime schema`,
  97. anyOf: [
  98. ...properites.filter((p) => p.required && p.unique).map((p) => onePropertyObjectDef(p.name, PropertyDef(p))),
  99. PRIMITIVE_PROPERTY_DEFS.definitions.Uint64 as JSONSchema7,
  100. ],
  101. }
  102. const BatchSchema: JSONSchema7 = {
  103. $schema: 'http://json-schema.org/draft-07/schema',
  104. $id: `https://joystream.org/entityBatches/${schemaName}Batch.schema.json`,
  105. title: `${schemaName}Batch`,
  106. description: `JSON schema for batch of entities based on ${schemaName} runtime schema`,
  107. ...strictObjectDef({
  108. required: ['className', 'entries'],
  109. properties: {
  110. className: { type: 'string' },
  111. entries: {
  112. type: 'array',
  113. items: { '$ref': `../entities/${schemaName}Entity.schema.json` },
  114. },
  115. },
  116. }),
  117. }
  118. const entitySchemaPath = path.join(getSchemasLocation('entities'), `${schemaName}Entity.schema.json`)
  119. fs.writeFileSync(entitySchemaPath, JSON.stringify(EntitySchema, undefined, 4))
  120. console.log(`${entitySchemaPath} succesfully generated!`)
  121. const entityReferenceSchemaPath = path.join(getSchemasLocation('entityReferences'), `${schemaName}Ref.schema.json`)
  122. fs.writeFileSync(entityReferenceSchemaPath, JSON.stringify(ReferenceSchema, undefined, 4))
  123. console.log(`${entityReferenceSchemaPath} succesfully generated!`)
  124. const batchOfEntitiesSchemaPath = path.join(getSchemasLocation('entityBatches'), `${schemaName}Batch.schema.json`)
  125. fs.writeFileSync(batchOfEntitiesSchemaPath, JSON.stringify(BatchSchema, undefined, 4))
  126. console.log(`${batchOfEntitiesSchemaPath} succesfully generated!`)
  127. } else {
  128. console.log('WARNING: Schemas with "existingProperties" not supported yet!')
  129. console.log('Skipping...')
  130. }
  131. })