Skip to content

Instantly share code, notes, and snippets.

@icebob
Created September 11, 2017 09:23
Show Gist options
  • Save icebob/07024c0ac22589a5496473c2a8a91146 to your computer and use it in GitHub Desktop.
Save icebob/07024c0ac22589a5496473c2a8a91146 to your computer and use it in GitHub Desktop.
Example Joi validator for Moleculer
"use strict";
let ServiceBroker = require("../src/service-broker");
let BaseValidator = require("../src/validator");
let { ValidationError } = require("../src/errors");
// --- JOI VALIDATOR CLASS ---
class JoiValidator extends BaseValidator {
constructor() {
super();
this.validator = require("joi");
}
compile(schema) {
return (params) => this.validate(params, schema);
}
validate(params, schema) {
const res = this.validator.validate(params, schema);
if (res.error)
throw new ValidationError(res.error.message, null, res.error.details);
return true;
}
}
let broker = new ServiceBroker({
logger: true,
validation: true,
validator: new JoiValidator()
});
// --- TEST BROKER ---
let Joi = require("joi");
broker.createService({
name: "greeter",
actions: {
hello: {
params: Joi.object().keys({
name: Joi.string().min(4).max(30).required()
}),
handler(ctx) {
return `Hello ${ctx.params.name}`;
}
}
}
});
broker.start()
.then(() => broker.call("greeter.hello").then(res => broker.logger.info(res)))
.catch(err => broker.logger.error(err.message, err.data))
.then(() => broker.call("greeter.hello", { name: 100 }).then(res => broker.logger.info(res)))
.catch(err => broker.logger.error(err.message, err.data))
.then(() => broker.call("greeter.hello", { name: "Joe" }).then(res => broker.logger.info(res)))
.catch(err => broker.logger.error(err.message, err.data))
.then(() => broker.call("greeter.hello", { name: "John" }).then(res => broker.logger.info(res)))
.catch(err => broker.logger.error(err.message, err.data));
@tvinhkhoa
Copy link

tvinhkhoa commented Jan 28, 2022

Could you demo for it, please? I had problem version v17.x.x the package Joi is validate function not found. Please send for package.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment