Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

transform joi to json not working with latest fastify #373

Closed
alexanderniebuhr opened this issue Mar 3, 2021 · 6 comments · Fixed by #374
Closed

transform joi to json not working with latest fastify #373

alexanderniebuhr opened this issue Mar 3, 2021 · 6 comments · Fixed by #374

Comments

@alexanderniebuhr
Copy link
Contributor

🐛 Bug Report

A clear and concise description of what the bug is.

To Reproduce

Steps to reproduce the behavior:

const Joi = require('@hapi/joi')
const convert = require('joi-to-json-schema')

server.register(swagger, {
  routePrefix: '/documentation',
  openapi: {
    info: {
      title: 'Test swagger',
      description: 'testing the fastify swagger api',
      version: '0.1.0'
    },
  },
  exposeRoute: true,
  transform: schema => {
    const {
      params = undefined,
      body = undefined,
      querystring = undefined,
      response = undefined,
      ...others
    } = schema
    const transformed = { ...others }
    if (params) transformed.params = convert(params)
    if (body) transformed.body = convert(body)
    if (querystring) transformed.querystring = convert(querystring)
    if (response) transformed.response = convert(response)
    return transformed
  }
})

fastify.post('/the/url', {
  schema: {
    body: Joi.object().keys({
      hello: Joi.string().required()
    }).required()
  },
  validatorCompiler: ({ schema, method, url, httpPart }) => {
    return data => schema.validate(data)
  }
}, handler)

Expected behavior

A clear and concise description of what you expected to happen.

 -- converts to json schema and swagger ui loads without issue

Actual behavior

{"level":50,"time":1614766137739,"pid":28616,"hostname":"DESKTOP-GR2CUIQ","reqId":"req-7","req":{"method":"GET","url":"/documentation/json","hostname":"localhost:3000","remoteAddress":"::1","remotePort":56077},"res":{"statusCode":500},"err":{"type":"AssertionError","message":"requires a joi schema object","stack":"AssertionError [ERR_ASSERTION]: requires a joi schema object\n    at convert (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\joi-to-json-schema@5.1.0\\node_modules\\joi-to-json-schema\\build\\index.js:235:24)\n    at Object.transform (file:///C:/Users/Alexander/Documents/projects/frix/playground/fastify/src/index.js:35:34)\n    at Object.swagger (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify-swagger@4.3.2\\node_modules\\fastify-swagger\\lib\\spec\\openapi\\index.js:36:19)\n    at Object.handler (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify-swagger@4.3.2\\node_modules\\fastify-swagger\\lib\\routes.js:46:26)\n    at preHandlerCallback (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\handleRequest.js:124:28)\n    at preValidationCallback (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\handleRequest.js:107:5)\n    at handler (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\handleRequest.js:70:7)\n    at handleRequest (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\handleRequest.js:18:5)\n    at next (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\route.js:442:7)\n    at Object.preParsing (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify-compress@3.4.2\\node_modules\\fastify-compress\\index.js:294:14)\n    at next (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\route.js:452:18)\n    at preParsingHookRunner (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\route.js:472:3)\n    at runPreParsing (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\route.js:419:5)\n    at next (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\hooks.js:158:7)\n    at Object.onRequest (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify-compress@3.4.2\\node_modules\\fastify-compress\\index.js:207:5)\n    at hookIterator (C:\\Users\\Alexander\\Documents\\projects\\frix\\playground\\fastify\\node_modules\\.pnpm\\fastify@3.13.0\\node_modules\\fastify\\lib\\hooks.js:237:10)","generatedMessage":false,"code":"ERR_ASSERTION","actual":false,"expected":true,"operator":"=="},"msg":"requires a joi schema object"}

Your Environment

  • node version: 15
  • fastify version: 3.13.0
  • joi-to-json-schema: 5.1.0
  • os: Windows,
  • any other relevant information
@mcollina
Copy link
Member

mcollina commented Mar 3, 2021

Was this working in v3.12.0?

cc @Eomm

@alexanderniebuhr
Copy link
Contributor Author

just tested some version. seems to break since 3.0. we need 3.0 can't use 2.0. schema complier changed, so this might also change the schema :/

v2 in fastify docs:

const joi = require('joi')

// Validation options to match ajv's baseline options used in Fastify
const joiOptions = {
  abortEarly: false, // return all errors
  convert: true, // change data type of data to match type keyword
  allowUnknown : false, // remove additional properties
  noDefaults: false
}

const joiBodySchema = joi.object().keys({
  age: joi.number().integer().required(),
  sub: joi.object().keys({
    name: joi.string().required()
  }).required()
})

const joiSchemaCompiler = schema => data => {
  // joi `validate` function returns an object with an error property (if validation failed) and a value property (always present, coerced value if validation was successful)
  const { error, value } = joiSchema.validate(data, joiOptions)
  if (error) {
    return { error }
  } else {
    return { value }
  }
}

// or more simply...
const joiSchemaCompiler = schema => data => joiSchema.validate(data, joiOptions)

fastify.post('/the/url', {
  schema: {
    body: joiBodySchema
  },
  schemaCompiler: joiSchemaCompiler
}, handler)

v3 in fastify docs:

const Joi = require('@hapi/joi')

fastify.post('/the/url', {
  schema: {
    body: Joi.object().keys({
      hello: Joi.string().required()
    }).required()
  },
  validatorCompiler: ({ schema, method, url, httpPart }) => {
    return data => schema.validate(data)
  }
}, handler)

@alexanderniebuhr
Copy link
Contributor Author

the schema the transform functions get are following

{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{ hide: true, [Symbol(fastify.schemas.visited)]: true }
{
  body: {
    type: 'object',
    '$_root': {
      _types: [Set],
      alternatives: [Function (anonymous)],
      any: [Function (anonymous)],
      array: [Function (anonymous)],
      boolean: [Function (anonymous)],
      date: [Function (anonymous)],
      function: [Function (anonymous)],
      link: [Function (anonymous)],
      number: [Function (anonymous)],
      object: [Function (anonymous)],
      string: [Function (anonymous)],
      symbol: [Function (anonymous)],
      binary: [Function (anonymous)],
      allow: [Function (anonymous)],
      custom: [Function (anonymous)],
      disallow: [Function (anonymous)],
      equal: [Function (anonymous)],
      exist: [Function (anonymous)],
      forbidden: [Function (anonymous)],
      invalid: [Function (anonymous)],
      not: [Function (anonymous)],
      only: [Function (anonymous)],
      optional: [Function (anonymous)],
      options: [Function (anonymous)],
      prefs: [Function (anonymous)],
      preferences: [Function (anonymous)],
      required: [Function (anonymous)],
      strip: [Function (anonymous)],
      valid: [Function (anonymous)],
      when: [Function (anonymous)],
      ValidationError: [class (anonymous) extends Error],
      version: '17.4.0',
      cache: [Object],
      assert: [Function: assert],
      attempt: [Function: attempt],
      build: [Function: build],
      checkPreferences: [Function: checkPreferences],
      compile: [Function: compile],
      defaults: [Function: defaults],
      expression: [Function: expression],
      extend: [Function: extend],
      isError: [Function: isError],
      isExpression: [Function: isTemplate],
      isRef: [Function (anonymous)],
      isSchema: [Function (anonymous)],
      in: [Function: in],
      override: Symbol(override),
      ref: [Function: ref],
      types: [Function: types],
      alt: [Function (anonymous)],
      bool: [Function (anonymous)],
      func: [Function (anonymous)],
      x: [Function: expression],
      trace: [Function: trace],
      untrace: [Function (anonymous)],
      [Symbol(@hapi/lab/coverage/initialize)]: [Function: trace]
    },
    '$_temp': { ruleset: false, whens: {} },
    _ids: { _byId: Map(0) {}, _byKey: [Map], _schemaChain: false },
    _preferences: null,
    _valids: null,
    _invalids: null,
    _rules: [],
    _singleRules: Map(0) {},
    _refs: { refs: [] },
    _flags: { presence: 'required' },
    _cache: null,
    '$_terms': {
      alterations: null,
      examples: null,
      externals: null,
      metas: [],
      notes: [],
      shared: null,
      tags: [],
      whens: null,
      dependencies: null,
      keys: [Array],
      patterns: null,
      renames: null
    },
    '$_super': { default: [Function: bound default] }
  }
}

@mcollina
Copy link
Member

mcollina commented Mar 3, 2021

A PR to fix this would be highly welcomed.

@mcollina
Copy link
Member

mcollina commented Mar 3, 2021

@alexanderniebuhr
Copy link
Contributor Author

@mcollina It should work, as the schema looks good.! do you know what this is, and where there are coming from??

  { hide: true, [Symbol(fastify.schemas.visited)]: true }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants