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
-
String to Number:
- If a string represents a numeric value (e.g.,
"42"
,"3.14"
), it is converted to aNumber
. - Strings starting with 0 are treated as strings (e.g.,
"0123"
remains"0123"
).
- If a string represents a numeric value (e.g.,
-
String to Boolean:
- If the string is
"true"
or"false"
, it is converted to aBoolean
. "true"
becomestrue
(Boolean)."false"
becomesfalse
(Boolean).
- If the string is
-
String to Date:
- If the string matches a valid date format (e.g.,
"2024-12-01T10:00:00.000Z"
), it is converted to aDate
object. - This is useful for handling fields that represent dates or timestamps.
- If the string matches a valid date format (e.g.,
-
Unchanged Strings:
- Any string that does not match the patterns above is kept as a
String
(e.g.,"hello"
,"123abc"
, or special characters).
- Any string that does not match the patterns above is kept as a
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.