All Projects β†’ hjkcai β†’ typesafe-joi

hjkcai / typesafe-joi

Licence: MIT license
A fork of joi that produces typed validation results in TypeScript

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to typesafe-joi

next-joi
Validate NEXT.js API Routes with joi
Stars: ✭ 111 (+48%)
Mutual labels:  joi
api-with-express
🌈 API with Express
Stars: ✭ 25 (-66.67%)
Mutual labels:  joi
joi-to-typescript
Convert Joi Schemas to TypeScript interfaces
Stars: ✭ 73 (-2.67%)
Mutual labels:  joi
task-manager
Task Manager App
Stars: ✭ 19 (-74.67%)
Mutual labels:  joi
express-mongoose-es8-rest-api
A Boilerplate for developing Rest api's in Node.js using express with support for ES6,ES7,ES8 ,Mongoose,JWT for authentication,Standardjs for linting
Stars: ✭ 20 (-73.33%)
Mutual labels:  joi
wily
Build Node.js APIs from the command line (Dead Project 😡)
Stars: ✭ 14 (-81.33%)
Mutual labels:  joi
express-ts-api-boilerplate
Express TypeScript API Boilerplate
Stars: ✭ 15 (-80%)
Mutual labels:  joi
typesafe-hapi
Typechecking for HapiJS based on Joi schemas!
Stars: ✭ 21 (-72%)
Mutual labels:  joi
micro-joi
A Joi wrapper for zeit/micro
Stars: ✭ 46 (-38.67%)
Mutual labels:  joi
koa-restful-boilerplate
A boilerplate for koa2 RESTful API development
Stars: ✭ 31 (-58.67%)
Mutual labels:  joi
rest-api-node-typescript
This is a simple REST API with node and express with typescript
Stars: ✭ 154 (+105.33%)
Mutual labels:  joi
README-ecoleta
🎁 TrΓͺs modelos de README com o Projeto criados para o blog da @Rocketseat πŸš€
Stars: ✭ 179 (+138.67%)
Mutual labels:  joi
toi
A TypeScript validation library capable of inferring types
Stars: ✭ 25 (-66.67%)
Mutual labels:  joi
vayder
Easy and concise validations for Express routes
Stars: ✭ 26 (-65.33%)
Mutual labels:  joi
felicity
Javascript object constructors and sample data based on Joi schema.
Stars: ✭ 107 (+42.67%)
Mutual labels:  joi

typesafe-joi

typesafe-joi is a fork of @hapi/joi. More precisely, this is a fork of @types/hapi__joi because it has just redefined the essential APIs of joi. Almost all the APIs are the same as the original APIs, but limitations exists. That is why I create a new package.

typesafe-joi currently matches the API of @hapi/joi 15.x. And it requires TypeScript >=3.0.0 to work.

NOTE: typesafe-joi is still WIP. Sorry but I do not have enough time to write a unit test for it. Please feel free to open an issue when you find bugs or suggestions. I am glad to help!

What’s the difference?

The JavaScript APIs of typesafe-joi and joi are identical. However, its type definition lacks of the type information of the β€œvalue” behind the schema. That means, JavaScript knows what the validated object look like at runtime, but TypeScript does not know it at all at compile time. typesafe-joi records more information into schemas so that TypeScript is able to know what object you are validating at compile time.

Unfortunately not all joi APIs are able to be properly described in TypeScript. See Reference for more information.

Usage

Import and use joi from typesafe-joi:

import * as Joi from 'typesafe-joi'

The TypeScript magic is shown when you call .validate or .attempt:

const data: any = dataFromAnywhere

// { foo?: string } | undefined
Joi.object({ foo: Joi.string() }).validate(data).value

// { id: number, email?: string }[]
Joi.attempt(data, Joi.array()
  .items({
    id: Joi.number().integer().required(),
    email: Joi.string().email()
  })
  .required()
)

You can also use Literal to pull the data type out of the schema:

const schema = Joi.array()
  .items({
    id: Joi.number().integer().required(),
    email: Joi.string().email()
  })
  .required()

type T = Joi.Literal<typeof schema>

NOTE: I suggest to turn on strict option in the compiler options of TypeScript.

Typecasting

Not every API of typesafe-joi matches the original joi in types. typesafe-joi provides typecast helpers in case you have to define the resulting type manually.

// 'foo'
Joi.string().required() as Joi.Cast.String<'foo'>

If the typecast includes undefined type, the key will be optional.

// { foo?: Foo }
Joi.object({ foo: number().required() as Joi.Cast.Object<Foo | undefined> })

Typecasting means you have to define everything by yourself. Schema attributes like allow is discarded.

// number | 'foo' | true
Joi.number().allow('foo').default(true)

// 123
Joi.number().allow('foo').default(true) as Joi.Cast.Number<123>

TypeScript may complain about type mismatch. In this case assert the expression to any firstly.

// Error
Joi.object({
  foo: Joi.object().pattern(/\d+/, 1).allow(1) as Joi.Cast.Object<Foo>
})

// { map: Foo | 1 }
Joi.object({
  foo: Joi.object().pattern(/\d+/, 1).allow(1) as any as Joi.Cast.Object<Foo | 1>
})

I recommend not to use the schema anymore after typecast. The behavior will be undefined.

Supported schema types to cast:

  • Cast.Alternatives
  • Cast.Any
  • Cast.Array
  • Cast.Binary
  • Cast.Boolean
  • Cast.Date
  • Cast.Function
  • Cast.Lazy
  • Cast.Number
  • Cast.Object
  • Cast.String

Reference

Here is a list of APIs of joi.

  • βœ… - Fully supported
  • βœ”οΈ - Supported but might be incorrect (not well tested)
  • ⚠️ - Partially supported (with limitations)
  • ❌ - Not supported (however you can use it without auto type generation)
  • πŸ”˜ - Supported but no type generation needed
API Status Note
Joi
version πŸ”˜
validate(value, schema, [options], [callback]) βœ…
compile(schema) βœ”οΈ
describe(schema) πŸ”˜
assert(value, schema, [message]) βœ…
attempt(value, schema, [message]) βœ…
ref(key, [options]) πŸ”˜
isRef(ref) πŸ”˜
reach(schema, path) ❌
defaults(fn) πŸ”˜
bind() πŸ”˜
extend(extension) πŸ”˜ Requires module augmentation to typesafe-joi
any
any.validate(value, [options], [callback]) βœ…
any.allow(value) βœ…
any.valid(value) βœ…
any.invalid(value) βœ…
any.required() βœ…
any.optional() βœ…
any.forbidden() βœ…
any.strip() ⚠️ The object key will still exist. It will have never type.
any.description(desc) πŸ”˜
any.notes(notes) πŸ”˜
any.tags(tags) πŸ”˜
any.meta(meta) πŸ”˜
any.example(...values) πŸ”˜
any.unit(name) πŸ”˜
any.options(options) πŸ”˜ To properly use typesafe-joi, do not change convert, presence, noDefaults.
any.strict(isStrict) πŸ”˜
any.default(value, [description]) ⚠️ Manually define the default type when using reference as default.
any.concat(schema) βœ”οΈ
any.when(condition, options) βœ”οΈ
any.label(name) πŸ”˜
any.raw(isRaw) πŸ”˜
any.empty(schema) ❌
any.error(err, [options]) πŸ”˜
any.describe() πŸ”˜
array
array.sparse([enabled]) βœ…
array.single([enabled]) πŸ”˜
array.items(type) βœ…
array.ordered(type) ⚠️ No actual item order in the resulting type
array.min(limit) πŸ”˜
array.max(limit) πŸ”˜
array.length(limit) πŸ”˜
array.unique([comparator], [options]) πŸ”˜
array.has(schema) πŸ”˜
boolean
boolean.truthy(value) πŸ”˜
boolean.falsy(value) πŸ”˜
boolean.insensitive([enabled]) πŸ”˜
binary
binary.encoding(encoding) πŸ”˜
binary.min(limit) πŸ”˜
binary.max(limit) πŸ”˜
binary.length(limit) πŸ”˜
date
date.min(date) πŸ”˜
date.max(date) πŸ”˜
date.greater(date) πŸ”˜
date.less(date) πŸ”˜
date.iso() πŸ”˜
date.timestamp([type]) πŸ”˜
func
func.arity(n) πŸ”˜
func.minArity(n) πŸ”˜
func.maxArity(n) πŸ”˜
func.class() πŸ”˜
func.ref() πŸ”˜
number
number.unsafe([enabled]) πŸ”˜
number.min(limit) πŸ”˜
number.max(limit) πŸ”˜
number.greater(limit) πŸ”˜
number.less(limit) πŸ”˜
number.integer() πŸ”˜
number.precision(limit) πŸ”˜
number.multiple(base) πŸ”˜
number.positive() πŸ”˜
number.negative() πŸ”˜
number.port() πŸ”˜
object
object.keys([schema]) βœ…
object.append([schema]) βœ…
object.min(limit) ❌
object.max(limit) ❌
object.length(limit) ❌
object.pattern(pattern, schema) ⚠️ The result type of pattern may be useless.
object.and(peers) ❌
object.nand(peers) ❌
object.or(peers) ❌
object.xor(peers) ❌
object.oxor(...peers) ❌
object.with(key, peers) ❌
object.without(key, peers) ❌
object.rename(from, to, [options]) ❌
object.assert(ref, schema, [message]) πŸ”˜
object.unknown([allow]) πŸ”˜
object.type(constructor, [name]) ⚠️ If you need to combine keys and type, make sure type is the last call (.keys(...).type(...)), or the resulting type will be incorrect.
object.schema() ⚠️ Same as type.
object.requiredKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
object.optionalKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
object.forbiddenKeys(children) ⚠️ Nested key is not supported (e.g. a.b, a.b.c).
string
string.insensitive() πŸ”˜
string.min(limit, [encoding]) πŸ”˜
string.max(limit, [encoding]) πŸ”˜
string.truncate([enabled]) πŸ”˜
string.creditCard() πŸ”˜
string.length(limit, [encoding]) πŸ”˜
string.regex(pattern, [options]) πŸ”˜
string.replace(pattern, replacement) πŸ”˜
string.alphanum() πŸ”˜
string.token() πŸ”˜
string.email([options]) πŸ”˜
string.ip([options]) πŸ”˜
string.uri([options]) πŸ”˜
string.guid() - aliases: uuid πŸ”˜
string.hex([options]) πŸ”˜
string.base64([options]) πŸ”˜
string.dataUri([options]) πŸ”˜
string.hostname() πŸ”˜
string.normalize([form]) πŸ”˜
string.lowercase() πŸ”˜
string.uppercase() πŸ”˜
string.trim([enabled]) πŸ”˜
string.isoDate() πŸ”˜
symbol
symbol.map(map) πŸ”˜
alternatives Array literal alternatives schema is not supported yet.
alternatives.try(schemas) βœ…
alternatives.when(condition, options) βœ”οΈ
lazy

Contribution

Feel free to submit an issue or PR if you have any ideas, or found any bugs.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].