Ad

Default Value Nodejs

In Spring Boot, in my controller method, I can check and assign default value like below in my controller method.

Instead of checking for if(query){}. In case the user doesn't call the endpoint with one of the NOT required parameters, how can I assign default values in express route like Spring boot.

router.get('/products', ProductController.getAllProducts);

//...
static async getAllProducts(req, res, next)
public ResponseEntity<Map<String, Object>> getAll(HttpServletRequest request,
            @RequestParam(name = "page", required = false, defaultValue = "1") @Min(1) Integer page,
            @RequestParam(name = "limit", required = false, defaultValue ="20") Integer limit,
            @RequestParam(name = "description_length", required = false, defaultValue = "200")
Ad

Answer

You might consider using schema validation libraries like joi for query schema validation/transformation:

Example with express-joi-validation:

// ...
const Joi = require('@hapi/joi');
const validator = require('express-joi-validation').createValidator({});

// ...

// If `page` is null, undefined, negative integer - set default value `0`
const querySchema = Joi.object({
  page: Joi.alternatives().try([
      Joi.number().integer().min(0),
      Joi.empty(Joi.any()).default(0),
  ])
});

// ...

router.get('/products', validator.query(querySchema), ProductController.getAllProducts);

// ...
Ad
source: stackoverflow.com
Ad