Code Monkey home page Code Monkey logo

celebrate's People

Contributors

aarifkhamdi avatar adarah avatar arb avatar bboystatix avatar billylaing avatar brainsiq avatar btalayeminaei avatar cjihrig avatar eduardostuart avatar gerkindev avatar giltho avatar gonenduk avatar hoangnguyennn avatar ikokostya avatar irwin-r avatar isaachinman avatar jdtzmn avatar justin-calleja avatar kandros avatar lbevilacqua avatar loganarnett avatar markmssd avatar olsonpm avatar spyndutz avatar twrayden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

celebrate's Issues

Possible Enhancement

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!

[email protected]

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.

Express 5 heads up

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.

HTTP Status Code On Error

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.

Integration tests

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.

Relocate `_schema`

Hide it behind a symbol or something. Maybe have a schema function that returns this information?

Change Setting Joi result back to req

Remove conditional and just do Object.defineProperty and set the value there. Make this a breaking change in case it has unintended side effects.

Exported API

Change exported API to

{
  celebrate: function() {},
  errors: function() {},
  Joi: Joi
}

This makes importing the different APIs a little cleaner.

Relocate Validated values

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.

Body Checks

Skip body check on "GET" and "HEAD" requests.
Add test for req.body being undefined.

Breaking Changes?

Noticed there's a major version change to 3.0.0, are there any breaking changes from 2.2 that could be documented here?

node v6 support (joi v12)

  • node version - 6.14.2
  • celebrate version - 8.0.0

Is 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!

how to extend joi schema

  • node version - 8.0.0
  • celebrate version - 6.0.0
  • joi version (via npm ls --depth=0 | grep joi) - 12.x.x

My 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
screenshot from 2017-11-08 12 34 26
"
So Please let me know how i can solve this issue

Expose isCelebrate

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.

Log error/warning on Celebrate rejection

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).

How to validate file extension (.mp3, wmv)

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

Joi Update

Bump the peerDep to joi 11. Should this be a major?

celebrate undefined

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)

Add Joi as a peer dependency

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?

Celebrate stripping out all keys

  • 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:

  1. It is lettering error prone objects flow past the middleware.
  2. They are getting created.
  3. No proper error messaging

Custom Joi

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.

Joi 13+

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.

Unit testing validators

  • node version - 8.9.0
  • celebrate version - ^7.0.1
  • joi version (via npm ls --depth=0 | grep joi) -^13.0.2

Am I to be using Joi.validate(), or does Celebrate expose its own custom validator?

Validate a Query param base on a Params value

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.

TypeScript compiler can't found declaration

  • node version - v8.6.0
  • celebrate version - 5.0.1
  • joi 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"
}

Bump Jest

A few places where we could use describe.each to cut down on test boilerplate

How to validate multipart/form-data

Hi, there.
Sorry to bother you but
I've got problems to validate multipart/form-data
from an angular app

Express

exports.create = {
  body: {
    content: Joi.string().required(),
    title: Joi.string().required()
  }
};

router.post('',
  celebrate(validators.create),
  jwtVerify,
  extractFile,
  controllers.create
);

Angular

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 ?

Remove Fast Series

joi validation is sync, so there really isn't a good reason so use an async library.

readme typo

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

exported Joi type definitions are missing

  • node version - 6.11.4
  • celebrate version - 7.0.1
  • joi version (via npm ls --depth=0 | grep joi) - 13.0.2

The 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.

Possible enhancement for @types

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!

Clean up Error Handler

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"
    ]
  }
}

Send Back All Validation Errors

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.