0

I have created a simple API which has all verbs GET, PUT, POST, DELETE, but in this, I want to validate POST data.

I have tried Joi Libary but I did not get the proper way to do it.

CodeSnippet of POST Method

    appRouter.route('/')
        .post(function (req, res) 
        {            
            if (req.body.ProductName) 
            {
                conn.connect().then(function () {
                    var transaction = new sql.Transaction(conn);
                    transaction.begin().then(function () {
                        var request = new sql.Request(transaction);
                        request.input("ProductName", sql.VarChar(50), req.body.ProductName)
                        request.input("ProductPrice", sql.Decimal(18, 0), req.body.ProductPrice)
                        request.execute("Usp_InsertProduct").then(function () {
                            transaction.commit().then(function (recordSet) {
                                console.log(recordSet);
                                conn.close();
                                res.status(200).send(req.body);
                            }).catch(function (err) {
                                console.log("Error in Transaction Commit " + err);
                                conn.close();
                                res.status(400).send("Error while inserting data");
                            });
                        }).catch(function (err) {
                            console.log("Error in Transaction Begin " + err);
                            conn.close();
                            res.status(400).send("Error while inserting data");
                        });

                    }).catch(function (err) {
                        console.log(err);
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });
                })
                    .catch(function (err) {
                        console.log(err);
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });
            }
            else {
                res.status(400).send("Error while inserting data");
            }
        });

Snapshot of Controller

Controller

4 Answers 4

3

You can use this: validator created by google they use it to validate query param, but you can use it to validate payload. its simple and extensible

and use it like this:

const v = require('./validator')
// then test your payload like this...
const testPayload = (req, res, next) => {
try {
    const validate = v.object({
        username: v.string, //required field, string
        password: v.string, // required field, string
        age: v.number, // required field, number
        opt: v.optional(v.array(v.string))) // optional field, array of string
    })
    validate(req.body);
    next() // if everything goes well pass it to next middle ware, or handle your payload
}
catch (err) {
   next(err) // handling common error
}
Sign up to request clarification or add additional context in comments.

Comments

2

I usually user express-validator to validate API requests. It's based on validator.js. You can easily verify types, fields length, and even build your own custom functions to verify fields. And this package also make very easy to return to the user what fields that are not correct and why.

Example of validation error return from API call.

[
    {
        "location": "params",
        "param": "is_active",
        "msg": "Missing is_active param."
    },
    {
        "location": "params",
        "param": "is_active",
        "msg": "is_active param must be boolean true or false."
    }
]

Comments

2

You can use the combination of Joi and middleware to validate all your parameters. For example if you want to validate ProductName from the request body,

const validateParams = function (paramSchema) {
    return async (req, res, next) => {
        const schema = Joi.object().keys(paramSchema);
        try{
            await Joi.validate(paramSchema, schema);
        } catch (err) {
            return res.send(400, {
                status: 400,
                result: err.details[0].message
            });
        }
        next();
    }
};

function routeFunction (req, res, next) {
    // do anything you want to
}
server.post(`${routeURI}/abc`, validateParams({
        ProductName: Joi.string().required(),
    }), routeFunction);

Similarly, if you want to validate the response, you can create similar middleware and use Joi for the same purpose.

1 Comment

For more info read: ranvir.xyz/blog/…
0

You can use your own middleware function for validating the api. This link contains information about middle functions using express framework: http://expressjs.com/en/guide/using-middleware.html

You can use a middleware for POST request for your url or simply for POST request.

1 Comment

Better post core content rather than post an external link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.