# json-schema-ref-resolver
[](https://github.com/fastify/json-schema-ref-resolver/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/json-schema-ref-resolver)
[](https://github.com/neostandard/neostandard)
__json-schema-ref-resolver__ is a javascript library that resolves references in [JSON schemas](https://json-schema.org/draft/2020-12/json-schema-core#name-introduction).
- [Installation](#installation)
- [Usage](#usage)
- [API](#api)
- [RefResolver([options])](#refresolveroptions)
- [addSchema(schema, [schemaId])](#addschemaschema-schemaid)
- [getSchema(schemaId, [jsonPointer])](#getschemaschemaid-jsonpointer)
- [getSchemaRefs(schemaId)](#getschemarefsschemaid)
- [getSchemaDependencies(schemaId)](#getschemadependenciesschemaid)
- [derefSchema(schemaId)](#derefschemaschemaid)
- [getDerefSchema(schemaId, [jsonPointer])](#getderefschemaschemaid-jsonpointer)
- [Caveats](#caveats)
## Installation
```bash
npm install json-schema-ref-resolver
```
## Usage
```javascript
const assert = require('node:assert')
const { RefResolver } = require('json-schema-ref-resolver')
const sourceSchema = {
$id: 'sourceSchema',
type: 'object',
properties: {
foo: {
$ref: 'targetSchema#/definitions/bar'
}
}
}
const targetSchema = {
$id: 'targetSchema',
definitions: {
bar: {
type: 'string'
}
}
}
const refResolver = new RefResolver()
refResolver.addSchema(sourceSchema)
refResolver.addSchema(targetSchema)
const derefSourceSchema = refResolver.getDerefSchema('sourceSchema')
assert.deepStrictEqual(derefSourceSchema, {
$id: 'sourceSchema',
type: 'object',
properties: {
foo: {
type: 'string'
}
}
})
```
## API
#### RefResolver([options])
- __allowEqualDuplicates__ - if set to `false`, an error will be thrown if a schema with the same `$id` is added to the resolver. If set to `true`, the error will be thrown only if the schemas are not equal. Default: `true`.
- __insertRefSymbol__ - if set to `true` resolver inserts a `Symbol.for('json-schema-ref')` instead of the `$ref` property when dereferencing a schema. Default `false`.
- __cloneSchemaWithoutRefs__ - if set to `false` resolver would not clone a schema if it does not have references. That allows to significantly improve performance when dereferencing a schema. If you want to modify a schema after dereferencing, set this option to `true`. Default: `false`.
#### addSchema(schema, [schemaId])
Adds a json schema to the resolver. If the schema has an `$id` property, it will be used as the schema id. Otherwise, the `schemaId` argument will be used as the schema id. During the addition of the schema, ref resolver will find and add all nested schemas and references.
- `schema` __\