Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/gobengo/protobuf-validator
Validate ProtoBuf.js Messages
https://github.com/gobengo/protobuf-validator
Last synced: 25 days ago
JSON representation
Validate ProtoBuf.js Messages
- Host: GitHub
- URL: https://github.com/gobengo/protobuf-validator
- Owner: gobengo
- Created: 2013-10-20T23:56:47.000Z (about 11 years ago)
- Default Branch: master
- Last Pushed: 2014-05-17T22:34:49.000Z (over 10 years ago)
- Last Synced: 2024-10-03T15:30:05.678Z (about 1 month ago)
- Language: JavaScript
- Size: 223 KB
- Stars: 12
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# protobuf-validator
Validate Objects as [Protocol Buffer](https://developers.google.com/protocol-buffers/docs/proto) messages.
Thanks to [ProtoBuf.js](https://github.com/dcodeIO/ProtoBuf.js)!
API inspired by [node-validator](https://github.com/chriso/node-validator).## Usage
Assuming you have a message `MyMessage` in a `messages.proto` file.
message MyMessage {
optional string name = 1;
required int32 myNumber = 2;
}Make a ProtobufValidator
var Protobuf = require('protobufjs');
var ProtobufValidator = require('protobuf-validator').ProtobufValidator;// First, Get a ProtoBuf.js Reflect Instance for your message
var builder = Protobuf.protoFromFile(path.join(__dirname, 'messages.proto'));
var myMessageReflection = builder.lookup('MyMessage');
// Then make a Validator
var validator = ProtobufValidator(myMessageReflection);Validate that an object has all required fields.
var message = {
name: 'Wish I had a .myNumber'
};
// Will throw because 'myNumber' is missing yet required
validator.validate(message).hasRequiredFields();Validate that an object has valid values.
var message = {
myNumber: 'Wait this is not an int32...'
};
// Will throw because the value for '.myNumber' is not a Number
validator.validate(message).hasValidValues();By default, an Error will be thrown when encountered. But you are encouraged to override `.error` for alternative behavior. For example, to store a bunch of errors.
validator.error = function (err) {
this.errors = this.errors || [];
this.errors.push(err);
};
// will not throw
validator.validate({})
.hasValidValues()
.hasRequiredFields();
// because they've been stored in .errors
validator.errors.length > 0; // true