compile-json-stringify icon indicating copy to clipboard operation
compile-json-stringify copied to clipboard

[Feature Request]: Default option?

Open dalisoft opened this issue 4 years ago • 3 comments

Hi @nwoltman

Thanks for such a nice tool.

const cjs = compileJsonStringify({
  type: 'object',
  properties: {
    status: { type: 'string' },
    message: { type: 'string', default: 'OK' }, // <-- Default does not work
    data: {
      type: 'object',
      properties: {
        user: {
          type: 'object',
          properties: { id: { type: 'string' }, name: { type: 'string' } }
        }
      }
    }
  }
});


const data = {
  status: 'success',
  data: { user: { id: 'uuid', name: 'John' } }
};

cjs(data) // {"status":"success","data":{"user":{"id":"uuid","name":"John"}}}

Is there any way to get default work? Thanks

dalisoft avatar May 11 '21 18:05 dalisoft

Hi @dalisoft, I'm glad you're finding the module useful. The default option simply isn't implemented. If you wanted to you could try implementing it, but adding that feature comes with some hard decisions. If the default option were implemented, either:

  1. It wouldn't work with the additionalProperties option, or
  2. compileJsonStringify would have to do a bunch of extra work merging in the default properties when the additionalProperties option is true, which doesn't really fit in with the purpose of this module. That additional work might also be slower than setting the defaults yourself before using compileJsonStringify to stringify the object.

nwoltman avatar May 17 '21 02:05 nwoltman

@nwoltman Thanks for reply. I really want use this library as fast serializer to my node.js framework, but seems there some cons and a lot of users really does want use default property

dalisoft avatar May 20 '21 03:05 dalisoft

Being able to set defaults sounds useful enough that I'd accept a PR that adds the default property. Alternatively, you could try running the data through Ajv before using this library for serialization. That should work since the schema format that this library uses should be the same as Ajv, and I wouldn't expect Ajv to add much overhead.

nwoltman avatar May 24 '21 19:05 nwoltman