I wrote this middleware for express enabling developers to require certain parameters the easy way. How good is this approach? Can you call this quality code? Is everything OK, or is something missing?
Package: NPM
function getMissingPrams(reqParams, requiredParamsArray) {
//handling errors
if (!reqParams)
return new Error('send reqParams for the first argument')
if (!(requiredParamsArray instanceof Array))
return new Error('you must be using array for the second argument')
if (requiredParamsArray.length < 1)
return new Error('not found Required parameters')
//Assigning body keys to array optimizing performance
const reqParamsArray = Object.keys(reqParams);
//extracting the missing paramerters
const missedParams = requiredParamsArray.filter(param => !reqParamsArray.includes(param))
//here's the array of missedParams
return missedParams;
}
1 Answer 1
I'm assuming you're only wanting a review of the approach rather than the implementation. Otherwise, you would have placed the entire implementation in the question (which is required by Code Review if you wanted that reviewed).
Doing parameter checks on runtime is
- A performance cost
- Noise in the code
- Development overhead
If you want to ensure type safety while not sacrificing runtime performance, code readability, or precious developer time (and hair), it is best to move this responsibility off the runtime and to somewhere else. This is either at authoring time, compile time, or both. Your options are either:
To use a type hinting and linter setup, like JSDoc and ESLint. This is the least invasive way to enforce safety while still be able to write in vanilla JS.
Use a type-safe language, like TypeScript or Flow. You'll have to change how your code is written, but type-safety is built-in. You can also write code in TS, compile it to JS, and always be sure that JS is type-safe (and not care about the consuming end).
In either case, there are tools, plugins and editor add-ons that allow you to get immediate feedback on incorrect types (in-editor warnings) and fail the build if the types aren't adhered correctly. An added benefit is that the code is self-documenting, especially if you take the JSDoc route.
-
\$\begingroup\$ here's the code github.com/Microsmsm/require-params/blob/master/… \$\endgroup\$solimanware– solimanware2017年11月27日 23:00:32 +00:00Commented Nov 27, 2017 at 23:00
-
\$\begingroup\$ @Microsmsm "Make sure you include your code in your question" codereview.stackexchange.com/help/on-topic \$\endgroup\$Joseph– Joseph2017年11月28日 13:09:19 +00:00Commented Nov 28, 2017 at 13:09
-
\$\begingroup\$ it was but I don't know why anchor tags in gray I think that's why u thought it's normal text \$\endgroup\$solimanware– solimanware2017年11月28日 16:21:41 +00:00Commented Nov 28, 2017 at 16:21