Search code examples
swagger-uirswag

How to programatically set field values in Swagger UI


I'm using Rswag and Swagger UI, and I have two inputs on my form that I want to load dynamically from server side data, called date_range_start and date_range_end. The values I want to set are based on the current date and the timezone of the user, so I don't want to put them directly as examples in the openapi spec, but instead fetch them server side and update the form on load.

I have the same question as was asked here. I'm reasking it because I don't think the approach discussed there is likely to be the right way to do this. The approach they're taking seems to be hacky, directly manipulating the DOM, instead of using Swagger UI functions. Is there a way within SwaggerUI to set fields on load?

I would probably put it inside this where you see the comment:

configObject.onComplete = {
  // set specific form input values based on fetch
}
const ui = SwaggerUIBundle(configObject);

I don't need help with the fetch part of it, just trying to understand how you can set parameter form values programmatically in swagger ui.


Solution

  • I found that I could adapt this approach, and set default values in particular cases. Note that dispatchInitialValue=false allows you to actually clear out any examples from the input; on my version of Swagger it doesn't send those examples by default like you see claimed in the linked post.

    const SetDefaultParamsPlugin = () => ({
      wrapComponents: {
        JsonSchemaForm: (Original, { React }) => ({ value, description, ...props }) => {
          let dispatchInitialValue = true;
          if (description == "date_range_start") {
            value = defaultRangeStart;
          } else if (description == "date_range_end") {
            value = defaultRangeEnd;
          } else {
            dispatchInitialValue = false;
          }
    
          return React.createElement(Original, { ...props, value, description: value, dispatchInitialValue })
        }
      },
    });
    
    configObject.plugins = [SetDefaultParamsPlugin];