openapi-format icon indicating copy to clipboard operation
openapi-format copied to clipboard

Keep $ref dereference when writing the update files

Open thim81 opened this issue 2 years ago • 4 comments

Currently, openapi-format dereferences the OpenAPI documents to do its formatting, sorting, ... and write a dereferenced result.

Investigate the option to leverage: https://www.npmjs.com/package/json-refs to format the OpenAPI documents and update the $ref values in different files.

const jsonRefs = require('json-refs');

const json = {
  "foo": {
    "$ref": "#/bar"
  },
  "bar": {
    "baz": "qux"
  }
};

const options = {
  filter: ['relative', 'remote'],
  loaderOptions: {
    processContent: (res, callback) => callback(undefined, res.text)
  }
};

jsonRefs.resolveRefs(json, options).then(
  (results) => {
    // make changes to the resolved object
    results.resolved.bar.baz = "newValue";
    // write the changes to the $ref locations
    jsonRefs.updateRefs(results.refs, results.resolved).then(
      (updated) => console.log(updated),
      (err) => console.log(err)
    );
  },
  (err) => console.log(err)
);

thim81 avatar Jan 16 '23 21:01 thim81

yes this would be great. in addition we make heavily use of $ref to other files what the best solution to tackle those? format one file after the other?

rngtng avatar Mar 28 '23 16:03 rngtng

You could try to do them one by one, although it is not ideal and I m not sure it it would work fully.

Another approach could be to use a good diff tool and diff the final, formatted result with the various files. Also not ideal.

Ideally, would be to have openapi-format support referenced files. I need to find time to play with the json-ref library. If you or anybody else are interested, I always welcome PRs.

thim81 avatar Mar 28 '23 18:03 thim81

Cool thanks a lot. I‘ll explore myself options too..

rngtng avatar Mar 28 '23 18:03 rngtng

hi @rngtng

With the release 1.24.0 of OpenAPI, we introduced the option to split OpenAPI files in a file/folder structure.

The split is a programmatically break-up of the OpenAPI in 1 main OpenAPI and per path and per component a separate file, with this kind of process flow.

graph TD
    A[Start] --> B[Load OpenAPI Split File]
    
    B --> C[Apply Bundling]
    C --> D[Apply Filtering]
    D --> E[Apply Sorting]
    
    E --> F{Split OpenAPI?}
    
    F -- Yes --> G[Split into Multiple Files]
    F -- No --> H[Save as Single File]
    
    G --> I[Save Modular Structure]
    H --> I[Save Final Output]
    
    I --> J[End]

You can give it a try

npx openapi-format https://raw.githubusercontent.com/thim81/openapi-format/refs/heads/main/test/__utils__/train.yaml -o split/train.yaml --split

Let me know what you think of it.

thim81 avatar Sep 27 '24 17:09 thim81