UNPKG

5.57 kBJavaScriptView Raw
1'use strict'
2
3const fastClone = require('rfdc')({ circles: false, proto: true })
4const { kSchemaVisited } = require('./symbols')
5const kFluentSchema = Symbol.for('fluent-schema-object')
6
7const {
8 codes: {
9 FST_ERR_SCH_MISSING_ID,
10 FST_ERR_SCH_ALREADY_PRESENT,
11 FST_ERR_SCH_NOT_PRESENT,
12 FST_ERR_SCH_DUPLICATE
13 }
14} = require('./errors')
15
16const URI_NAME_FRAGMENT = /^#[A-Za-z]{1}[\w-:.]{0,}$/
17
18function Schemas () {
19 this.store = {}
20}
21
22Schemas.prototype.add = function (inputSchema, refResolver) {
23 var schema = fastClone((inputSchema.isFluentSchema || inputSchema[kFluentSchema])
24 ? inputSchema.valueOf()
25 : inputSchema
26 )
27 const id = schema.$id
28 if (id === undefined) {
29 throw new FST_ERR_SCH_MISSING_ID()
30 }
31
32 if (this.store[id] !== undefined) {
33 throw new FST_ERR_SCH_ALREADY_PRESENT(id)
34 }
35
36 this.store[id] = this.resolveRefs(schema, true, refResolver)
37}
38
39Schemas.prototype.resolve = function (id) {
40 if (this.store[id] === undefined) {
41 throw new FST_ERR_SCH_NOT_PRESENT(id)
42 }
43 return Object.assign({}, this.store[id])
44}
45
46Schemas.prototype.resolveRefs = function (routeSchemas, dontClearId, refResolver) {
47 if (routeSchemas[kSchemaVisited]) {
48 return routeSchemas
49 }
50
51 // alias query to querystring schema
52 if (routeSchemas.query) {
53 // check if our schema has both querystring and query
54 if (routeSchemas.querystring) {
55 throw new FST_ERR_SCH_DUPLICATE('querystring')
56 }
57 routeSchemas.querystring = routeSchemas.query
58 }
59
60 // let's check if our schemas have a custom prototype
61 for (const key of ['headers', 'querystring', 'params', 'body']) {
62 if (typeof routeSchemas[key] === 'object' && Object.getPrototypeOf(routeSchemas[key]) !== Object.prototype) {
63 return routeSchemas
64 }
65 }
66
67 // See issue https://github.com/fastify/fastify/issues/1767
68 const cachedSchema = Object.assign({}, routeSchemas)
69
70 try {
71 // this will work only for standard json schemas
72 // other compilers such as Joi will fail
73 this.traverse(routeSchemas, refResolver)
74
75 // when a plugin uses the 'skip-override' and call addSchema
76 // the same JSON will be pass throug all the avvio tree. In this case
77 // it is not possible clean the id. The id will be cleared
78 // in the startup phase by the call of validation.js. Details PR #1496
79 if (dontClearId !== true) {
80 this.cleanId(routeSchemas)
81 }
82 } catch (err) {
83 // if we have failed because `resolve` has thrown
84 // let's rethrow the error and let avvio handle it
85 if (/FST_ERR_SCH_*/.test(err.code)) throw err
86
87 // otherwise, the schema must not be a JSON schema
88 // so we let the user configured schemaCompiler handle it
89 return cachedSchema
90 }
91
92 if (routeSchemas.headers) {
93 routeSchemas.headers = this.getSchemaAnyway(routeSchemas.headers)
94 }
95
96 if (routeSchemas.querystring) {
97 routeSchemas.querystring = this.getSchemaAnyway(routeSchemas.querystring)
98 }
99
100 if (routeSchemas.params) {
101 routeSchemas.params = this.getSchemaAnyway(routeSchemas.params)
102 }
103
104 routeSchemas[kSchemaVisited] = true
105 return routeSchemas
106}
107
108Schemas.prototype.traverse = function (schema, refResolver) {
109 for (var key in schema) {
110 // resolve the `sharedSchemaId#' only if is not a standard $ref JSON Pointer
111 if (typeof schema[key] === 'string' && key !== '$schema' && key !== '$ref' && schema[key].slice(-1) === '#') {
112 schema[key] = this.resolve(schema[key].slice(0, -1))
113 } else if (key === '$ref' && refResolver) {
114 const refValue = schema[key]
115
116 const framePos = refValue.indexOf('#')
117 const refId = framePos >= 0 ? refValue.slice(0, framePos) : refValue
118 if (refId.length > 0 && !this.store[refId]) {
119 const resolvedSchema = refResolver(refId)
120 if (resolvedSchema) {
121 this.add(resolvedSchema, refResolver)
122 }
123 }
124 }
125
126 if (schema[key] !== null && typeof schema[key] === 'object' &&
127 (key !== 'enum' || (key === 'enum' && schema.type !== 'string'))) {
128 // don't traverse non-object values and the `enum` keyword when used for string type
129 this.traverse(schema[key], refResolver)
130 }
131 }
132}
133
134Schemas.prototype.cleanId = function (schema) {
135 for (var key in schema) {
136 if (key === '$id' && !URI_NAME_FRAGMENT.test(schema[key])) {
137 delete schema[key]
138 }
139 if (schema[key] !== null && typeof schema[key] === 'object') {
140 this.cleanId(schema[key])
141 }
142 }
143}
144
145Schemas.prototype.getSchemaAnyway = function (schema) {
146 if (schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema
147 if (!schema.type || !schema.properties) {
148 return {
149 type: 'object',
150 properties: schema
151 }
152 }
153 return schema
154}
155
156Schemas.prototype.getSchemas = function () {
157 return Object.assign({}, this.store)
158}
159
160Schemas.prototype.getJsonSchemas = function (options) {
161 const store = this.getSchemas()
162 const schemasArray = Object.keys(store).map(schemaKey => {
163 // if the shared-schema "replace-way" has been used, the $id field has been removed
164 if (store[schemaKey].$id === undefined) {
165 store[schemaKey].$id = schemaKey
166 }
167 return store[schemaKey]
168 })
169
170 if (options && options.onlyAbsoluteUri === true) {
171 // the caller wants only the absolute URI (without the shared schema - "replace-way" usage)
172 return schemasArray.filter(_ => !/^\w*$/g.test(_.$id))
173 }
174 return schemasArray
175}
176
177function buildSchemas (s) {
178 const schema = new Schemas()
179 s.getJsonSchemas().forEach(_ => schema.add(_))
180 return schema
181}
182
183module.exports = { Schemas, buildSchemas }