utils.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { get } from 'lodash-es';
  2. import { ASTFactory, type ASTNodeJSON } from '@flowgram.ai/free-layout-editor';
  3. import { type JsonSchema } from '../../typings';
  4. function sortProperties(properties: Record<string, JsonSchema>) {
  5. return Object.entries(properties).sort(
  6. (a, b) => (get(a?.[1], 'extra.index') || 0) - (get(b?.[1], 'extra.index') || 0)
  7. );
  8. }
  9. export function createASTFromJSONSchema(jsonSchema: JsonSchema): ASTNodeJSON | undefined {
  10. const { type } = jsonSchema || {};
  11. if (!type) {
  12. return undefined;
  13. }
  14. switch (type) {
  15. case 'object':
  16. return ASTFactory.createObject({
  17. properties: sortProperties(jsonSchema.properties || {}).map(([key, _property]) => ({
  18. key,
  19. type: createASTFromJSONSchema(_property),
  20. meta: { description: _property.description },
  21. })),
  22. });
  23. case 'array':
  24. return ASTFactory.createArray({
  25. items: createASTFromJSONSchema(jsonSchema.items!),
  26. });
  27. case 'string':
  28. return ASTFactory.createString();
  29. case 'number':
  30. return ASTFactory.createNumber();
  31. case 'boolean':
  32. return ASTFactory.createBoolean();
  33. case 'integer':
  34. return ASTFactory.createInteger();
  35. default:
  36. // Camel case to variable-core type
  37. return;
  38. }
  39. }