PARSE DATA
Data Conversion

Data Conversion Process

The Parse Data middleware simplifies handling incoming request data by automatically converting strings into their corresponding JavaScript types. This process ensures that your application receives data in a structured and usable format, reducing the need for manual parsing and validation.

Conversion Rules

  1. String to Number:

    • If a string represents a numeric value (e.g., "42", "3.14"), it is converted to a Number.
    • Strings starting with 0 are treated as strings (e.g., "0123" remains "0123").
  2. String to Boolean:

    • If the string is "true" or "false", it is converted to a Boolean.
    • "true" becomes true (Boolean).
    • "false" becomes false (Boolean).
  3. String to Date:

    • If the string matches a valid date format (e.g., "2024-12-01T10:00:00.000Z"), it is converted to a Date object.
    • This is useful for handling fields that represent dates or timestamps.
  4. Unchanged Strings:

    • Any string that does not match the patterns above is kept as a String (e.g., "hello", "123abc", or special characters).

Example Conversions

Query Parameters

Request:

fetch("/query?string=value&integer=123&boolean=true")

Server-side:

vkrun.get("/query", (request: v.Request, response: v.Response) => {
  console.log(request.query)
  // Output: { string: "value", integer: 123, boolean: true }
  response.status(200).end()
})

URL Parameters

Request:

fetch("/params/42/example")

Server-side:

vkrun.get("/params/:id/:name", (request: v.Request, response: v.Response) => {
  console.log(request.params)
  // Output: { id: 42, name: "example" }
  response.status(200).end()
})

JSON Body

Request:

fetch("/data", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ count: "10", active: "true" })
})

Server-side:

vkrun.post("/data", (request: v.Request, response: v.Response) => {
  console.log(request.body)
  // Output: { count: 10, active: true }
  response.status(200).end()
})

By automating data conversion, the Parse Data middleware reduces repetitive tasks and enhances the maintainability of your application.

Copyright © 2024 MIT by Mario Elvio