Validate your objects with Kasper
Recently I was working on a project which required me to make a bunch of external API calls to 3rd party services in my code flow to get a job done. My project also exposed its own APIs to be consumed by other teams within the company.
Now when you build APIs, you expect consumers to send data(say JSON) in correct format (agreed API contract). But this doesn’t happen always and fat finger errors also do pop up.
If a team sends { amount: “123” } instead of { amount: 123 } as a POST request body, then the code is prone to break at some later stage.

Javascript is not a statically typed language and variable type is determined at runtime. And to validate the arguments/response received, you do not want to write a bunch of if-else blocks each time.
So keep these things in mind as good practices:
- Validate the user input before entering the main logic of your program. If you find something not agreed upon, it is better to raise an error early.
- When you make external API calls, validate the response you receive. A small change in external service APIs can lead to unexpected cascading failure in your code that will require a lot of debugging.
- Before returning response to your consumers, validate if the response being sent is also in the correct format (API contract).
- Instead of responding with a 500-Internal server error, you could return a 400-Bad request error along with a descriptive error message so consumers can correct themselves without assistance.
To do these basic validations, I used an internal tool to which I have now published as NPM module with 100% test coverage.
https://www.npmjs.com/package/kasper
Some quick features:
- Supported types: string, number, boolean, null, error, array, date, object
- Partial schema validation: When you add keys to an object in steps and want to validate it against a final schema. Mostly use it when you do Object.assign and want to check if nothing is left undefined.
- Strict match: Object should strictly match the declared schema.
- Default values: In case a mismatch occurs, you can set a default value for that key. Very helpful in case of setting defaults (say port number) to configuration objects.
- Allowed/Not-allowed values: Check value of key to be in allowed values only and not any of the not-allowed (check for blank array/string) values.
Embed this validator into your code to make it more robust and easier to debug when unexpected changes occur. Also, I welcome your suggestions/additions/contributions to the package. The idea is to keep this package simple and not overload it with rarely used features.
