UNPKG

2.49 kBPlain TextView Raw
1import { Joi } from './joi.extensions'
2import {
3 AnySchemaTyped,
4 ArraySchemaTyped,
5 BooleanSchemaTyped,
6 ObjectSchemaTyped,
7 StringSchemaTyped,
8} from './joi.model'
9
10export const booleanSchema = Joi.boolean() as BooleanSchemaTyped
11export const booleanDefaultToFalseSchema = Joi.boolean().default(false) as BooleanSchemaTyped
12export const stringSchema = Joi.string()
13export const numberSchema = Joi.number()
14export const integerSchema = Joi.number().integer()
15export const percentageSchema = Joi.number().integer().min(0).max(100)
16export const dateStringSchema = stringSchema.dateString()
17export const binarySchema = Joi.binary()
18
19export const urlSchema = (scheme: string | string[] = 'https'): StringSchemaTyped =>
20 Joi.string().uri({ scheme })
21
22export function arraySchema<T>(items?: AnySchemaTyped<T, T>): ArraySchemaTyped<T> {
23 return items ? Joi.array().items(items) : Joi.array()
24}
25
26export function objectSchema<IN, OUT = IN>(
27 schema?: { [key in keyof Partial<IN>]: AnySchemaTyped<IN[key]> },
28): ObjectSchemaTyped<IN, OUT> {
29 return Joi.object(schema)
30}
31
32export const anySchema = Joi.any()
33export const anyObjectSchema = Joi.object().options({ stripUnknown: false })
34
35// 1g498efj5sder3324zer
36/**
37 * [a-z0-9_]*
38 * 6-64 length
39 */
40export const idSchema = stringSchema
41 .regex(/^[a-z0-9_]*$/)
42 .min(6)
43 .max(64)
44
45/**
46 * `_` should NOT be allowed to be able to use slug-ids as part of natural ids with `_` separator.
47 */
48export const SLUG_PATTERN = /^[a-z0-9-]*$/
49
50/**
51 * "Slug" - a valid URL, filename, etc.
52 */
53export const slugSchema = stringSchema.regex(SLUG_PATTERN).min(1).max(255)
54
55// 16725225600 is 2500-01-01
56export const unixTimestampSchema = numberSchema.integer().min(0).max(16725225600)
57
58// 2
59export const verSchema = numberSchema.optional().integer().min(1).max(100)
60
61/**
62 * Be careful, by default emailSchema does TLD validation. To disable it - use `stringSchema.email({tld: false}).lowercase()`
63 */
64export const emailSchema = stringSchema.email().lowercase()
65
66/**
67 * Pattern is simplified for our use, it's not a canonical SemVer.
68 */
69export const SEM_VER_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+$/
70export const semVerSchema = stringSchema.regex(SEM_VER_PATTERN)
71// todo: .error(() => 'should be SemVer')
72
73export const userAgentSchema = stringSchema
74 .min(5) // I've seen UA of `Android` (7 characters)
75 .max(400)
76
77export const utcOffsetSchema = numberSchema
78 .min(-14 * 60)
79 .max(14 * 60)
80 .dividable(15)
81
82export const ipAddressSchema = stringSchema.ip()