https://github.com/goodrequest/joi-type-extract
Extract type from Joi schema
https://github.com/goodrequest/joi-type-extract
backend express joi typescript web-utils
Last synced: 3 months ago
JSON representation
Extract type from Joi schema
- Host: GitHub
- URL: https://github.com/goodrequest/joi-type-extract
- Owner: GoodRequest
- Created: 2022-04-04T11:17:14.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-01-19T16:22:30.000Z (over 2 years ago)
- Last Synced: 2025-06-18T01:51:25.888Z (4 months ago)
- Topics: backend, express, joi, typescript, web-utils
- Homepage:
- Size: 17.6 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# joi-type-extract
Clone of https://github.com/TCMiranda/joi-extract-type## Setup
1. Install package
```bash
npm install @goodrequest/joi-type-extract
or
yarn add @goodrequest/joi-type-extract
```
2. Create ./src/types/joi/index.d.ts and import package in it, which will extend Joi types
```Typescript
import '@goodrequest/joi-type-extract'
```
3. Add this compiler option and include created file in tsconfig.json in typeRoots
```Json
{
"compilerOptions": {
"strictNullChecks": true,
"typeRoots": [
"./src/types"
]
}
}
```## Usage example
```Typescript
import Joi from 'joi'export const requestSchema = () =>
Joi.object({
params: Joi.object({
userID: Joi.number().required()
}),
query: Joi.object({
search: Joi.string().required()
}),
body: Joi.object({
name: Joi.string().required()
})
})export const responseSchema = Joi.object({
messages: Joi.array().items({
message: Joi.string().required(),
type: Joi.string().valid(MESSAGE_TYPE.SUCCESS).required()
}).required()
})type RequestType = Joi.extractType>
type ResponseType = Joi.extractType
```
Extracted EequestType and ResponseType can be then used in express.Request and express.Response types
```Typescript
import { Request, Response, NextFunction } from 'express'const businessLogic = async (
req: Request,
res: Response,
next: NextFunction
) => {
const { params, query, body } = req// params.userID will have number type
// query.serch will have string type
// body.name will have string type// response will be enforced to be same as ResponseType
return res.json({
messages: [
{
message: 'Response message',
type: MESSAGE_TYPE.SUCCESS
}
]
})
}
```