Skip to content

date field serialization crashes when null #218

Closed
@simoami

Description

@simoami

🐛 Bug Report

I have a timestamp field in my schema named 'updatedAt' and defined as follows:

{
  updatedAt: { type: ['string', null], format: 'date-time'}
}

When a record is created for the first time, the ORM return updatedAt with null, because only createdAt is set on record creation.

When it goes through serialization, I get the following error:

TypeError: Cannot read property 'toISOString' of null
     at $asDatetime (eval at build (/usr/src/app/node_modules/fast-json-stringify/index.js:142:20), <anonymous>:60:26)
     at $arr$mainusermembershipsi (eval at build (/usr/src/app/node_modules/fast-json-stringify/index.js:142:20), <anonymous>:554:17)
     at $arr$mainusermemberships (eval at build (/usr/src/app/node_modules/fast-json-stringify/index.js:142:20), <anonymous>:452:17)
     at $mainuser (eval at build (/usr/src/app/node_modules/fast-json-stringify/index.js:142:20), <anonymous>:403:17)
     at Object.$main (eval at build (/usr/src/app/node_modules/fast-json-stringify/index.js:142:20), <anonymous>:134:17)
     at serialize (/usr/src/app/node_modules/fastify/lib/validation.js:132:41)
     at preserializeHookEnd (/usr/src/app/node_modules/fastify/lib/reply.js:298:15)
    at next (/usr/src/app/node_modules/fastify/lib/hooks.js:101:7)
     at handleResolve (/usr/src/app/node_modules/fastify/lib/hooks.js:112:5)
     at process._tickCallback (internal/process/next_tick.js:68:7)

To Reproduce

Steps to reproduce the behavior:

The generated eval code strictly checks for underfined, so null is considered a valid value! Here's is what the generated code looks like:

if (obj['updatedAt'] !== undefined) {
  if (addComma) {
    json += ','
  }
  addComma = true
  json += '"updatedAt":'
  json += $asDatetime(obj['updatedAt'])
}

And since the function below doesn't check for null, the second condition date.toISOString triggers the error Cannot read property 'toISOString' because date itself is null!

function $asDatetime (date) {
 if (date instanceof Date) {
   return '"' + date.toISOString() + '"'
 } else if (typeof date.toISOString === 'function') {  <----- Error thrown here
   return '"' + date.toISOString() + '"'
 } else {
   return $asString(date)
 }
}

My suggestion is to make 2 changes as proposed below:

function $asDatetime (date) {
  if (date instanceof Date) {
    return '"' + date.toISOString() + '"'
  } else if (date && typeof date.toISOString' === 'function') {
    return '"' + date.toISOString() + '"'
  } else {
    return $asStringNullable(date)
  }
}

Your Environment

  • node version: 10
  • fastify version: 2.13.0
  • os: Mac and alpine (dockerized)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions