Skip to content

Instantly share code, notes, and snippets.

@mattpocock
Last active May 30, 2019 12:25
Show Gist options
  • Save mattpocock/e50142182e9953d1abc63763d799b9a0 to your computer and use it in GitHub Desktop.
Save mattpocock/e50142182e9953d1abc63763d799b9a0 to your computer and use it in GitHub Desktop.
Autogenerate forms based on JSON API

Auto Generating forms (or an entire admin application?) based on JSON API models

I've been thinking more and more about how we can automate the generation of FE code based on knowledge of the BE model. I feel strongly that if the BE changes, the FE should be able to automatically react.

This should definitely be true when inputting data to mutations.

// AssetInputForm.jsx

// auto-generated JSON from API schema
import assetInputSchema from 'schema/assetInputSchema.json';

// A function that allows the FE dev to customise aspects of the form
import customiseSchema from 'utils/customiseSchema';

const modifiedSchema = customiseSchema(
  assetInputSchema,
  {
    // Look for a field called 'description' and set its type to longtext
    description: {
      type: 'longtext'
    }
  }
)

export default () => <SchemaForm schema={modifiedSchema} />
// SchemaForm.jsx

import { SchemaFormBuilder } from 'schema-form-builder';

const typeResolvers = {
  string: ({
    isRequired,
    value,
    onChange,
    error,
    warning
  }) => <Input required={isRequired} value={value} onChange={onChange} />,
  longtext: () => <TextArea />,
  // ...etc
}

export default <SchemaFormBuilder typeResolvers={typeResolvers}} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment