arb / celebrate Goto Github PK
View Code? Open in Web Editor NEWA joi validation middleware for Express.
License: MIT License
A joi validation middleware for Express.
License: MIT License
Rather than overwrite req.x
, with the updated values, attach them to res.locals.celebrate.x
. We should do this because it's the blessed location for middleware to attach things to res
. Also, with the current implementation, we have no way to get the initial values back at all.
Additionally, we need this for express 5 compatibility.
celebrate seems to only send back one validation error at a time even if there are multiple validation errors.
Is it possible to have it validate all errors and then send back all of them?
Now that we are trying to support multiple versions of express, add basic integration tests with a test matrix for express version 3, 4, and 5.
This is mostly a question, so the other stuff didn't seem relevant
The issue I am having with celebrate
is:
I am looking for a simple way to log when Celebrate errors occur. I just started user testing linkmelater.win, and have a couple of users who are experiencing issues signing up. I think I know the root cause, but I want to confirm in my logs before I get back to them. Currently, celebrate just returns the 400 and a message describing what's missing. Since I don't have much user-defined input, I would like for that error message to just get logged on my server too. any advice? Looking to avoid writing an error handler if I can (still pretty novice with Joi).
A few places where we could use describe.each
to cut down on test boilerplate
It's "jsdom" by default so set it to "node"
I see there's already type definitions, which is awesome!
However, I don't understand why the schema has all 4 params
, headers
, query
, and body
set as required. Shouldn't they be set as optional, as such:
{
params?: object,
headers?: object,
query?: object,
body?: object,
}
For example, if I want to validate only the params, I shouldn't have to specify an empty headers
, query
and body
.
Thanks for considering!
Skip body check on "GET" and "HEAD" requests.
Add test for req.body being undefined.
Bump Joi up to 14.
Looks pretty easy and can add a new badge.
node
version - 8.9.0celebrate
version - ^7.0.1joi
version (via npm ls --depth=0 | grep joi
) -^13.0.2Am I to be using Joi.validate()
, or does Celebrate
expose its own custom validator?
How do I use Celebrate to validate route params?
For example http://localhost/verify/12445
I need to validate 12445. How can I do this?
I was watching a Take Data Validation Seriously - Paul Milham, WildWorks and at 18:27 he talks about the need for forced validation.
Is there a way to force that the request goes through a Joi validation or the data isn't passed to the handler or there is a server error sent back?
Also, is this possible for response validation as well?
Noticed there's a major version change to 3.0.0, are there any breaking changes from 2.2 that could be documented here?
Bump the peerDep to joi 11. Should this be a major?
how to validate file extension with Celebrate Joi,
My Joi schema is like this
body: Joi.object().keys({ Audio: Joi.string().regex(/\.(?:wav|mp3)$/i).optional().options({ language: { any: { allowOnly: 'request id is required' }, label: 'audio file' } }).label('please provide [.mp3] or [.wav] file'), indexname: Joi.string().required() })
in audio my file is attached
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' -F Audio=@"33107045414_f1b635aea6_k.jpg" -F indexname=1222 'http://172.24.5.22:3000/api/v1/audio'
so how can i validate file format with the help of joi regex function
Hide it behind a symbol or something. Maybe have a schema
function that returns this information?
Since https://github.com/continuationlabs/celebrate#issues exists, and is unlikely to be read by anyone opening an issue, maybe we should consider adding a GitHub issue template.
Hi, there.
Sorry to bother you but
I've got problems to validate multipart/form-data
from an angular app
exports.create = {
body: {
content: Joi.string().required(),
title: Joi.string().required()
}
};
router.post('',
celebrate(validators.create),
jwtVerify,
extractFile,
controllers.create
);
add(data): Observable<Post> {
const { title, content, isDraft, image } = data;
const postData = new FormData();
postData.append('title', title);
postData.append('content', content);
postData.append('isDraft', isDraft);
postData.append('image', image, title);
return this.http.post<Post>(this.postsUrl, postData)
.pipe(catchError((error: any) => HttpErrorHandler.handle(error)));
}
The error message is
{"isJoi":true,"name":"ValidationError","details":[{"message":""content" is required","path":["content"],"type":"any.required","context":{"key":"content","label":"content"}}],"_object":{},"_meta":{"source":"body"}}
Can you help me, please ?
node
version - v8.6.0celebrate
version - 5.0.1joi
version (via npm ls --depth=0 | grep joi
) -Explain the problem here
Now TypeScript declaration https://github.com/continuationlabs/celebrate/blob/master/lib/index.d.ts is presented in npm package, but can't be found by TypeScript compiler:
$ ls node_modules/celebrate/lib/index.d.ts
node_modules/celebrate/lib/index.d.ts
$ ./node_modules/.bin/tsc
t.ts(1,28): error TS7016: Could not find a declaration file for module 'celebrate'. '/home/kostya/tmp/ts-test/node_modules/celebrate/lib/index.js' implicitly has an 'any' type.
Try `npm install @types/celebrate` if it exists or add a new declaration (.d.ts) file containing `declare module 'celebrate';`
1 import * as celebrate from 'celebrate';
~~~~~~~~~~~
For fix this need to add property types
to package.json
of Celebrate
package:
{
+ "types": "./lib/index.d.ts"
}
The docs show to require celebrate like below:
// try-celebrate.js
const { celebrate, Joi, errors } = require('celebrate');
console.log('celebrate', celebrate);
terminal
$ node try-celebrate.js
celebrate undefined
but celebrate is undefined. The below is what works for me to get the celebrate object:
const celebrate = require('celebrate')
const { Joi, errors } = celebrate
console.log('celebrate', celebrate)
node
version - v8.5.0celebrate
version - [email protected]joi
version (via npm ls --depth=0 | grep joi
) - [email protected]Cannot set property query of #<IncomingMessage> which has only a getter
TypeError: Cannot set property query of #<IncomingMessage> which has only a getter
at Joi.validate (/home/kevin/wheatt-node/node_modules/celebrate/lib/index.js:37:23)
Commenting out that line seemed to fix the problem, if that helps. Not sure what it does.
node
version - 8.0.0celebrate
version - 6.0.0joi
version (via npm ls --depth=0 | grep joi
) - 12.x.xMy joi
schema looks like this:
body: Joi.object().keys({ request_id: Joi.string().required().options({ language: { any: { allowOnly: 'request id is required' }, label: 'request id' } }).label('please provide request id'), topic_name: Joi.string().required().options({ language: { any: { allowOnly: 'topic name is required' }, label: 'topic name' } }).label('The name of the topic is required'), additional_title: Joi.string().optional(), additional_search_tags: Joi.string().optional(), topic_level: Joi.string().optional(), parent_topic: Joi.array().sparse(), properties: Joi.object(), region: Joi.array().sparse(), published_start_date: Joi.date().optional(), published_end_date: Joi.date().optional() })
Here is an example value that is not working as expected:
body: Joi.object().keys({ request_id: Joi.string().required().options({ language: { any: { allowOnly: 'request id is required' }, label: 'request id' } }).label('please provide request id'), topic_name: Joi.string().required().options({ language: { any: { allowOnly: 'topic name is required' }, label: 'topic name' } }).label('The name of the topic is required'), additional_title: Joi.string().optional(), additional_search_tags: Joi.string().optional(), topic_level: Joi.string().optional(), parent_topic: Joi.array().sparse(), properties: Joi.object(), region: Joi.array().sparse(), published_start_date: Joi.date().format('YYYY-MM-DD').optional(), published_end_date: Joi.date().format('YYYY-MM-DD').optional() })
The issue I am having with celebrate
is: i am using joi-date-extensions to extend date format but show me this error "Cannot read property 'extend' of undefined
"
So Please let me know how i can solve this issue
node
version - 6.7.0
celebrate
version - 4.0.1
joi
version (via npm ls --depth=0 | grep joi
) - 10.2.0
My joi
schema looks like this:
export const JUserSchema = Joi.object().keys({
"name" : Joi.string().min(3).max(200).required(),
"description" : Joi.string().min(0).max(2000).optional()
});
Here is an example value that is not working as expected:
curl -H "Content-Type: application/json" -X POST -d '{"name":"test", "description":"xyz"}' http://localhost:5000/users
The issue I am having with celebrate
is:
import { JUserSchema } from '../schemas/joi/user';
import { MUser } from '../schemas/users';
const Celebrate = require('celebrate');
const users = Router();
users.post('/', Celebrate({body:JUserSchema}), function(request, response, next) {
MUser.create(request.body, function(error,doc) {
if(error) response.status(500).json(error);
response.status(200).json(doc);
});
});
Basically this goes ahead and creates an object without the name
and description
keys (i.e. an object with just the mongo id), even though it is a compliant object. The same happens when the object is incorrectly sent (e.g. if i remove the name key from the POST
submission)
So there are three issues:
node
version - 6.14.2celebrate
version - 8.0.0Is using the latest v7.x.x
release the best way to work with node v6 (joi v12 is the last version that supports node v6)?
Why? I'm deploying to firebase / google cloud functions that run node v6 (limiting joi to v12). ๐ฟ
Thanks for the great module!
Remove conditional and just do Object.defineProperty
and set the value there. Make this a breaking change in case it has unintended side effects.
node
version - v8.10.0celebrate
version - [email protected]joi
version (via npm ls --depth=0 | grep joi
) - [email protected]My joi
schema looks like this:
const ConfigSchema = {
params: Joi.object().keys({
param1: Joi.string().required().valid([
'a',
'b'
])
}),
query: Joi.alternatives()
.when('params.param1, {
is: 'a',
then: Joi.object().keys({
query1: Joi.string().required()
}),
otherwhise: Joi.any()
})
};
Here is an example value that is not working as expected:
{ params: { param1: 'a' }, query: { query1: 'blha' }}
or
{ params: { param1: 'b' } }
The issue I am having with celebrate
is:
I want to validate query field based on the values that a params may have
Is it possible?? Using the given schema I will get always:
"value" not matching any of the allowed alternatives'
If I remove the query property from the schema both example values works so the error may be when referencing the params.param1
Regards.
We should probably export the isCelebrate
Symbol so that users could use it if they didn't want to use our error handler function but wanted to know if the passed in err
was from celebrate
or not.
node
version - 6.11.4celebrate
version - 7.0.1joi
version (via npm ls --depth=0 | grep joi
) - 13.0.2The issue I am having with celebrate
is:
Type definitions for exported Joi are missing. The index.d.ts
defines exported Joi
as of type object
. Consider defining the type as Joi from @types/joi
.
Allow Joi options to be passed in.
Our package.json
calls for joi 11.x.x.
joi 13.0.0 has been released.
Hey guys,
First of all, thank you very much for the repo you created. I have used Celebrate at the company I work at with great success, and it is used in production.
I recently built a library that exposes a fluent interface for Celebrate. You can find it here: https://github.com/naveedn/vayder
I built the library because the Express middleware pipeline lends itself to declaratively chaining validations, and the facade pattern makes it easy to understand what Celebrate is doing.
I was wondering if you guys were interested in having this interface directly incorporated in your repo?
Thanks again!
What are we going to do about joi@13 and beyond? I doubt express is ever going to be as aggressive about their supported versions of node as the hapi ecosystem.
Do we want to have two versions of celebrate? I don't really like that idea, but I actually don't have a better one. I don't think we can stick with 12 forever.
The current .npmignore only includes lib/index.js and nothing else. That means it'll break when it tries to include "schema.js"
I think it needs to be !lib/**
per outmoded/hapi-contrib#90 (comment)
If you've been following along, you've seen that I've recently made some changes to celebrate and I wanted to explain why this is a major release and not a minor.
The most recent round of changes, I removed stuff (fast-series
and the conditional check for how to set updated values back to req
). Writing values on req
is the change I'm most unsure of and is the main impetus for making this a major rather than a minor.
All of MY tests pass which is great but I can't be 100% that these changes won't impact your running instances. I decided the safest thing to do would be to make a new major so you can opt into it and let me know if there are any major bugs.
There are no new features for this release. Just code cleanup and some performance gains (about 1000 operations per second improvement)
This also includes a new version of Joi which will definitely include breaking changes to your schema. Please see the joi v14 release notes for more information.
For projects that install Joi as part of there own dependencies, it would be good to get warnings of incompatible versions when npm installing.
Edit: It looks like it used to be a peerDep but was removed at some point?
joi
validation is sync, so there really isn't a good reason so use an async library.
Change exported API to
{
celebrate: function() {},
errors: function() {},
Joi: Joi
}
This makes importing the different APIs a little cleaner.
Recently, I started using express with celebrate as a middleware for request body validation and there's a tiny detail that I'm wondering:
When a Joi constraint is violated, a response body is serialized and sent with a HTTP Status 400 (Bad Request).
By definition:
400 Bad Request
This response means that server could not understand the request due to invalid syntax.
In this case, a bad request would be appropriated to a request body like:
// invalid JSON syntax
{ "param1": "abc", "param2":
But, when the request body is well-formed, the server understands the content-type but cannot process the request due to business logic validation, should the default response be sent with a HTTP Status 422 (Unprocessable Entity)?
422 Unprocessable Entity
The request was well-formed but was unable to be followed due to semantic errors.
In README.md: missing 'next' arg in error handler (express won't register as error handler without 4 args). (Resolve #14 )
The issue I am having with celebrate
is:
I was wondering how I could use an extended Joi object with celetabre, the idea is that I could have custom validations.
There is version 14 defs now, so we should update to that to keep things current.
The current error handler spits back the entire Joi validation message which could be a pretty bad information leak as it contains the entire object.
The hapi response looks something like this:
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"name\" fails because [\"name\" is not allowed to be empty]",
"validation": {
"source": "payload",
"keys": [
"name"
]
}
}
Update to new high res logo
Add sponsor logo and copy
Line 7 of the 2nd example in the Usage
section of the readme, I believe it should be celebrate
instead of Celebrate
I can make a pull request tomorrow if needed, or you can modify that "online" if you find it easier
Add a basic Joi error responder.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.