UNPKG

1.41 kBPlain TextView Raw
1import { StringSchema } from 'joi'
2import * as JoiLib from 'joi'
3import { ExtendedNumberSchema, numberExtensions } from './number.extensions'
4import { ExtendedStringSchema, stringExtensions } from './string.extensions'
5
6export interface ExtendedJoi extends JoiLib.Root {
7 // eslint-disable-next-line id-blacklist
8 string(): ExtendedStringSchema
9 // eslint-disable-next-line id-blacklist
10 number(): ExtendedNumberSchema
11}
12
13/**
14 * This is the only right place to import Joi from
15 */
16export const Joi: ExtendedJoi = JoiLib.defaults(schema => {
17 // hack to prevent infinite recursion due to .empty('') where '' is a stringSchema itself
18 if (schema.type === 'string') {
19 return (
20 (schema as StringSchema)
21 .trim() // trim all strings by default
22 // 2020-09-21: null values are NOT treated as EMPTY enymore
23 // .empty([schema.valid('', null)]) // treat '' or null as empty (undefined, will be stripped out)
24 // treat '' as empty (undefined, will be stripped out)
25 .empty([schema.valid('')])
26 )
27 }
28
29 // Treat `null` as undefined for all schema types
30 // undefined values will be stripped by default from object values
31 // 2020-09-21: breaking change: null values are NOT treated as EMPTY anymore
32 // return schema.empty(null)
33 return schema
34})
35 .extend((joi: typeof JoiLib) => stringExtensions(joi))
36 .extend((joi: typeof JoiLib) => numberExtensions(joi))