0

I am using this code and created a microservice

const { json, send } = require('micro')
const { router, post } = require('microrouter')
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
console.log(process.env.STRIPE_SECRET_KEY)
module.exports = router(
    post('/', async (req, res) => {
        const data = await json(req)
        try {
            const { status } = await stripe.charges.create(data)
            send(res, 200, { status })
        } catch (err) {
            send(res, 500, { message: err.message })
        }
    })
)

I can make a post request here using microrouter but how can I validate the payload body to get only the required fields only.

Please help if someone know any module to validate microservice post payload.

Profer
  • 553
  • 8
  • 40
  • 81

2 Answers2

1

You can use joi npm and express validator

const Joi = require("joi");
const validate = require("express-validation");

const validationSchema = {
      body: {
        Id: Joi.string()
          .guid()
          .required(), // mandatory
        FirstName: Joi.string().required(), // mandatory
        LastName: Joi.string().required(), // mandatory
        Email: Joi.string()
          .email({ minDomainAtoms: 2 })
          .required(), // mandatory
        Password: Joi.string().required(), // mandatory
        createdOn: Joi.date()
          .timestamp()
          .required(), // mandatory

      }
    };

Router File

module.exports = router(
    post('/',validate(validationSchema), async (req, res) => {
        const data = await json(req)
        try {
            const { status } = await stripe.charges.create(data)
            send(res, 200, { status })
        } catch (err) {
            send(res, 500, { message: err.message })
        }
    })
)
Biswadev
  • 1,456
  • 11
  • 24
  • it should not throw a next error..similar example is given here https://scotch.io/tutorials/node-api-schema-validation-with-joi – Biswadev Dec 26 '18 at 12:48
0

you have so common issue, as i can understand you can use for this payloads https://validatejs.org/#validators

this is email validate example:

var constraints = {
  from: {
    email: true
  }
};

validate({from: null}, constraints);
// => undefined

validate({from: ""}, constraints);
// => {"email": ["From is not a valid email"]}

validate({from: "nicklas@ansman"}, constraints);
// => {"email": ["From is not a valid email"]}

// Any TLD is allowed
validate({from: "nicklas@foo.faketld"}, constraints);
// => undefined

// Upper cased emails are allowed
validate({from: "NICKLAS@ANSMAN.SE"}, constraints);
// => undefined

constraints = {
  from: {
    email: {
      message: "doesn't look like a valid email"
    }
  }
};

validate({from: "foobar"}, constraints);
// => {"email": ["From doesn't look like a valid email"]}

// It allows unicode
validate({from: "first.läst@example.com"}, constraints);
// => undefined
Vadim Hulevich
  • 1,803
  • 8
  • 17