You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

simplified-joi.ts 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import Joi, { SchemaLike } from 'joi'
  2. const JOI_MAPPING: { [k: string]: SchemaLike } = {
  3. string: Joi.string(),
  4. number: Joi.number(),
  5. bool: Joi.bool(),
  6. boolean: Joi.boolean(),
  7. symbol: Joi.symbol(),
  8. // Simply pass schema as object or array for them
  9. // object: Joi.object(),
  10. // array: Joi.array(),
  11. }
  12. const isNotRequiredRegex = /notrequired/i
  13. const isNotRequired = isNotRequiredRegex.test.bind(isNotRequiredRegex)
  14. function isObject (value: any): value is { [k: string]: any } {
  15. return !!value && typeof value === 'object'
  16. }
  17. function isArray (value: any): value is Array<any> {
  18. return !!value && Array.isArray(value)
  19. }
  20. function isJoiSchema (value: any): value is SchemaLike {
  21. return !!value && value.isJoi
  22. }
  23. export function transformSchema (schema: any): SchemaLike {
  24. if (isJoiSchema(schema)) return schema
  25. if (isArray(schema)) {
  26. schema = schema.map(transformSchema)
  27. return Joi.array().ordered(schema).required()
  28. }
  29. if (isObject(schema)) {
  30. schema = Object.entries(schema)
  31. .reduce((acc, [key, value]) => ({
  32. ...acc,
  33. [key]: transformSchema(value),
  34. }), {})
  35. return Joi.object(schema).required()
  36. }
  37. const [schemaName, schemaOptions = ''] = (schema as string).split('|', 2)
  38. schema = JOI_MAPPING[schemaName]
  39. if (typeof schema === 'undefined') {
  40. throw new Error(`Requested Joi validator ${schema} unsupported or undefined.`)
  41. }
  42. return isNotRequired(schemaOptions) ? schema : schema.required()
  43. }
  44. export default transformSchema