File size: 2,357 Bytes
23ac194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict'

const assert = require('node:assert/strict')
const { test } = require('node:test')
const { RefResolver } = require('../index.js')

test('should return schema refs', () => {
  const refResolver = new RefResolver()

  const schemaId = 'schemaId'
  const schema = {
    $id: 'schemaId',
    type: 'object',
    properties: {
      foo: { $ref: 'schemaId2#/definitions/foo' },
      bar: { $ref: 'schemaId3#/definitions/bar' },
      baz: {
        type: 'object',
        properties: {
          qux: { $ref: 'schemaId4#/definitions/qux' }
        }
      }
    }
  }

  refResolver.addSchema(schema)

  const schemaRefs = refResolver.getSchemaRefs(schemaId)
  assert.deepStrictEqual(schemaRefs, [
    { schemaId: 'schemaId2', jsonPointer: '#/definitions/foo' },
    { schemaId: 'schemaId3', jsonPointer: '#/definitions/bar' },
    { schemaId: 'schemaId4', jsonPointer: '#/definitions/qux' }
  ])
})

test('should return nested schema refs', () => {
  const refResolver = new RefResolver()

  const schemaId = 'schemaId'
  const subSchemaId = 'subSchemaId'

  const schema = {
    $id: 'schemaId',
    $ref: 'schemaId2#/definitions/subschema',
    definitions: {
      subschema: {
        $id: subSchemaId,
        type: 'object',
        properties: {
          foo: { $ref: 'schemaId2#/definitions/foo' },
          bar: { $ref: 'schemaId3#/definitions/bar' },
          baz: {
            type: 'object',
            properties: {
              qux: { $ref: 'schemaId4#/definitions/qux' }
            }
          }
        }
      }
    }
  }

  refResolver.addSchema(schema)

  const schemaRefs = refResolver.getSchemaRefs(schemaId)
  assert.deepStrictEqual(schemaRefs, [
    { schemaId: 'schemaId2', jsonPointer: '#/definitions/subschema' }
  ])

  const subSchemaRefs = refResolver.getSchemaRefs(subSchemaId)
  assert.deepStrictEqual(subSchemaRefs, [
    { schemaId: 'schemaId2', jsonPointer: '#/definitions/foo' },
    { schemaId: 'schemaId3', jsonPointer: '#/definitions/bar' },
    { schemaId: 'schemaId4', jsonPointer: '#/definitions/qux' }
  ])
})

test('should throw is schema does not exist', () => {
  const refResolver = new RefResolver()

  try {
    refResolver.getSchemaRefs('schemaId')
    assert.fail('should throw error')
  } catch (error) {
    assert.equal(error.message, 'Schema with id "schemaId" is not found.')
  }
})