strong-tie/inbound-calls
0
1'use strict'2 3const {4 kSchemaHeaders: headersSchema,5 kSchemaParams: paramsSchema,6 kSchemaQuerystring: querystringSchema,7 kSchemaBody: bodySchema,8 kSchemaResponse: responseSchema9} = require('./symbols')10const scChecker = /^[1-5](?:\d{2}|xx)$|^default$/11 12const {13 FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX14} = require('./errors')15 16const { FSTWRN001 } = require('./warnings')17 18function compileSchemasForSerialization (context, compile) {19 if (!context.schema || !context.schema.response) {20 return21 }22 const { method, url } = context.config || {}23 context[responseSchema] = Object.keys(context.schema.response)24 .reduce(function (acc, statusCode) {25 const schema = context.schema.response[statusCode]26 statusCode = statusCode.toLowerCase()27 if (!scChecker.test(statusCode)) {28 throw new FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX()29 }30 31 if (schema.content) {32 const contentTypesSchemas = {}33 for (const mediaName of Object.keys(schema.content)) {34 const contentSchema = schema.content[mediaName].schema35 contentTypesSchemas[mediaName] = compile({36 schema: contentSchema,37 url,38 method,39 httpStatus: statusCode,40 contentType: mediaName41 })42 }43 acc[statusCode] = contentTypesSchemas44 } else {45 acc[statusCode] = compile({46 schema,47 url,48 method,49 httpStatus: statusCode50 })51 }52 53 return acc54 }, {})55}56 57function compileSchemasForValidation (context, compile, isCustom) {58 const { schema } = context59 if (!schema) {60 return61 }62 63 const { method, url } = context.config || {}64 65 const headers = schema.headers66 // the or part is used for backward compatibility67 if (headers && (isCustom || Object.getPrototypeOf(headers) !== Object.prototype)) {68 // do not mess with schema when custom validator applied, e.g. Joi, Typebox69 context[headersSchema] = compile({ schema: headers, method, url, httpPart: 'headers' })70 } else if (headers) {71 // The header keys are case insensitive72 // https://datatracker.ietf.org/doc/html/rfc2616#section-4.273 const headersSchemaLowerCase = {}74 Object.keys(headers).forEach(k => { headersSchemaLowerCase[k] = headers[k] })75 if (headersSchemaLowerCase.required instanceof Array) {76 headersSchemaLowerCase.required = headersSchemaLowerCase.required.map(h => h.toLowerCase())77 }78 if (headers.properties) {79 headersSchemaLowerCase.properties = {}80 Object.keys(headers.properties).forEach(k => {81 headersSchemaLowerCase.properties[k.toLowerCase()] = headers.properties[k]82 })83 }84 context[headersSchema] = compile({ schema: headersSchemaLowerCase, method, url, httpPart: 'headers' })85 } else if (Object.hasOwn(schema, 'headers')) {86 FSTWRN001('headers', method, url)87 }88 89 if (schema.body) {90 const contentProperty = schema.body.content91 if (contentProperty) {92 const contentTypeSchemas = {}93 for (const contentType of Object.keys(contentProperty)) {94 const contentSchema = contentProperty[contentType].schema95 contentTypeSchemas[contentType] = compile({ schema: contentSchema, method, url, httpPart: 'body', contentType })96 }97 context[bodySchema] = contentTypeSchemas98 } else {99 context[bodySchema] = compile({ schema: schema.body, method, url, httpPart: 'body' })100 }101 } else if (Object.hasOwn(schema, 'body')) {102 FSTWRN001('body', method, url)103 }104 105 if (schema.querystring) {106 context[querystringSchema] = compile({ schema: schema.querystring, method, url, httpPart: 'querystring' })107 } else if (Object.hasOwn(schema, 'querystring')) {108 FSTWRN001('querystring', method, url)109 }110 111 if (schema.params) {112 context[paramsSchema] = compile({ schema: schema.params, method, url, httpPart: 'params' })113 } else if (Object.hasOwn(schema, 'params')) {114 FSTWRN001('params', method, url)115 }116}117 118function validateParam (validatorFunction, request, paramName) {119 const isUndefined = request[paramName] === undefined120 const ret = validatorFunction && validatorFunction(isUndefined ? null : request[paramName])121 122 if (ret?.then) {123 return ret124 .then((res) => { return answer(res) })125 .catch(err => { return err }) // return as simple error (not throw)126 }127 128 return answer(ret)129 130 function answer (ret) {131 if (ret === false) return validatorFunction.errors132 if (ret && ret.error) return ret.error133 if (ret && ret.value) request[paramName] = ret.value134 return false135 }136}137 138function validate (context, request, execution) {139 const runExecution = execution === undefined140 141 if (runExecution || !execution.skipParams) {142 const params = validateParam(context[paramsSchema], request, 'params')143 if (params) {144 if (typeof params.then !== 'function') {145 return wrapValidationError(params, 'params', context.schemaErrorFormatter)146 } else {147 return validateAsyncParams(params, context, request)148 }149 }150 }151 152 if (runExecution || !execution.skipBody) {153 let validatorFunction = null154 if (typeof context[bodySchema] === 'function') {155 validatorFunction = context[bodySchema]156 } else if (context[bodySchema]) {157 // TODO: add request.contentType and reuse it here158 const contentType = request.headers['content-type']?.split(';', 1)[0]159 const contentSchema = context[bodySchema][contentType]160 if (contentSchema) {161 validatorFunction = contentSchema162 }163 }164 const body = validateParam(validatorFunction, request, 'body')165 if (body) {166 if (typeof body.then !== 'function') {167 return wrapValidationError(body, 'body', context.schemaErrorFormatter)168 } else {169 return validateAsyncBody(body, context, request)170 }171 }172 }173 174 if (runExecution || !execution.skipQuery) {175 const query = validateParam(context[querystringSchema], request, 'query')176 if (query) {177 if (typeof query.then !== 'function') {178 return wrapValidationError(query, 'querystring', context.schemaErrorFormatter)179 } else {180 return validateAsyncQuery(query, context, request)181 }182 }183 }184 185 const headers = validateParam(context[headersSchema], request, 'headers')186 if (headers) {187 if (typeof headers.then !== 'function') {188 return wrapValidationError(headers, 'headers', context.schemaErrorFormatter)189 } else {190 return validateAsyncHeaders(headers, context, request)191 }192 }193 194 return false195}196 197function validateAsyncParams (validatePromise, context, request) {198 return validatePromise199 .then((paramsResult) => {200 if (paramsResult) {201 return wrapValidationError(paramsResult, 'params', context.schemaErrorFormatter)202 }203 204 return validate(context, request, { skipParams: true })205 })206}207 208function validateAsyncBody (validatePromise, context, request) {209 return validatePromise210 .then((bodyResult) => {211 if (bodyResult) {212 return wrapValidationError(bodyResult, 'body', context.schemaErrorFormatter)213 }214 215 return validate(context, request, { skipParams: true, skipBody: true })216 })217}218 219function validateAsyncQuery (validatePromise, context, request) {220 return validatePromise221 .then((queryResult) => {222 if (queryResult) {223 return wrapValidationError(queryResult, 'querystring', context.schemaErrorFormatter)224 }225 226 return validate(context, request, { skipParams: true, skipBody: true, skipQuery: true })227 })228}229 230function validateAsyncHeaders (validatePromise, context, request) {231 return validatePromise232 .then((headersResult) => {233 if (headersResult) {234 return wrapValidationError(headersResult, 'headers', context.schemaErrorFormatter)235 }236 237 return false238 })239}240 241function wrapValidationError (result, dataVar, schemaErrorFormatter) {242 if (result instanceof Error) {243 result.statusCode = result.statusCode || 400244 result.code = result.code || 'FST_ERR_VALIDATION'245 result.validationContext = result.validationContext || dataVar246 return result247 }248 249 const error = schemaErrorFormatter(result, dataVar)250 error.statusCode = error.statusCode || 400251 error.code = error.code || 'FST_ERR_VALIDATION'252 error.validation = result253 error.validationContext = dataVar254 return error255}256 257module.exports = {258 symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema },259 compileSchemasForValidation,260 compileSchemasForSerialization,261 validate262}263 