oas icon indicating copy to clipboard operation
oas copied to clipboard

Support for conditionally dereferencing with `getReference/findReference` class methods

Open huypham50 opened this issue 7 months ago • 1 comments

My current logic looks like this

const oasNormalizer = new OASNormalize(url)
const validatedSchema = await oasNormalizer.validate()
const schema = new Oas(validatedSchema);
await schema.dereference()

// skipping some traverse logic

let reqBodySchema: MediaTypeObject['schema'] = undefined
if (reqBodySchema) {
  if ('type' in reqBodySchema) {
    console.log('type:', reqBodySchema.type)
  } else if ('$ref' in reqBodySchema) { // we should not need to do this because the schema has been dereferenced
    console.log('ref:', reqBodySchema.$ref)
  }
}

At this point, since the schema has been dereferenced, should we narrow the types so we don't have to do type narrowing? Something like this:

// dereferencedSchema returns a narrower type of schema that removes RefObject from `X | RefObject`
const dereferencedSchema = await schema.dereference()

Also, is there a way conditionally dereference schema? Something like this:

if ('$ref' in reqBodySchema) {
  const ref = reqBodySchema.$ref // ref is a string
  const refSchema1 = schema.getReference(ref) // return schema or throw error
  const refSchema2 = schema.findReference(ref) // return schema or undefined
}

Let me know if I am doing anything that is not standard. New to this (great) library. Also recommendations for great Typescript libraries for the OpenAPI / JSONSchema ecosystem would be greatly appreciated!

huypham50 avatar Nov 14 '23 06:11 huypham50

This is tricky because technically after dereferencing $ref may still be present if there was a circular reference present. I'm definitely not opposed to adding some getReference and findReference tooling into oas core. If you're interested in doing that work we'd happily pull it in.

erunion avatar Nov 14 '23 18:11 erunion