Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb://.. as a validating url #93

Closed
c-hartmann opened this issue Sep 13, 2015 · 2 comments
Closed

mongodb://.. as a validating url #93

c-hartmann opened this issue Sep 13, 2015 · 2 comments

Comments

@c-hartmann
Copy link

Would love to see mongodb://.. URI style to validate against 'url' format, as featured in:
http://blog.nodejitsu.com/npmawesome-managing-app-configuration-with-convict/

From what i can see, this might require to use:

    assert(validator.isURL(mongouri, {require_valid_protocol: false}));

instead of using it without the options object.

A custom validator function works fine this way:

     mongo: {
      doc: 'main database',
      bind: {
        format: function check (url) {
          if (!validator.isURL(url,{require_valid_protocol: false})) {
            throw new Error('must be a URL like');
          }
        },
        default: 'mongodb://localhost:27017/'+my_db_name,
        env: "DB_BIND"
      },
@pdehaan
Copy link
Contributor

pdehaan commented Sep 15, 2015

@c-hartmann If you want to validate that the protocol is "mongodb://", you can use joi's uri() validator:

var Joi = require('joi');

function isMongoUrl(url) {
  var mongodbSchema = Joi.string().uri({
    scheme: ['mongodb']
  });

  Joi.assert(url, mongodbSchema);
}

Actually, the validator library supports custom schemes too:

function isMongoUrl(url) {
  if (!validator.isURL(url, {
    protocols: ['mongodb']
  })) {
    throw new Error('must be URL like');
  }
}

@madarche
Copy link
Collaborator

I totally agree with @pdehaan suggestions.

We would loose some "validation strictness" if we set {require_valid_protocol: false} by default in convict.

Here is a full working code:

const validator = require('validator');
convict.addFormat({
    name: 'mongo-uri',
    validate: function(val) {
        if (!validator.isURL(val, {protocols: ['mongodb']})) {
            throw new Error('must be a MongoDB URI');
        }
    }
});

var conf = convict({
    uri: {
        doc: 'Mongo URI',
        format: 'mongo-uri',
        default: ''
    }
});
conf.load({uri: 'mongodb://localhost:27017/some_db_name'});
conf.validate({strict: true});

@c-hartmann could you please close this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants